forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScheduledCleaner.swift
More file actions
62 lines (59 loc) · 2.47 KB
/
ScheduledCleaner.swift
File metadata and controls
62 lines (59 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import ActiveApplicationMonitor
import AppKit
import AXExtension
import Foundation
import Logger
public final class ScheduledCleaner {
public init() {
// occasionally cleanup workspaces.
Task { @ServiceActor in
while !Task.isCancelled {
try await Task.sleep(nanoseconds: 2 * 60 * 60 * 1_000_000_000)
let availableTabs = findAvailableOpenedTabs()
for (url, workspace) in workspaces {
if workspace.isExpired {
Logger.service.info("Remove idle workspace")
for url in workspace.filespaces.keys {
WidgetDataSource.shared.cleanup(for: url)
}
workspace.cleanUp(availableTabs: availableTabs)
workspaces[url] = nil
} else {
// cleanup chats for unused files
let filespaces = workspace.filespaces
for (url, _) in filespaces {
if workspace.isFilespaceExpired(
fileURL: url,
availableTabs: availableTabs
) {
Logger.service.info("Remove idle filespace")
WidgetDataSource.shared.cleanup(for: url)
}
}
// cleanup workspace
workspace.cleanUp(availableTabs: availableTabs)
}
}
}
}
}
func findAvailableOpenedTabs() -> Set<String> {
guard let xcode = ActiveApplicationMonitor.latestXcode else { return [] }
let app = AXUIElementCreateApplication(xcode.processIdentifier)
let windows = app.windows.filter { $0.identifier == "Xcode.WorkspaceWindow" }
guard !windows.isEmpty else { return [] }
var allTabs = Set<String>()
for window in windows {
guard let editArea = window.firstChild(where: { $0.description == "editor area" })
else { continue }
let tabBars = editArea.children { $0.description == "tab bar" }
for tabBar in tabBars {
let tabs = tabBar.children { $0.roleDescription == "tab" }
for tab in tabs {
allTabs.insert(tab.title)
}
}
}
return allTabs
}
}