sprag-cli 3.130.0 → 3.132.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/bin/cli.js +11 -1
  2. package/mac/SpragBar.swift +3141 -0
  3. package/mod/sprag-statusline/hooks/register.tsx +58 -3
  4. package/package.json +2 -1
  5. package/src/agent-activity.js +485 -0
  6. package/src/agent-detail.js +266 -0
  7. package/src/agent-usage.js +410 -0
  8. package/src/agent-warnings.js +128 -0
  9. package/src/bar-app.js +330 -0
  10. package/src/bar-rules.js +133 -0
  11. package/src/bar-settings.js +78 -0
  12. package/src/brief.js +40 -13
  13. package/src/caps-cache.js +4 -3
  14. package/src/claude-version.js +38 -0
  15. package/src/codex/budget.js +1 -1
  16. package/src/codex/delegation-diagnostics.js +1 -1
  17. package/src/codex/panel.js +1 -7
  18. package/src/commands/bar.js +370 -0
  19. package/src/commands/delegate.js +1 -0
  20. package/src/commands/feedback.js +2 -2
  21. package/src/commands/install.js +4 -1
  22. package/src/commands/last.js +1 -1
  23. package/src/commands/route-scan.js +39 -1
  24. package/src/commands/team.js +1 -1
  25. package/src/commands/uninstall.js +2 -0
  26. package/src/commands/upgrade.js +1 -1
  27. package/src/compact-window.js +1 -1
  28. package/src/cowork-sync.js +1 -1
  29. package/src/ctx-window-cache.js +11 -8
  30. package/src/delegation-agents.js +41 -2
  31. package/src/doc2md.cjs +1 -0
  32. package/src/gateway-auth.js +1 -0
  33. package/src/handoff.js +1 -0
  34. package/src/history.js +18 -1
  35. package/src/installer.js +43 -0
  36. package/src/korean-style.js +1 -1
  37. package/src/permission-secrets.js +1 -1
  38. package/src/session-cache.js +19 -0
  39. package/src/statusline-guard.js +17 -0
  40. package/src/team-sync.js +1 -1
  41. package/src/transcript-lines.js +1 -1
  42. package/src/window-labels.js +11 -0
@@ -0,0 +1,3141 @@
1
+ // Sprag Bar: the menu bar app that `sprag` starts on macOS.
2
+ //
3
+ // A runner in the menu bar moves faster the more of the machine the agent sessions use. A click opens a panel with every
4
+ // Claude Code and Codex session, the machine's CPU, memory and GPU split by who is using them, account limits, settings and
5
+ // rules. The dashboard window shows the same at full size.
6
+ //
7
+ // Session data comes from `sprag bar --json` (one child at a time, never overlapping). Machine totals, each process's CPU
8
+ // time and memory footprint, and GPU time per process come from the kernel and the I/O registry. A setting is changed by
9
+ // running the sprag command that owns it; this app writes no sprag file of its own except its pid file.
10
+ //
11
+ // The package ships this source, not a binary. `sprag bar build` compiles it on the user's Mac (src/bar-app.js):
12
+ // swiftc -O -swift-version 5 mac/SpragBar.swift -o sprag-bar
13
+ // Arguments: --node <node> --cli <bin/cli.js> [--data-dir <dir>] [--version-tag <v>] [--ttl <seconds>] [--trace]
14
+ // [--selftest <capture prefix> [--selftest-wait <seconds>] [--selftest-write]]
15
+ import AppKit
16
+ import SwiftUI
17
+ import Darwin
18
+ import IOKit
19
+
20
+ // ---------- data ----------
21
+ struct Win: Decodable { let key: String; let label: String; let usedPct: Double; let resetsAt: Double? }
22
+ struct Limits: Decodable { let plan: String?; let windows: [Win]; let at: Double? }
23
+ struct UsageTop: Decodable { let claude: Limits?; let codex: Limits? }
24
+ struct Ctx: Decodable { let tokens: Double; let window: Double?; let pct: Double? }
25
+ struct Tok: Decodable { let input: Double; let cacheRead: Double; let cacheWrite: Double; let output: Double }
26
+ struct SUsage: Decodable { let tokens: Tok; let requests: Double?; let costUsd: Double? }
27
+ struct DetailText: Decodable { let text: String; let at: Double? }
28
+ struct ToolCall: Decodable { let at: Double?; let tool: String; let target: String?; let pending: Bool? }
29
+ struct ProcItem: Decodable { let pid: Int; let name: String; let cpuPct: Double?; let rssMb: Double? }
30
+ struct Detail: Decodable { let prompt: DetailText?; let reply: DetailText?; let recent: [ToolCall]?; let procs: [ProcItem]? }
31
+ struct Session: Decodable, Identifiable {
32
+ let cwd: String?; let detail: Detail?
33
+ let agent: String; let pid: Int; let name: String?; let project: String?; let sessionId: String?
34
+ let state: String?; let stateSince: Double?; let tools: [String]; let subagents: Int
35
+ let cpu: Double?; let rssMb: Double?; let procs: Int?
36
+ let cpuPct: Double?; let model: String?; let modelName: String?; let effort: String?; let context: Ctx?; let usage: SUsage?
37
+ var id: Int { pid }
38
+ }
39
+ struct Totals: Decodable { let sessions: Int; let busy: Int; let subagents: Int; let cpu: Double?; let rssMb: Double?; let procs: Int?; let costUsd: Double? }
40
+ struct Animal: Decodable { let grade: String; let emoji: String }
41
+ struct NextS: Decodable { let grade: String; let emoji: String; let name: String; let floorPct: Double?; let pass: Double?; let needDlg: Bool? }
42
+ struct Standing: Decodable { let grade: String; let emoji: String; let name: String; let org: String?; let rank: Double?; let ranked: Double?; let crown: Bool?; let idle: Bool?; let scorePct: Double?; let spendRank: Double?; let dlgRank: Double?; let next: NextS? }
43
+ struct Act: Decodable { let label: String?; let commands: [String]? }
44
+ struct Advice: Decodable, Identifiable { let code: String; let title: String?; let explain: String?; let tip: String?; let actions: [Act]?; var id: String { code } }
45
+ struct Warn: Decodable, Identifiable { let kind: String; let chip: String; let level: String; let since: Double?; let detail: String?; let resetsAt: Double?; let advice: [Advice]?; var id: String { chip } }
46
+ struct Snapshot: Decodable { let at: Double; let resources: Bool; let animal: Animal?; let totals: Totals; let sessions: [Session]; let cores: Int?; let usage: UsageTop?; let warnings: [Warn]?; let standing: Standing? }
47
+ struct Sample { var sysCpu = 0.0, claudeCpu = 0.0, codexCpu = 0.0, sysMem = 0.0, claudeMem = 0.0, codexMem = 0.0, gpu = 0.0, at = 0.0, cost = 0.0, claudeGpu = 0.0, codexGpu = 0.0, leftCpu = 0.0, leftMem = 0.0 }
48
+ struct Hist { let at: Double; let cpu: Double; let mem: Double; let gpu: Double } // one reading of one session, for its trend lines // each a fraction of the whole machine
49
+
50
+ struct RoutingS: Decodable { var enabled: Bool; var relaxed: Bool; var relaxUntil: Double? }
51
+ struct StatuslineS: Decodable { var compact: Int; var labels: String; var timer: Bool }
52
+ struct TeamS: Decodable { var joined: Bool; var teamName: String?; var displayName: String? }
53
+ struct CompactS: Decodable { var is1m: Bool; var value: Double?; var auto: Bool; var source: String?; var modelKey: String?; var ok: Bool; var reason: String; var recommended: Double; var min: Double; var max: Double; var warn: Bool }
54
+ struct Settings: Decodable { var routing: RoutingS; var statusline: StatuslineS; var language: String; var team: TeamS; var compactWindow: CompactS? }
55
+ struct RuleItem: Decodable { let index: Int; let text: String; let date: String?; let tags: [String]? }
56
+ struct RuleFile: Decodable { let path: String?; let exists: Bool; let bytes: Int; let tokens: Int; let rules: [RuleItem] }
57
+ struct ProjectRules: Decodable { let root: String; let name: String; let path: String?; let exists: Bool; let bytes: Int; let tokens: Int; let rules: [RuleItem] }
58
+ struct PresetItem: Decodable { let id: String; let text: String }
59
+ struct PresetRules: Decodable { let path: String?; let rules: [PresetItem]; let pending: [PresetItem] }
60
+ struct ModelRule: Decodable { let index: Int; let scope: String?; let root: String?; let label: String?; let tier: String?; let status: String?; let text: String; let example: String?; let count: Double?; let savedUsd: Double? }
61
+ struct ModelRules: Decodable { let enabled: Bool; let rules: [ModelRule] }
62
+ struct TeamRule: Decodable { let id: String?; let level: String; let scope: String; let text: String }
63
+ struct TeamRules: Decodable { let joined: Bool; let rules: [TeamRule] }
64
+ struct Rules: Decodable { let budgetTokens: Int; let global: RuleFile; let projects: [ProjectRules]; let preset: PresetRules; let model: ModelRules; let team: TeamRules }
65
+ enum Page: Equatable { case status, settings, rules, warning(String), session(Int) }
66
+ /** Which page the panel shows. */
67
+ final class Nav: ObservableObject {
68
+ @Published var page: Page = .status { didSet { if page != oldValue { onChange?(page) } } }
69
+ var onChange: ((Page) -> Void)?
70
+ }
71
+ /** Fit the window to its content again. Set by the app; called whenever a page grows or shrinks. */
72
+ var RELAYOUT: () -> Void = {}
73
+ func firstLine(_ t: String) -> String { t.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) }.first { !$0.isEmpty } ?? "" }
74
+ func stripAnsi(_ t: String) -> String { t.replacingOccurrences(of: "\u{001B}\\[[0-9;?]*[A-Za-z]", with: "", options: .regularExpression) }
75
+ struct Opt: Identifiable { let id: String; let label: String; init(_ id: String, _ label: String) { self.id = id; self.label = label } }
76
+
77
+ var NODE = "/opt/homebrew/bin/node", CLI = "", TRACE = false
78
+ let CORES = Double(ProcessInfo.processInfo.activeProcessorCount)
79
+ let RAM_MB = Double(ProcessInfo.processInfo.physicalMemory) / 1048576
80
+ /** One process's time on the GPU since the last reading, as a fraction of the time that passed, and the session it runs under. */
81
+ struct GpuUse: Identifiable { let pid: Int32; let name: String; let share: Double; let session: Int?; var left = false; var id: Int32 { pid } }
82
+ struct GpuLine: Identifiable { let id: String; let label: String; let note: String; let share: Double; let agent: String?; var pid: Int? = nil }
83
+ /**
84
+ * GPU time each process has used since it opened the GPU, in ns. The GPU driver keeps one entry per client process in the
85
+ * I/O registry with its creator ("pid 404, name") and its accumulated GPU time; Activity Monitor's GPU column reads the same.
86
+ */
87
+ func gpuClients() -> [Int32: (name: String, ns: Double)] {
88
+ var out: [Int32: (name: String, ns: Double)] = [:]
89
+ var it: io_iterator_t = 0
90
+ guard IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOAccelerator"), &it) == KERN_SUCCESS else { return out }
91
+ defer { IOObjectRelease(it) }
92
+ var acc = IOIteratorNext(it)
93
+ while acc != 0 {
94
+ var kids: io_iterator_t = 0
95
+ if IORegistryEntryGetChildIterator(acc, kIOServicePlane, &kids) == KERN_SUCCESS {
96
+ var c = IOIteratorNext(kids)
97
+ while c != 0 {
98
+ if let who = IORegistryEntryCreateCFProperty(c, "IOUserClientCreator" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? String, who.hasPrefix("pid "),
99
+ let usage = IORegistryEntryCreateCFProperty(c, "AppUsage" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? [[String: Any]] {
100
+ let parts = who.dropFirst(4).split(separator: ",", maxSplits: 1)
101
+ if let pid = Int32(parts.first.map(String.init) ?? "") {
102
+ let ns = usage.reduce(0.0) { $0 + (($1["accumulatedGPUTime"] as? NSNumber)?.doubleValue ?? 0) }
103
+ var e = out[pid] ?? (name: parts.count > 1 ? parts[1].trimmingCharacters(in: .whitespaces) : "", ns: 0)
104
+ e.ns += ns; out[pid] = e
105
+ }
106
+ }
107
+ IOObjectRelease(c); c = IOIteratorNext(kids)
108
+ }
109
+ IOObjectRelease(kids)
110
+ }
111
+ IOObjectRelease(acc); acc = IOIteratorNext(it)
112
+ }
113
+ return out
114
+ }
115
+ func parentPid(_ pid: Int32) -> Int32? {
116
+ var info = proc_bsdinfo()
117
+ let size = Int32(MemoryLayout<proc_bsdinfo>.size)
118
+ return proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, size) == size ? Int32(info.pbi_ppid) : nil
119
+ }
120
+ /** The session a process runs under: its nearest ancestor that is a session's own process. Another user's process cannot be read and has none. */
121
+ func sessionOf(_ pid: Int32, _ roots: Set<Int>) -> Int? {
122
+ var cur = pid, hops = 0
123
+ while cur > 1 && hops < 64 {
124
+ if roots.contains(Int(cur)) { return Int(cur) }
125
+ guard let up = parentPid(cur) else { return nil }
126
+ cur = up; hops += 1
127
+ }
128
+ return nil
129
+ }
130
+ /** A process's working folder. */
131
+ func procCwd(_ pid: Int32) -> String? {
132
+ var info = proc_vnodepathinfo()
133
+ let size = Int32(MemoryLayout<proc_vnodepathinfo>.size)
134
+ guard proc_pidinfo(pid, PROC_PIDVNODEPATHINFO, 0, &info, size) == size else { return nil }
135
+ return withUnsafePointer(to: &info.pvi_cdir.vip_path) { $0.withMemoryRebound(to: CChar.self, capacity: Int(MAXPATHLEN)) { String(cString: $0) } }
136
+ }
137
+ /** The executable's file name; the registry cuts names at 16 characters. */
138
+ func procName(_ pid: Int32, _ fallback: String) -> String {
139
+ var buf = [CChar](repeating: 0, count: 4096)
140
+ return proc_pidpath(pid, &buf, UInt32(buf.count)) > 0 ? (String(cString: buf) as NSString).lastPathComponent : fallback
141
+ }
142
+ /** One process: CPU time used so far in ns, and its memory footprint in MB (resident, compressed and GPU-backed pages: Activity Monitor's Memory column). */
143
+ struct Proc { let pid: Int32; let ppid: Int32; let name: String; let start: UInt64; let cpuNs: Double; let memMb: Double }
144
+ struct Load { var cpu = 0.0, mem = 0.0, n = 0; mutating func add(_ c: Double, _ m: Double) { cpu += c; mem += m; n += 1 } } // cpu: fraction of the whole machine
145
+ /** A session's load: its own process tree, and what it started detached (re-parented to launchd, so no longer under it). */
146
+ struct Work { var cpu = 0.0, mem = 0.0, gpu = 0.0, n = 0; mutating func add(_ c: Double, _ m: Double) { cpu += c; mem += m; n += 1 } }
147
+ struct Usage { var tree = Load(), detached = Load(); var names: [String: Load] = [:]; var work: [String: Work] = [:] } // work: its programs by name, the agent itself left out
148
+ enum Phase: Int { case needsUser = 0, active = 1, idle = 2 }
149
+ struct AppLoad: Identifiable { let id: String; let name: String; let cpu: Double; let mem: Double; let n: Int }
150
+ let TIMEBASE: Double = { var t = mach_timebase_info_data_t(); mach_timebase_info(&t); return Double(t.numer) / Double(max(1, t.denom)) }()
151
+ /** Every process of this user. Another user's processes cannot be measured without privileges; they count in the machine totals only. */
152
+ func census() -> [Int32: Proc] {
153
+ let n = proc_listallpids(nil, 0)
154
+ guard n > 0 else { return [:] }
155
+ var pids = [Int32](repeating: 0, count: Int(n) + 128)
156
+ let got = proc_listallpids(&pids, Int32(pids.count * MemoryLayout<Int32>.size))
157
+ let me = getuid(), size = Int32(MemoryLayout<proc_bsdinfo>.size)
158
+ var out: [Int32: Proc] = [:]
159
+ for pid in pids.prefix(Int(max(0, got))) where pid > 1 {
160
+ var info = proc_bsdinfo()
161
+ guard proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, size) == size, info.pbi_uid == me else { continue }
162
+ var ri = rusage_info_v2()
163
+ let ok = withUnsafeMutablePointer(to: &ri) { $0.withMemoryRebound(to: rusage_info_t?.self, capacity: 1) { proc_pid_rusage(pid, RUSAGE_INFO_V2, $0) } } == 0
164
+ var name = withUnsafePointer(to: &info.pbi_name) { $0.withMemoryRebound(to: CChar.self, capacity: 33) { String(cString: $0) } }
165
+ if name.isEmpty { name = withUnsafePointer(to: &info.pbi_comm) { $0.withMemoryRebound(to: CChar.self, capacity: 17) { String(cString: $0) } } }
166
+ out[pid] = Proc(pid: pid, ppid: Int32(info.pbi_ppid), name: name, start: info.pbi_start_tvsec,
167
+ cpuNs: ok ? Double(ri.ri_user_time + ri.ri_system_time) * TIMEBASE : 0, memMb: ok ? Double(ri.ri_phys_footprint) / 1048576 : 0)
168
+ }
169
+ return out
170
+ }
171
+ var ARGBUF = [UInt8](repeating: 0, count: 1_048_576)
172
+ let SID_KEY = Array("CLAUDE_CODE_SESSION_ID=".utf8), PID_KEY = Array("CLAUDE_PID=".utf8), APP_KEY = Array("__CFBundleIdentifier=".utf8)
173
+ /**
174
+ * The Claude session that started a process. Claude Code puts its session id and its own pid in the environment of every
175
+ * child, and a child that was detached keeps them. Only those two values are read; nothing else of the environment is kept.
176
+ */
177
+ func claudeOrigin(_ pid: Int32) -> (sid: String?, cpid: Int32?, title: String?, bundle: String?, vars: Int) {
178
+ var mib: [Int32] = [CTL_KERN, KERN_PROCARGS2, pid]
179
+ var size = ARGBUF.count
180
+ guard sysctl(&mib, 3, &ARGBUF, &size, nil, 0) == 0, size > 8 else { return (nil, nil, nil, nil, 0) }
181
+ let argc = ARGBUF.withUnsafeBytes { $0.load(as: Int32.self) }
182
+ var i = 4
183
+ while i < size && ARGBUF[i] != 0 { i += 1 } // the executable path
184
+ while i < size && ARGBUF[i] == 0 { i += 1 }
185
+ var left = argc, argv: [String] = []
186
+ while left > 0 && i < size {
187
+ let at = i
188
+ while i < size && ARGBUF[i] != 0 { i += 1 }
189
+ if argv.count < 4 { argv.append(String(decoding: ARGBUF[at..<min(i, at + 200)], as: UTF8.self)) }
190
+ i += 1; left -= 1
191
+ }
192
+ // What the process is running, for programs whose own name says little (node, Python, a shell): the script, never its options.
193
+ var title: String? = nil
194
+ if let first = argv.first {
195
+ let words = first.split(separator: " ")
196
+ if words.count > 1 { title = words.prefix(4).joined(separator: " ") }
197
+ else if let script = argv.dropFirst().first(where: { !$0.hasPrefix("-") && !$0.contains("=") }) { title = "\((first as NSString).lastPathComponent) \((script as NSString).lastPathComponent)" }
198
+ }
199
+ var sid: String? = nil, cpid: Int32? = nil, bundle: String? = nil, vars = 0
200
+ func has(_ key: [UInt8], _ at: Int, _ end: Int) -> Bool { guard end - at > key.count else { return false }; for k in 0..<key.count where ARGBUF[at + k] != key[k] { return false }; return true }
201
+ while i < size {
202
+ let at = i
203
+ while i < size && ARGBUF[i] != 0 { i += 1 }
204
+ if i == at { break }
205
+ vars += 1
206
+ if has(SID_KEY, at, i) { sid = String(decoding: ARGBUF[(at + SID_KEY.count)..<i], as: UTF8.self) }
207
+ else if has(PID_KEY, at, i) { cpid = Int32(String(decoding: ARGBUF[(at + PID_KEY.count)..<i], as: UTF8.self)) }
208
+ else if has(APP_KEY, at, i) { bundle = String(decoding: ARGBUF[(at + APP_KEY.count)..<i], as: UTF8.self) }
209
+ i += 1
210
+ }
211
+ return (sid, cpid, title.map { String($0.prefix(34)) }, bundle, vars)
212
+ }
213
+ /** The program the system holds responsible for a process: the app behind a virtual machine or an XPC helper. Optional: without it those helpers count as other programs. */
214
+ typealias ResponsibleFn = @convention(c) (pid_t) -> pid_t
215
+ let RESPONSIBLE: ResponsibleFn? = {
216
+ guard let sym = dlsym(UnsafeMutableRawPointer(bitPattern: -2), "responsibility_get_pid_responsible_for_pid") else { return nil }
217
+ return unsafeBitCast(sym, to: ResponsibleFn.self)
218
+ }()
219
+ let PLAIN_NAMES: Set<String> = ["node", "bash", "sh", "zsh", "ruby", "java", "perl", "npm", "npx", "deno", "bun", "tsx"]
220
+ /**
221
+ * The app a session runs in. Its first ancestor that is a regular (Dock) application; when the chain ends at a daemon
222
+ * instead (a terminal that keeps its shells in a background host, or tmux), the app named in the session's own
223
+ * environment, which the system sets to the bundle that launched the shell.
224
+ */
225
+ func owningApp(_ pid: Int) -> NSRunningApplication? {
226
+ var cur = Int32(pid), hops = 0
227
+ while cur > 1 && hops < 64 {
228
+ if let app = NSRunningApplication(processIdentifier: cur), app.activationPolicy == .regular { return app }
229
+ guard let up = parentPid(cur) else { break }
230
+ cur = up; hops += 1
231
+ }
232
+ guard let bundle = claudeOrigin(Int32(pid)).bundle, !bundle.isEmpty else { return nil }
233
+ return NSRunningApplication.runningApplications(withBundleIdentifier: bundle).first { $0.activationPolicy == .regular }
234
+ }
235
+ /** Named variables from a process's environment, read the same way as claudeOrigin. Only the names asked for are kept. */
236
+ func envValues(_ pid: Int32, _ names: [String]) -> [String: String] {
237
+ var mib: [Int32] = [CTL_KERN, KERN_PROCARGS2, pid]
238
+ var size = ARGBUF.count
239
+ guard sysctl(&mib, 3, &ARGBUF, &size, nil, 0) == 0, size > 8 else { return [:] }
240
+ var left = ARGBUF.withUnsafeBytes { $0.load(as: Int32.self) }, i = 4
241
+ while i < size && ARGBUF[i] != 0 { i += 1 }
242
+ while i < size && ARGBUF[i] == 0 { i += 1 }
243
+ while left > 0 && i < size { while i < size && ARGBUF[i] != 0 { i += 1 }; i += 1; left -= 1 }
244
+ var out: [String: String] = [:]
245
+ while i < size {
246
+ let at = i
247
+ while i < size && ARGBUF[i] != 0 { i += 1 }
248
+ if i == at { break }
249
+ if ARGBUF[at] == 0x4f || ARGBUF[at] == 0x54 { // only lines starting with O or T are decoded at all
250
+ let line = String(decoding: ARGBUF[at..<i], as: UTF8.self)
251
+ if let eq = line.firstIndex(of: "="), names.contains(String(line[..<eq])) { out[String(line[..<eq])] = String(line[line.index(after: eq)...]) }
252
+ }
253
+ i += 1
254
+ }
255
+ return out
256
+ }
257
+ /** The terminal tab a session lives in, when its terminal can be told to show one. Orca gives every shell a handle and ships a command that switches to it. */
258
+ func exactTab(_ s: Session) -> (tool: String, args: [String])? {
259
+ let env = envValues(Int32(s.pid), ["ORCA_TERMINAL_HANDLE", "ORCA_CLI_BIN_DIR"])
260
+ guard let handle = env["ORCA_TERMINAL_HANDLE"], handle.hasPrefix("term_"), handle.count < 80, handle.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "_" || $0 == "-" }),
261
+ let dir = env["ORCA_CLI_BIN_DIR"], dir.hasSuffix(".app/Contents/Resources/bin"), FileManager.default.isExecutableFile(atPath: dir + "/orca") else { return nil }
262
+ return (dir + "/orca", ["terminal", "switch", "--terminal", handle])
263
+ }
264
+ /** Go to a session: show its tab where the terminal allows it, then bring the terminal app to the front. */
265
+ func jump(to s: Session) {
266
+ if let tab = exactTab(s) {
267
+ let p = Process(); p.executableURL = URL(fileURLWithPath: tab.tool); p.arguments = tab.args
268
+ p.standardOutput = FileHandle.nullDevice; p.standardError = FileHandle.nullDevice
269
+ try? p.run()
270
+ }
271
+ owningApp(s.pid)?.activate(options: [.activateAllWindows])
272
+ }
273
+ /** A name a person recognises: the app for anything inside an .app bundle, else the executable's file name. */
274
+ func appName(_ pid: Int32, _ fallback: String) -> String {
275
+ var buf = [CChar](repeating: 0, count: 4096)
276
+ guard proc_pidpath(pid, &buf, UInt32(buf.count)) > 0 else { return fallback }
277
+ let path = String(cString: buf)
278
+ if let r = path.range(of: ".app/") { return (String(path[..<r.lowerBound]) as NSString).lastPathComponent }
279
+ return (path as NSString).lastPathComponent
280
+ }
281
+ /**
282
+ * Programs that are not swept up with the rest when leftovers are cleaned: apps, virtual machines and databases. Other
283
+ * work may depend on them (a Docker that an ended session started can be serving every project's local database), and
284
+ * some hold data that a plain stop signal would cut off. They are stopped from their own app.
285
+ */
286
+ /**
287
+ * True when a process holds a TCP connection that is open both ways: something is talking to it, or it to something.
288
+ * A dev server with a browser or a simulator attached is the case this is for.
289
+ */
290
+ func hasOpenConnection(_ pid: Int32) -> Bool {
291
+ let size = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, nil, 0)
292
+ guard size > 0 else { return false }
293
+ var fds = [proc_fdinfo](repeating: proc_fdinfo(), count: Int(size) / MemoryLayout<proc_fdinfo>.size)
294
+ let got = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, &fds, size)
295
+ guard got > 0 else { return false }
296
+ let want = Int32(MemoryLayout<socket_fdinfo>.size)
297
+ for fd in fds.prefix(Int(got) / MemoryLayout<proc_fdinfo>.size) where fd.proc_fdtype == 2 { // PROX_FDTYPE_SOCKET
298
+ var info = socket_fdinfo()
299
+ guard proc_pidfdinfo(pid, fd.proc_fd, PROC_PIDFDSOCKETINFO, &info, want) == want else { continue }
300
+ if info.psi.soi_kind == 2 && info.psi.soi_proto.pri_tcp.tcpsi_state == 4 { return true } // SOCKINFO_TCP, TSI_S_ESTABLISHED
301
+ }
302
+ return false
303
+ }
304
+ func isSharedService(_ p: Proc) -> Bool {
305
+ var buf = [CChar](repeating: 0, count: 4096)
306
+ let path = proc_pidpath(p.pid, &buf, UInt32(buf.count)) > 0 ? String(cString: buf) : ""
307
+ // An app bundle, but not the launcher a language runtime keeps inside its framework (Python.framework/.../Python.app):
308
+ // a script run with that is an ordinary leftover.
309
+ // A helper deep inside an app (Xcode.app/.../Some.framework/...) still counts as that app.
310
+ if let app = path.range(of: ".app/") {
311
+ let fw = path.range(of: ".framework/")
312
+ if fw == nil || app.lowerBound < fw!.lowerBound { return true }
313
+ }
314
+ let name = ((path as NSString).lastPathComponent + " " + p.name).lowercased()
315
+ return ["docker", "qemu", "virtualization", "colima", "podman", "postgres", "mysqld", "mongod", "redis-server", "simulator"].contains { name.contains($0) }
316
+ }
317
+ struct SessionGroup: Identifiable { let id: String; let name: String; let sessions: [Session] }
318
+ /**
319
+ * Sessions of one project together: grouped by working folder, in the order the first of each group came, and a session
320
+ * that another session started sits in its starter's group, right after it.
321
+ */
322
+ func groupSessions(_ sessions: [Session], parents: [Int: Int]) -> [SessionGroup] {
323
+ let byPid = Dictionary(sessions.map { ($0.pid, $0) }, uniquingKeysWith: { a, _ in a })
324
+ func top(_ s: Session) -> Session { var cur = s, hops = 0; while let p = parents[cur.pid], let up = byPid[p], hops < 16 { cur = up; hops += 1 }; return cur }
325
+ var order: [String] = [], members: [String: [Session]] = [:], names: [String: String] = [:]
326
+ for s in sessions {
327
+ let t = top(s), key = t.cwd ?? "pid:\(t.pid)"
328
+ if members[key] == nil { order.append(key); names[key] = t.project ?? t.cwd.map { ($0 as NSString).lastPathComponent } ?? t.name ?? t.agent }
329
+ members[key, default: []].append(s)
330
+ }
331
+ return order.map { key in
332
+ let all = members[key] ?? []
333
+ var out: [Session] = []
334
+ func add(_ s: Session) { guard !out.contains(where: { $0.pid == s.pid }) else { return }; out.append(s); for c in all where parents[c.pid] == s.pid { add(c) } }
335
+ for s in all where parents[s.pid].flatMap({ byPid[$0] }) == nil { add(s) }
336
+ for s in all { add(s) }
337
+ return SessionGroup(id: key, name: names[key] ?? key, sessions: out)
338
+ }
339
+ }
340
+ let LEFT = Color(red: 0.56, green: 0.52, blue: 0.91) // what ended sessions left running
341
+ let CARD_FILL = Color(nsColor: NSColor(name: nil) { $0.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua ? NSColor.black.withAlphaComponent(0.22) : NSColor.white.withAlphaComponent(0.62) })
342
+ /** One whole split by who is using it, on a known scale: parts in order, the rest of the track empty. */
343
+ struct SplitBar: View {
344
+ let parts: [(value: Double, color: Color)]; let scale: Double
345
+ var body: some View {
346
+ let full = max(scale, parts.reduce(0) { $0 + $1.value }, 0.000001)
347
+ GeometryReader { g in
348
+ HStack(spacing: 2) {
349
+ ForEach(Array(parts.enumerated()), id: \.offset) { _, p in if p.value > 0 { Rectangle().fill(p.color).frame(width: max(3, (g.size.width - 2 * CGFloat(parts.count)) * CGFloat(p.value / full))) } }
350
+ Rectangle().fill(Color.primary.opacity(0.12)).frame(maxWidth: .infinity)
351
+ }.clipShape(Capsule())
352
+ }.frame(height: 8)
353
+ }
354
+ }
355
+ let CLAUDE = Color(red: 0.85, green: 0.47, blue: 0.34), CODEX = Color(red: 0.06, green: 0.64, blue: 0.50)
356
+ func agentTint(_ agent: String) -> Color { agent == "codex" ? CODEX : CLAUDE }
357
+
358
+ final class Box { var data = Data() }
359
+ /** Run the sprag CLI once and hand its exit code, stdout and stderr to `done` on the main queue. It is killed after `timeout` seconds. */
360
+ func sprag(_ args: [String], timeout: Double, cwd: String? = nil, _ done: @escaping (Int32, String, String) -> Void) {
361
+ let p = Process(); p.executableURL = URL(fileURLWithPath: NODE); p.arguments = [CLI] + args
362
+ // Not the folder the app was started from: `sprag routing` re-renders the rule file of the project it runs in.
363
+ // A project rule command has to run inside its project, which is the only time `cwd` is given.
364
+ p.currentDirectoryURL = URL(fileURLWithPath: cwd ?? ProcessInfo.processInfo.environment["HOME"] ?? NSHomeDirectory())
365
+ let out = Pipe(), err = Pipe(); p.standardOutput = out; p.standardError = err; p.standardInput = FileHandle.nullDevice
366
+ DispatchQueue.global(qos: .userInitiated).async {
367
+ let o = Box(), e = Box(); var code: Int32 = -1
368
+ do {
369
+ try p.run()
370
+ let killer = DispatchWorkItem { if p.isRunning { p.terminate() } }
371
+ DispatchQueue.global().asyncAfter(deadline: .now() + timeout, execute: killer)
372
+ let g = DispatchGroup(); g.enter()
373
+ DispatchQueue.global().async { e.data = err.fileHandleForReading.readDataToEndOfFile(); g.leave() } // both pipes drained at once
374
+ o.data = out.fileHandleForReading.readDataToEndOfFile(); g.wait(); p.waitUntilExit(); killer.cancel(); code = p.terminationStatus
375
+ } catch { e.data = Data("실행하지 못했습니다: \(error.localizedDescription)".utf8) }
376
+ DispatchQueue.main.async { done(code, String(decoding: o.data, as: UTF8.self), String(decoding: e.data, as: UTF8.self)) }
377
+ }
378
+ }
379
+
380
+ /** Whole-machine CPU and memory, the figures Activity Monitor shows. */
381
+ final class Machine {
382
+ private var last: [UInt64]?
383
+ func cpu() -> Double? { // fraction busy since the previous call
384
+ var info = host_cpu_load_info_data_t()
385
+ var count = mach_msg_type_number_t(MemoryLayout<host_cpu_load_info_data_t>.stride / MemoryLayout<integer_t>.stride)
386
+ let kr = withUnsafeMutablePointer(to: &info) { p in p.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, $0, &count) } }
387
+ guard kr == KERN_SUCCESS else { return nil }
388
+ let now = [UInt64(info.cpu_ticks.0), UInt64(info.cpu_ticks.1), UInt64(info.cpu_ticks.2), UInt64(info.cpu_ticks.3)] // user, system, idle, nice
389
+ defer { last = now }
390
+ guard let before = last else { return nil }
391
+ let d = zip(now, before).map { $0 >= $1 ? Double($0 - $1) : 0 }
392
+ let total = d.reduce(0, +)
393
+ return total > 0 ? (d[0] + d[1] + d[3]) / total : nil
394
+ }
395
+ /** GPU load of the whole machine and the memory the GPU holds. macOS publishes no per-process figure, so it cannot be split by session. */
396
+ func gpu() -> (load: Double, memMb: Double)? {
397
+ var it: io_iterator_t = 0
398
+ guard IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOAccelerator"), &it) == KERN_SUCCESS else { return nil }
399
+ defer { IOObjectRelease(it) }
400
+ var best: (Double, Double)?
401
+ var e = IOIteratorNext(it)
402
+ while e != 0 {
403
+ var props: Unmanaged<CFMutableDictionary>?
404
+ if IORegistryEntryCreateCFProperties(e, &props, kCFAllocatorDefault, 0) == KERN_SUCCESS, let d = props?.takeRetainedValue() as? [String: Any],
405
+ let st = d["PerformanceStatistics"] as? [String: Any], let u = st["Device Utilization %"] as? NSNumber {
406
+ let m = (st["In use system memory"] as? NSNumber)?.doubleValue ?? 0
407
+ if best == nil || u.doubleValue > best!.0 { best = (u.doubleValue, m / 1048576) }
408
+ }
409
+ IOObjectRelease(e); e = IOIteratorNext(it)
410
+ }
411
+ return best.map { (load: min(1, max(0, $0.0 / 100)), memMb: $0.1) }
412
+ }
413
+ func memUsedMb() -> Double? {
414
+ var stats = vm_statistics64_data_t()
415
+ var count = mach_msg_type_number_t(MemoryLayout<vm_statistics64_data_t>.stride / MemoryLayout<integer_t>.stride)
416
+ let kr = withUnsafeMutablePointer(to: &stats) { p in p.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { host_statistics64(mach_host_self(), HOST_VM_INFO64, $0, &count) } }
417
+ guard kr == KERN_SUCCESS else { return nil }
418
+ var page: vm_size_t = 0; host_page_size(mach_host_self(), &page)
419
+ let app = Double(stats.internal_page_count) - Double(stats.purgeable_count)
420
+ return (max(0, app) + Double(stats.wire_count) + Double(stats.compressor_page_count)) * Double(page) / 1048576
421
+ }
422
+ }
423
+
424
+ final class Model: ObservableObject {
425
+ @Published var snap: Snapshot?
426
+ @Published var samples: [Sample] = []
427
+ @Published var failure: String?
428
+ @Published var sysCpu: Double?
429
+ @Published var sysMemMb: Double?
430
+ @Published var gpu: Double? // fraction of the whole machine's GPU in use
431
+ @Published var gpuMemMb: Double?
432
+ @Published var gpuUse: [GpuUse] = [] // who has been on the GPU since the last reading, largest first
433
+ var gpuBySession: [Int: Double] = [:] // session pid: its processes' share of that time
434
+ var parentSession: [Int: Int] = [:] // a session started from inside another session, child pid: starter pid
435
+ private var gpuSeen: [Int32: Double] = [:]
436
+ private var gpuSeenAt = 0.0
437
+ @Published var usage: [Int: Usage] = [:] // by session pid, from this app's own count of processes
438
+ var leftover = Load() // processes a Claude session started that are still running after it ended
439
+ var leftoverItems: [AppLoad] = []
440
+ var others: [AppLoad] = [] // this user's other programs, grouped by app
441
+ var censusReady = false // CPU is a difference, so it needs two readings
442
+ private var cpuSeen: [Int32: Double] = [:]
443
+ private var cpuSeenAt = 0.0
444
+ private var origins: [Int32: (start: UInt64, sid: String?, cpid: Int32?, title: String?, readable: Bool)] = [:]
445
+ private var inherited: [Int32: (start: UInt64, sid: String?, cpid: Int32?)] = [:] // a top whose own environment is hidden: what a descendant said
446
+ var ownerOf: [Int32: Int] = [:] // process: the session it is charged to, or -1 for one an ended session left
447
+ var labelOf: [Int32: String] = [:] // process of a live session: the name its load is listed under
448
+ var leftoverPids: [String: [(pid: Int32, start: UInt64)]] = [:] // each leftover line: its processes, with the start time that identifies them
449
+ var leftoverShared: Set<String> = [] // leftover lines that are apps, virtual machines or databases: never part of a clean-up
450
+ var leftoverWhere: [String: String] = [:] // each leftover line: the folder it runs in, which names the project its session worked on
451
+ /** The leftover lines that hold an open connection right now. Read when the clean-up choices open, not on every poll. */
452
+ func leftoverBusy(_ labels: [String]) -> Set<String> {
453
+ Set(labels.filter { label in (leftoverPids[label] ?? []).contains { hasOpenConnection($0.pid) } })
454
+ }
455
+ private var bornOf: [Int: (sid: String?, cpid: Int32?)] = [:] // session pid: the session marker it was started with
456
+ private var appNames: [Int32: (start: UInt64, name: String)] = [:]
457
+ private var running = false
458
+ var hist: [Int: [Hist]] = [:] // per session pid, the last 60 readings
459
+ private func origin(_ p: Proc) -> (sid: String?, cpid: Int32?, title: String?, readable: Bool) {
460
+ if let o = origins[p.pid], o.start == p.start { return (o.sid, o.cpid, o.title, o.readable) }
461
+ let o = claudeOrigin(p.pid); origins[p.pid] = (p.start, o.sid, o.cpid, o.title, o.vars > 0); return (o.sid, o.cpid, o.title, o.vars > 0)
462
+ }
463
+ /**
464
+ * Who started a tree whose top hides its environment. The system does not hand out the environment of its own
465
+ * binaries, and a detached job is usually `/bin/bash script.sh`. The first descendant that can be read answers: it
466
+ * inherited the same environment. Nothing is remembered until one can be read, so a script that has not started a
467
+ * child yet is asked again at the next reading.
468
+ */
469
+ private func inheritedOrigin(_ top: Proc, _ kids: [Int32: [Int32]], _ all: [Int32: Proc]) -> (sid: String?, cpid: Int32?)? {
470
+ if let o = inherited[top.pid], o.start == top.start { return (o.sid, o.cpid) }
471
+ var queue = kids[top.pid] ?? [], seen = 0
472
+ while !queue.isEmpty && seen < 24 {
473
+ let pid = queue.removeFirst(); seen += 1
474
+ guard let p = all[pid] else { continue }
475
+ let o = origin(p)
476
+ if o.readable { inherited[top.pid] = (top.start, o.sid, o.cpid); return (o.sid, o.cpid) }
477
+ queue.append(contentsOf: kids[pid] ?? [])
478
+ }
479
+ return nil
480
+ }
481
+ private func nameOf(_ p: Proc) -> String {
482
+ if let o = appNames[p.pid], o.start == p.start { return o.name }
483
+ var n = appName(p.pid, p.name)
484
+ if PLAIN_NAMES.contains(n) || n.lowercased().hasPrefix("python"), let t = origin(p).title, !t.isEmpty { n = t }
485
+ appNames[p.pid] = (p.start, n); return n
486
+ }
487
+ /**
488
+ * Charges every process of this user to one of four owners: a live session whose tree it is in, a live session that
489
+ * started it detached, an ended session that left it behind, or nobody. `ps`-style resident size misses compressed and
490
+ * GPU-backed memory and a tree walk misses detached work, which is how a machine out of memory could show almost no AI load.
491
+ */
492
+ func readCensus(_ sessions: [Session]) {
493
+ let now = Date().timeIntervalSince1970, all = census()
494
+ guard !all.isEmpty else { return }
495
+ let span = cpuSeenAt > 0 && now - cpuSeenAt > 0.2 ? (now - cpuSeenAt) * 1e9 * CORES : 0
496
+ let roots = Set(sessions.map { Int32($0.pid) })
497
+ let bySid = Dictionary(sessions.compactMap { s in s.sessionId.map { ($0, s.pid) } }, uniquingKeysWith: { a, _ in a })
498
+ // 1. each process: its CPU since the last reading, the session whose tree it is in, or else the top of its own tree
499
+ struct Row { let p: Proc; let cpu: Double; let owner: Int32?; let top: Proc }
500
+ enum Cls { case session(Int), left, other }
501
+ var rows: [Row] = [], treeOwner: [Int32: Int32] = [:], topOf: [Int32: Int32] = [:]
502
+ rows.reserveCapacity(all.count)
503
+ for p in all.values {
504
+ var cpu = 0.0
505
+ if span > 0, let before = cpuSeen[p.pid], p.cpuNs >= before { cpu = (p.cpuNs - before) / span }
506
+ var cur = p, owner: Int32? = nil, hops = 0
507
+ while hops < 64 {
508
+ if roots.contains(cur.pid) { owner = cur.pid; break }
509
+ guard cur.ppid > 1, let up = all[cur.ppid] else { break }
510
+ cur = up; hops += 1
511
+ }
512
+ if let o = owner { treeOwner[p.pid] = o } else { topOf[p.pid] = cur.pid }
513
+ rows.append(Row(p: p, cpu: cpu, owner: owner, top: cur))
514
+ }
515
+ // 2. each tree outside the sessions: which session started it, if any
516
+ var cls: [Int32: Cls] = [:], nameAs: [Int32: Proc] = [:], kids: [Int32: [Int32]] = [:]
517
+ for p in all.values { kids[p.ppid, default: []].append(p.pid) }
518
+ let home = NSHomeDirectory()
519
+ for r in rows where r.owner == nil && cls[r.top.pid] == nil {
520
+ let own = origin(r.top)
521
+ var sid = own.sid, cpid = own.cpid
522
+ if sid == nil && cpid == nil && !own.readable, let o = inheritedOrigin(r.top, kids, all) { sid = o.sid; cpid = o.cpid }
523
+ var live: Int? = sid.flatMap { bySid[$0] }
524
+ if live == nil, let cp = cpid, roots.contains(cp), let root = all[cp], root.start <= r.top.start { live = Int(cp) }
525
+ // No marker anywhere, the top hides its environment, and it works in the folder of exactly one live session: that session's.
526
+ if live == nil, sid == nil, cpid == nil, !own.readable, let dir = procCwd(r.top.pid), dir != home, dir != "/" {
527
+ let here = sessions.filter { $0.cwd == dir }
528
+ if here.count == 1 { live = here[0].pid }
529
+ }
530
+ if let o = live { cls[r.top.pid] = .session(o) } else { cls[r.top.pid] = (sid != nil || cpid != nil) ? .left : .other }
531
+ }
532
+ // 3. a helper the system started on a program's behalf (a virtual machine, an XPC service) goes where that program went
533
+ if let responsible = RESPONSIBLE {
534
+ for (top, c) in cls {
535
+ guard case .other = c else { continue }
536
+ let r = responsible(top)
537
+ guard r > 1, r != top else { continue }
538
+ if let o = treeOwner[r] { cls[top] = .session(Int(o)); nameAs[top] = all[r] }
539
+ else if let t = topOf[r], t != top, let c2 = cls[t] { if case .other = c2 { continue }; cls[top] = c2; nameAs[top] = all[t] }
540
+ }
541
+ }
542
+ var use: [Int: Usage] = [:], left = Load(), leftBy: [String: Load] = [:], otherBy: [String: Load] = [:], owners: [Int32: Int] = [:], labels: [Int32: String] = [:]
543
+ var leftProcs: [String: [(pid: Int32, start: UInt64)]] = [:], shared: Set<String> = [], leftWhere: [String: String] = [:]
544
+ let nowSec = UInt64(now)
545
+ for r in rows {
546
+ if let o = r.owner {
547
+ var u = use[Int(o), default: Usage()]; u.tree.add(r.cpu, r.p.memMb)
548
+ // The agent's own process is the session, not something it is running; a child a few seconds old is usually a status line refresh.
549
+ if r.p.pid != o, nowSec >= r.p.start + 5 { let l = nameOf(r.p); u.work[l, default: Work()].add(r.cpu, r.p.memMb); labels[r.p.pid] = l }
550
+ use[Int(o)] = u; owners[r.p.pid] = Int(o); continue
551
+ }
552
+ let label = nameOf(nameAs[r.top.pid] ?? r.top)
553
+ switch cls[r.top.pid] ?? .other {
554
+ case .session(let o): var u = use[o, default: Usage()]; u.detached.add(r.cpu, r.p.memMb); u.names[label, default: Load()].add(r.cpu, r.p.memMb); u.work[label, default: Work()].add(r.cpu, r.p.memMb); labels[r.p.pid] = label; use[o] = u; owners[r.p.pid] = o
555
+ case .left:
556
+ left.add(r.cpu, r.p.memMb); leftBy[label, default: Load()].add(r.cpu, r.p.memMb); owners[r.p.pid] = -1
557
+ leftProcs[label, default: []].append((pid: r.p.pid, start: r.p.start))
558
+ if leftWhere[label] == nil, let c = procCwd(r.p.pid), c.count > 1, c != NSHomeDirectory() { leftWhere[label] = (c as NSString).lastPathComponent }
559
+ if !shared.contains(label), isSharedService(nameAs[r.top.pid] ?? r.top) || isSharedService(r.top) { shared.insert(label) }
560
+ case .other: otherBy[label, default: Load()].add(r.cpu, r.p.memMb)
561
+ }
562
+ }
563
+ ownerOf = owners; labelOf = labels; leftoverPids = leftProcs; leftoverShared = shared; leftoverWhere = leftWhere
564
+ cpuSeen = all.mapValues { $0.cpuNs }; cpuSeenAt = now; if span > 0 { censusReady = true }
565
+ origins = origins.filter { all[$0.key] != nil }; appNames = appNames.filter { all[$0.key] != nil }; inherited = inherited.filter { all[$0.key] != nil }
566
+ let list: ([String: Load]) -> [AppLoad] = { d in d.map { AppLoad(id: $0.key, name: $0.key, cpu: $0.value.cpu, mem: $0.value.mem, n: $0.value.n) }.sorted { $0.mem > $1.mem } }
567
+ usage = use; leftover = left; leftoverItems = list(leftBy); others = list(otherBy)
568
+ }
569
+ /**
570
+ * Whether a session is working, waiting for the user, or resting. Working is judged by evidence, not only by the
571
+ * agent's own state: a session whose programs are busy is working even while the agent sits at its prompt.
572
+ */
573
+ func phase(_ s: Session) -> Phase {
574
+ if s.state == "waiting" { return .needsUser }
575
+ if s.state == "busy" || s.state == "shell" || s.subagents > 0 { return .active }
576
+ guard let u = usage[s.pid] else { return .idle }
577
+ return u.work.values.contains { $0.cpu >= 0.02 || $0.gpu >= 0.05 } ? .active : .idle
578
+ }
579
+ /** The programs a session is running that are doing something, heaviest first. */
580
+ func working(_ s: Session, max n: Int = 2) -> [(name: String, w: Work)] {
581
+ guard let u = usage[s.pid] else { return [] }
582
+ let score: (Work) -> Double = { $0.cpu * 100 + $0.gpu * 100 + $0.mem / 2048 }
583
+ return u.work.filter { !$0.key.isEmpty && ($0.value.cpu >= 0.004 || $0.value.gpu >= 0.01 || $0.value.mem >= 1024) }
584
+ .sorted { score($0.value) != score($1.value) ? score($0.value) > score($1.value) : $0.key < $1.key }.prefix(n).map { (name: $0.key, w: $0.value) }
585
+ }
586
+ /** Who needs the user first, then who is working, then the rest; inside each the order they came in. */
587
+ func ordered(_ sessions: [Session]) -> [Session] {
588
+ sessions.enumerated().sorted { let a = phase($0.element).rawValue, b = phase($1.element).rawValue; return a != b ? a < b : $0.offset < $1.offset }.map { $0.element }
589
+ }
590
+ /**
591
+ * Ask what ended sessions left behind to stop. Nothing shared is touched, and every process is checked again right
592
+ * before the signal: it must still be the one that was counted (same pid and start time, this user's), not a live
593
+ * session and not this app. Returns how many were signalled.
594
+ */
595
+ @discardableResult func stopLeftovers(_ labels: [String], force: Bool = false) -> Int {
596
+ var sent = 0
597
+ let sessions = Set((snap?.sessions ?? []).map { Int32($0.pid) }), size = Int32(MemoryLayout<proc_bsdinfo>.size)
598
+ for label in labels where !leftoverShared.contains(label) {
599
+ for one in leftoverPids[label] ?? [] where one.pid > 1 && one.pid != getpid() && !sessions.contains(one.pid) {
600
+ var info = proc_bsdinfo()
601
+ guard proc_pidinfo(one.pid, PROC_PIDTBSDINFO, 0, &info, size) == size, info.pbi_start_tvsec == one.start, info.pbi_uid == getuid() else { continue }
602
+ if kill(one.pid, force ? SIGKILL : SIGTERM) == 0 { sent += 1 }
603
+ }
604
+ }
605
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in self?.refresh() }
606
+ return sent
607
+ }
608
+ /** GPU time is a running total per process, so use is the difference between two readings. A process first seen now is counted from the next one. */
609
+ func readGpuUse(_ roots: Set<Int>) {
610
+ let now = Date().timeIntervalSince1970, seen = gpuClients()
611
+ if gpuSeenAt > 0, now - gpuSeenAt > 0.2 {
612
+ let span = (now - gpuSeenAt) * 1e9
613
+ var use: [GpuUse] = [], by: [Int: Double] = [:]
614
+ for (pid, c) in seen {
615
+ guard let before = gpuSeen[pid], c.ns > before else { continue }
616
+ let share = min(1, (c.ns - before) / span)
617
+ guard share >= 0.001 else { continue }
618
+ let charged = ownerOf[pid] ?? sessionOf(pid, roots).map { $0 }
619
+ let owner = charged.flatMap { $0 >= 0 ? $0 : nil }
620
+ use.append(GpuUse(pid: pid, name: procName(pid, c.name), share: share, session: owner, left: charged == -1))
621
+ if let o = owner { by[o, default: 0] += share; if let l = labelOf[pid] { usage[o]?.work[l, default: Work()].gpu += share } }
622
+ }
623
+ gpuUse = use.sorted { $0.share > $1.share }; gpuBySession = by.mapValues { min(1, $0) }
624
+ }
625
+ gpuSeen = seen.mapValues { $0.ns }; gpuSeenAt = now
626
+ }
627
+ /** Who is on the GPU, largest first: a line per session (with the processes doing it) and a line per process outside any session. */
628
+ func gpuLines(_ sessions: [Session], max n: Int = 4) -> [GpuLine] {
629
+ var out: [GpuLine] = []
630
+ for s in sessions {
631
+ let mine = gpuUse.filter { $0.session == s.pid }
632
+ guard !mine.isEmpty else { continue }
633
+ out.append(GpuLine(id: "s\(s.pid)", label: s.name ?? s.agent, note: mine.prefix(2).map { $0.name }.joined(separator: ", "), share: min(1, mine.reduce(0) { $0 + $1.share }), agent: s.agent, pid: s.pid))
634
+ }
635
+ for u in gpuUse where u.session == nil { out.append(GpuLine(id: "p\(u.pid)", label: u.name, note: u.left ? "끝난 세션이 남긴 것" : "", share: u.share, agent: u.left ? "left" : nil)) }
636
+ return Array(out.sorted { $0.share > $1.share }.prefix(n))
637
+ }
638
+ var wantDetail = false // a session page or the dashboard is showing: ask the CLI for each session's work as well
639
+ @Published var detailOff = false // this CLI has no --detail
640
+ private let machine = Machine()
641
+ var onUpdate: (() -> Void)?
642
+ // One reading is an instant. A statusline refresh under an idle session lives a fraction of a second, so it was in one poll and
643
+ // gone from the next, and every figure jumped while nothing was happening. Each figure shown is the middle of the last readings.
644
+ private struct Reading { let at: Double; let cpu: [Int: Double]; let mem: [Int: Double] }
645
+ private var readings: [Reading] = []
646
+ private func middle(_ pick: (Reading) -> Double?) -> Double? {
647
+ guard let last = readings.last else { return nil }
648
+ let v = readings.filter { last.at - $0.at <= 11 }.suffix(5).compactMap(pick).sorted()
649
+ return v.isEmpty ? nil : v[(v.count - 1) / 2]
650
+ }
651
+ static func raw(_ s: Session) -> Double { s.cpuPct ?? (s.cpu ?? 0) / CORES }
652
+ // The app's own count comes first: it includes detached work and the full memory footprint. The CLI's figures are the fallback.
653
+ func cpuOf(_ s: Session) -> Double { if censusReady, let u = usage[s.pid] { return (u.tree.cpu + u.detached.cpu) * 100 }; return middle { $0.cpu[s.pid] } ?? Model.raw(s) } // a percentage of the whole machine
654
+ func memOf(_ s: Session) -> Double { if let u = usage[s.pid], u.tree.n > 0 { return u.tree.mem + u.detached.mem }; return middle { $0.mem[s.pid] } ?? (s.rssMb ?? 0) }
655
+ func share(_ agent: String?) -> Double { (snap?.sessions ?? []).filter { agent == nil || $0.agent == agent }.reduce(0) { $0 + cpuOf($1) } }
656
+ func mem(_ agent: String?) -> Double { (snap?.sessions ?? []).filter { agent == nil || $0.agent == agent }.reduce(0) { $0 + memOf($1) } }
657
+ func refresh() {
658
+ if running { return } // the previous child has not returned: never stack a second one on it
659
+ running = true
660
+ let p = Process(); p.executableURL = URL(fileURLWithPath: NODE); let detailed = wantDetail && !detailOff
661
+ p.arguments = [CLI, "bar", "--json"] + (detailed ? ["--detail"] : [])
662
+ let out = Pipe(); p.standardOutput = out; p.standardError = FileHandle.nullDevice
663
+ DispatchQueue.global(qos: .utility).async {
664
+ var data = Data(); var err: String?
665
+ do {
666
+ try p.run()
667
+ let killer = DispatchWorkItem { if p.isRunning { p.terminate() } }
668
+ DispatchQueue.global().asyncAfter(deadline: .now() + 4, execute: killer)
669
+ data = out.fileHandleForReading.readDataToEndOfFile(); p.waitUntilExit(); killer.cancel()
670
+ } catch { err = "sprag bar 실행 실패: \(error.localizedDescription)" }
671
+ let snap = try? JSONDecoder().decode(Snapshot.self, from: data)
672
+ DispatchQueue.main.async {
673
+ self.running = false
674
+ self.sysCpu = self.machine.cpu() ?? self.sysCpu
675
+ self.sysMemMb = self.machine.memUsedMb() ?? self.sysMemMb
676
+ if let g = self.machine.gpu() { self.gpu = g.load; self.gpuMemMb = g.memMb }
677
+ if snap == nil && detailed { self.detailOff = true; self.refresh(); return } // an older CLI refuses the flag: carry on without it
678
+ if let s = snap {
679
+ let cpu = Dictionary(s.sessions.map { ($0.pid, Model.raw($0)) }, uniquingKeysWith: { a, _ in a })
680
+ let mem = Dictionary(s.sessions.map { ($0.pid, $0.rssMb ?? 0) }, uniquingKeysWith: { a, _ in a })
681
+ self.readings.append(Reading(at: Date().timeIntervalSince1970, cpu: cpu, mem: mem)); if self.readings.count > 8 { self.readings.removeFirst() }
682
+ self.snap = s; self.failure = nil
683
+ if TRACE {
684
+ let rows = s.sessions.map { "\($0.pid):\(String(format: "%.1f", Model.raw($0)))/\(Int($0.rssMb ?? 0))>\(String(format: "%.1f", self.cpuOf($0)))/\(Int(self.memOf($0)))" }.joined(separator: " ")
685
+ print("POLL raw \(String(format: "%.1f", s.sessions.reduce(0) { $0 + Model.raw($1) }))% \(Int(s.sessions.reduce(0) { $0 + ($1.rssMb ?? 0) }))MB | shown \(String(format: "%.1f", self.share(nil)))% \(Int(self.mem(nil)))MB | order \(s.sessions.map { String($0.pid) }.joined(separator: ",")) | \(rows)"); fflush(stdout)
686
+ }
687
+ } else { self.failure = err ?? "sprag bar 출력을 읽지 못했습니다" }
688
+ let live = self.snap?.sessions ?? []
689
+ let roots = Set(live.map { $0.pid })
690
+ self.readCensus(live)
691
+ self.readGpuUse(roots)
692
+ var ups: [Int: Int] = [:]
693
+ for r in live { if let p = parentPid(Int32(r.pid)), let up = sessionOf(p, roots.subtracting([r.pid])) { ups[r.pid] = up } }
694
+ // A session started from another session's shell begins life with that session's marker, even when it was detached from its tree.
695
+ for r in live where ups[r.pid] == nil {
696
+ if self.bornOf[r.pid] == nil { let o = claudeOrigin(Int32(r.pid)); self.bornOf[r.pid] = (o.sid, o.cpid) }
697
+ guard let from = self.bornOf[r.pid] else { continue }
698
+ if let cp = from.cpid, Int(cp) != r.pid, roots.contains(Int(cp)) { ups[r.pid] = Int(cp) }
699
+ else if let sid = from.sid, sid != r.sessionId, let up = live.first(where: { $0.sessionId == sid }) { ups[r.pid] = up.pid }
700
+ }
701
+ self.bornOf = self.bornOf.filter { roots.contains($0.key) }
702
+ self.parentSession = ups
703
+ var x = Sample()
704
+ x.claudeCpu = self.share("claude") / 100; x.codexCpu = self.share("codex") / 100
705
+ x.claudeMem = self.mem("claude") / RAM_MB; x.codexMem = self.mem("codex") / RAM_MB
706
+ x.sysCpu = max(self.sysCpu ?? 0, x.claudeCpu + x.codexCpu); x.sysMem = max((self.sysMemMb ?? 0) / RAM_MB, x.claudeMem + x.codexMem)
707
+ x.leftCpu = self.leftover.cpu; x.leftMem = self.leftover.mem / RAM_MB
708
+ x.claudeGpu = min(1, live.filter { $0.agent != "codex" }.reduce(0) { $0 + (self.gpuBySession[$1.pid] ?? 0) })
709
+ x.codexGpu = min(1 - x.claudeGpu, live.filter { $0.agent == "codex" }.reduce(0) { $0 + (self.gpuBySession[$1.pid] ?? 0) })
710
+ x.gpu = max(self.gpu ?? 0, x.claudeGpu + x.codexGpu)
711
+ x.at = Date().timeIntervalSince1970; x.cost = self.snap?.totals.costUsd ?? 0
712
+ self.samples.append(x); if self.samples.count > 60 { self.samples.removeFirst() }
713
+ if let s = snap {
714
+ for r in s.sessions {
715
+ var a = self.hist[r.pid] ?? []
716
+ a.append(Hist(at: x.at, cpu: self.cpuOf(r), mem: self.memOf(r), gpu: self.gpuBySession[r.pid] ?? 0)); if a.count > 60 { a.removeFirst() }
717
+ self.hist[r.pid] = a
718
+ }
719
+ self.hist = self.hist.filter { k, _ in s.sessions.contains { $0.pid == k } }
720
+ }
721
+ self.onUpdate?()
722
+ }
723
+ }
724
+ }
725
+ }
726
+
727
+ /** The settings page. It only ever runs commands the CLI already has; nothing here writes a file itself. */
728
+ final class Prefs: ObservableObject {
729
+ @Published var s: Settings?
730
+ @Published var samples: [Int: String] = [:] // display level -> what the statusline looks like at that level
731
+ @Published var pendingCompact: Int? // a compact window value waiting for the second click
732
+ /** Called when the settings page opens. */
733
+ func open() { note = ""; failed = false; pendingCompact = nil; load(resetDraft: true); loadSamples() }
734
+ /** The CLI's own demo render at each level, with the stored label style, so a level is shown and not described. */
735
+ func loadSamples() {
736
+ for n in 0...3 {
737
+ sprag(["--statusline", "--demo", "healthy", "--compact-level", String(n), "--no-color", "--columns", "200"], timeout: 6) { code, out, _ in
738
+ let t = stripAnsi(out).trimmingCharacters(in: .whitespacesAndNewlines)
739
+ if code == 0, !t.isEmpty { self.samples[n] = t; RELAYOUT() }
740
+ }
741
+ }
742
+ }
743
+ @Published var working = false
744
+ @Published var note = ""
745
+ @Published var failed = false
746
+ @Published var nameDraft = ""
747
+ var onLayout: (() -> Void)?
748
+ func load(resetDraft: Bool = false, then: (() -> Void)? = nil) {
749
+ sprag(["bar", "--settings"], timeout: 6) { _, out, _ in
750
+ if let v = try? JSONDecoder().decode(Settings.self, from: Data(out.utf8)) {
751
+ self.s = v
752
+ if resetDraft { self.nameDraft = v.team.displayName ?? "" }
753
+ } else { self.note = "설정을 읽지 못했습니다"; self.failed = true }
754
+ self.onLayout?(); then?()
755
+ }
756
+ }
757
+ /** Run one settings command, show its first line of output, then read every setting back from the CLI. */
758
+ func apply(_ args: [String], say: String? = nil, resetDraft: Bool = false, then: (() -> Void)? = nil, _ guess: (inout Settings) -> Void = { _ in }) {
759
+ if working { return }
760
+ working = true
761
+ if var v = s { guess(&v); s = v } // the control moves at once; the reload below is what counts
762
+ sprag(args, timeout: 25) { code, out, err in
763
+ self.working = false
764
+ self.failed = code != 0
765
+ self.note = code == 0 ? (say ?? firstLine(out)) : (firstLine(err).isEmpty ? (firstLine(out).isEmpty ? "실패했습니다 (종료 코드 \(code))" : firstLine(out)) : firstLine(err))
766
+ self.load(resetDraft: resetDraft, then: then)
767
+ }
768
+ }
769
+ func setRouting(_ on: Bool, then: (() -> Void)? = nil) { apply(["routing", on ? "on" : "off"], then: then) { $0.routing.enabled = on } }
770
+ func setRelax(_ on: Bool, then: (() -> Void)? = nil) { apply(on ? ["routing", "relax"] : ["routing", "relax", "off"], then: then) { $0.routing.relaxed = on } }
771
+ func setLevel(_ n: Int, then: (() -> Void)? = nil) { apply(["mode", "compact=\(n)"], say: "상태줄 표시 단계를 \(n)로 바꿨습니다. 다음 갱신부터 적용됩니다", then: then) { $0.statusline.compact = n } }
772
+ func setLabels(_ v: String, then: (() -> Void)? = nil) { apply(["mode", v], say: "상태줄 라벨을 바꿨습니다. 다음 갱신부터 적용됩니다", then: { self.loadSamples(); then?() }) { $0.statusline.labels = v } }
773
+ /** Writes the global settings file for every model, so the page asks twice before calling this. */
774
+ func setCompact(_ n: Int, then: (() -> Void)? = nil) {
775
+ pendingCompact = nil
776
+ apply(["compact-window", "set", "--global", "--all-models", "--value", "\(n / 1000)k"], say: "자동 압축 시점을 \(n / 1000)k로 바꿨습니다. 새 세션부터 적용됩니다", then: then) { $0.compactWindow?.value = Double(n) }
777
+ }
778
+ func setCompactWarn(_ on: Bool, then: (() -> Void)? = nil) { apply(["compact-window", on ? "on" : "off"], say: on ? "자동 압축 알림을 켰습니다" : "자동 압축 알림을 껐습니다", then: then) { $0.compactWindow?.warn = on } }
779
+ func setTimer(_ on: Bool, then: (() -> Void)? = nil) { apply(["mode", on ? "timer" : "no-timer"], say: on ? "캐시 타이머를 켰습니다" : "캐시 타이머를 껐습니다", then: then) { $0.statusline.timer = on } }
780
+ func setLanguage(_ v: String, then: (() -> Void)? = nil) { apply(["mode", "lang=\(v)"], say: v == "ko" ? "안내문 언어를 한국어로 바꿨습니다" : "안내문 언어를 영어로 바꿨습니다", then: then) { $0.language = v } }
781
+ var nameChanged: Bool { let d = nameDraft.trimmingCharacters(in: .whitespaces); return !d.isEmpty && d != (s?.team.displayName ?? "") }
782
+ func rename() { if nameChanged { apply(["team", "name", nameDraft.trimmingCharacters(in: .whitespaces)], resetDraft: true) } }
783
+ func openTown() { apply(["team", "town"], say: "브라우저에서 타운을 열었습니다") }
784
+ }
785
+
786
+ /** The rules page. Like the settings page it only runs commands the CLI already has. */
787
+ final class RuleBook: ObservableObject {
788
+ @Published var data: Rules?
789
+ @Published var working = false
790
+ @Published var note = ""
791
+ @Published var failed = false
792
+ @Published var open: Set<String> = [] // groups that are unfolded
793
+ @Published var expanded: String? // the rule showing its full text and buttons
794
+ @Published var confirm: String? // the rule whose removal waits for the second click
795
+ @Published var drafts: [String: String] = [:]
796
+ func load(then: (() -> Void)? = nil) {
797
+ sprag(["bar", "--rules"], timeout: 8) { _, out, _ in
798
+ if let v = try? JSONDecoder().decode(Rules.self, from: Data(out.utf8)) { self.data = v } else { self.note = "규칙을 읽지 못했습니다"; self.failed = true }
799
+ RELAYOUT(); then?()
800
+ }
801
+ }
802
+ private func run(_ args: [String], cwd: String? = nil, say: String, then: (() -> Void)? = nil) {
803
+ working = true
804
+ sprag(args, timeout: 25, cwd: cwd) { code, out, err in
805
+ self.working = false; self.confirm = nil; self.expanded = nil
806
+ self.failed = code != 0
807
+ self.note = code == 0 ? say : (firstLine(err).isEmpty ? (firstLine(out).isEmpty ? "실패했습니다 (종료 코드 \(code))" : firstLine(out)) : firstLine(err))
808
+ self.load(then: then)
809
+ }
810
+ }
811
+ private func refuse(_ then: (() -> Void)?) { working = false; failed = true; confirm = nil; note = "목록이 그사이 바뀌어 지우지 않았습니다. 다시 확인해 주십시오"; RELAYOUT(); then?() }
812
+ /** A rule is removed by its number, and the number is a position in a file that may have changed since it was shown: read the list again first. */
813
+ func removeRatchet(scope: String, root: String?, index: Int, text: String, then: (() -> Void)? = nil) {
814
+ if working { return }
815
+ working = true
816
+ load {
817
+ let now = scope == "global" ? self.data?.global.rules : self.data?.projects.first { $0.root == root }?.rules
818
+ guard now?.first(where: { $0.index == index })?.text == text else { self.refuse(then); return }
819
+ self.run(["harness", "rm", scope == "global" ? "--global" : "--project", String(index)], cwd: root, say: "규칙을 지웠습니다. 지우기 전 내용은 같은 폴더의 ratchet.md.bak 에 있습니다", then: then)
820
+ }
821
+ }
822
+ func addRatchet(scope: String, root: String?, key: String, text: String, then: (() -> Void)? = nil) {
823
+ let t = text.trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(of: "\n", with: " ")
824
+ if working || t.count < 8 || !t.contains(" ") { return } // a bare number or R<n> would be read as a candidate id
825
+ run(["harness", "promote", t, scope == "global" ? "--global" : "--project"], cwd: root, say: "규칙을 추가했습니다. 새 세션부터 적용됩니다") { self.drafts[key] = ""; then?() }
826
+ }
827
+ func skipPreset(_ id: String, then: (() -> Void)? = nil) { if !working { run(["seed", "skip", id], say: "프리셋을 뺐습니다. 다시 권하지 않습니다", then: then) } }
828
+ func acceptPreset(_ id: String, then: (() -> Void)? = nil) { if !working { run(["seed", "accept", id, "--global"], say: "프리셋을 전역으로 등록했습니다", then: then) } }
829
+ func removeModel(index: Int, text: String, then: (() -> Void)? = nil) {
830
+ if working { return }
831
+ working = true
832
+ load {
833
+ guard self.data?.model.rules.first(where: { $0.index == index })?.text == text else { self.refuse(then); return }
834
+ self.run(["route-scan", "rules", "rm", String(index)], say: "모델 위임 룰을 지웠습니다", then: then)
835
+ }
836
+ }
837
+ }
838
+
839
+ // ---------- the runner: a dog drawn in code as a template image ----------
840
+ struct Pose { let fn: (Double, Double), ff: (Double, Double), hn: (Double, Double), hf: (Double, Double); let lift: Double, stretch: Double }
841
+ // Each leg: (upper, lower) segment angle in degrees from straight down, + is forward. A six-frame gallop.
842
+ let GALLOP: [Pose] = [
843
+ Pose(fn: (70, 80), ff: (54, 66), hn: (-66, -80), hf: (-50, -64), lift: 1.0, stretch: 0.9), // flight, stretched out
844
+ Pose(fn: (38, 18), ff: (54, 42), hn: (-56, -82), hf: (-42, -68), lift: 0.3, stretch: 0.6), // front legs land
845
+ Pose(fn: (2, -14), ff: (20, 6), hn: (-24, -70), hf: (-38, -80), lift: -0.5, stretch: 0.1), // weight over the front
846
+ Pose(fn: (-28, -52), ff: (-12, -34), hn: (34, 10), hf: (20, -6), lift: -0.3, stretch: -0.8), // gathered, hind legs reach under
847
+ Pose(fn: (16, -52), ff: (34, -32), hn: (14, 0), hf: (0, -14), lift: 0.2, stretch: -0.4), // hind legs carry
848
+ Pose(fn: (56, 26), ff: (66, 46), hn: (-30, -40), hf: (-44, -56), lift: 0.7, stretch: 0.4), // push off
849
+ ]
850
+ let STAND = Pose(fn: (4, -2), ff: (-7, 3), hn: (-9, 6), hf: (5, 12), lift: 0, stretch: 0)
851
+ let RUNNER_SCALE: CGFloat = 0.9
852
+ func runner(frame: Int, idle: Bool) -> NSImage {
853
+ let size = NSSize(width: 31 * RUNNER_SCALE, height: 21.4 * RUNNER_SCALE)
854
+ let img = NSImage(size: size, flipped: false) { _ in
855
+ let t = NSAffineTransform(); t.scale(by: RUNNER_SCALE); t.concat()
856
+ let p = idle ? STAND : GALLOP[frame % GALLOP.count]
857
+ let L = CGFloat(p.lift), s = CGFloat(p.stretch)
858
+ NSColor.black.setFill(); NSColor.black.setStroke()
859
+ func line(_ a: NSPoint, _ b: NSPoint, _ w: CGFloat) { let q = NSBezierPath(); q.lineWidth = w; q.lineCapStyle = .round; q.move(to: a); q.line(to: b); q.stroke() }
860
+ func leg(_ joint: NSPoint, _ a: (Double, Double)) {
861
+ let a1 = CGFloat(a.0) * .pi / 180, a2 = CGFloat(a.1) * .pi / 180
862
+ let knee = NSPoint(x: joint.x + sin(a1) * 3.7, y: joint.y - cos(a1) * 3.7)
863
+ var foot = NSPoint(x: knee.x + sin(a2) * 3.9, y: knee.y - cos(a2) * 3.9)
864
+ foot.y = max(foot.y, 1.3)
865
+ line(joint, knee, 2.7); line(knee, foot, 2.0)
866
+ NSBezierPath(ovalIn: NSRect(x: foot.x - 0.8, y: foot.y - 0.95, width: 2.5, height: 1.75)).fill() // paw
867
+ }
868
+ let shoulder = NSPoint(x: 19.0 + s * 0.3, y: 9.0 + L), hip = NSPoint(x: 11.0 - s, y: 9.2 + L)
869
+ leg(shoulder, p.ff); leg(hip, p.hf)
870
+ // tail: a husky carries it curled over the back, also at a run
871
+ let wag: CGFloat = idle ? (frame % 2 == 0 ? 0 : 1.2) : -s * 0.5
872
+ let tail = NSBezierPath(); tail.lineWidth = 3.1; tail.lineCapStyle = .round
873
+ tail.move(to: NSPoint(x: 9.0 - s, y: 13.0 + L))
874
+ tail.curve(to: NSPoint(x: 9.2 - s * 0.5 + wag, y: 18.3 + L * 0.6), controlPoint1: NSPoint(x: 3.4 - s, y: 12.2 + L), controlPoint2: NSPoint(x: 3.2 - s * 0.6 + wag, y: 19.0 + L * 0.6))
875
+ tail.stroke()
876
+ // body: short, deep chest, tucked waist
877
+ let f = s * 0.3
878
+ let body = NSBezierPath()
879
+ body.move(to: NSPoint(x: 7.8 - s, y: 11.0 + L))
880
+ body.curve(to: NSPoint(x: 12.0 - s * 0.5, y: 14.0 + L), controlPoint1: NSPoint(x: 7.8 - s, y: 13.0 + L), controlPoint2: NSPoint(x: 9.6 - s, y: 14.0 + L))
881
+ body.curve(to: NSPoint(x: 19.6 + f, y: 14.3 + L), controlPoint1: NSPoint(x: 14.6, y: 13.8 + L - s * 0.3), controlPoint2: NSPoint(x: 17.2, y: 13.9 + L - s * 0.3))
882
+ body.curve(to: NSPoint(x: 22.6 + f, y: 10.4 + L), controlPoint1: NSPoint(x: 21.6 + f, y: 14.3 + L), controlPoint2: NSPoint(x: 22.8 + f, y: 12.4 + L))
883
+ body.curve(to: NSPoint(x: 18.6 + f, y: 6.6 + L), controlPoint1: NSPoint(x: 22.4 + f, y: 8.2 + L), controlPoint2: NSPoint(x: 20.8 + f, y: 6.6 + L))
884
+ body.curve(to: NSPoint(x: 11.6 - s, y: 7.9 + L), controlPoint1: NSPoint(x: 16.2, y: 6.6 + L), controlPoint2: NSPoint(x: 14.0 - s * 0.5, y: 8.9 + L))
885
+ body.curve(to: NSPoint(x: 7.8 - s, y: 11.0 + L), controlPoint1: NSPoint(x: 9.4 - s, y: 7.2 + L), controlPoint2: NSPoint(x: 7.8 - s, y: 9.0 + L))
886
+ body.close(); body.fill()
887
+ // neck and a large head with a short muzzle
888
+ let hc = NSPoint(x: 24.0 + s * 0.4, y: 15.0 + L * 0.8 - (idle ? 0 : 0.4))
889
+ line(NSPoint(x: 20.6 + f, y: 12.0 + L), hc, 5.2)
890
+ NSBezierPath(ovalIn: NSRect(x: hc.x - 3.2, y: hc.y - 2.9, width: 6.4, height: 5.8)).fill()
891
+ let snout = NSBezierPath()
892
+ snout.move(to: NSPoint(x: hc.x + 1.4, y: hc.y + 1.2)); snout.line(to: NSPoint(x: hc.x + 4.7, y: hc.y - 0.3))
893
+ snout.curve(to: NSPoint(x: hc.x + 4.4, y: hc.y - 2.2), controlPoint1: NSPoint(x: hc.x + 5.5, y: hc.y - 0.7), controlPoint2: NSPoint(x: hc.x + 5.3, y: hc.y - 2.0))
894
+ snout.line(to: NSPoint(x: hc.x + 0.8, y: hc.y - 2.8)); snout.close(); snout.fill()
895
+ for (x0, tip, x1) in [(-3.0, -2.6, -0.6), (-1.0, 0.8, 2.1)] as [(CGFloat, CGFloat, CGFloat)] { // pricked ears
896
+ let ear = NSBezierPath(); ear.move(to: NSPoint(x: hc.x + x0, y: hc.y + 1.2)); ear.line(to: NSPoint(x: hc.x + tip, y: hc.y + 5.3)); ear.line(to: NSPoint(x: hc.x + x1, y: hc.y + 1.9)); ear.close(); ear.fill()
897
+ }
898
+ leg(shoulder, p.fn); leg(hip, p.hn)
899
+ NSGraphicsContext.current?.compositingOperation = .clear
900
+ NSBezierPath(ovalIn: NSRect(x: hc.x + 0.5, y: hc.y - 0.1, width: 1.7, height: 1.7)).fill() // eye
901
+ return true
902
+ }
903
+ img.isTemplate = true
904
+ return img
905
+ }
906
+
907
+ // ---------- text ----------
908
+ func memText(_ mb: Double?) -> String { guard let mb = mb else { return "-" }; return mb < 1024 ? "\(Int(mb.rounded())) MB" : String(format: "%.1f GB", mb / 1024) }
909
+ func pct1(_ v: Double) -> String { String(format: "%.1f%%", v) }
910
+ func tokText(_ n: Double) -> String { n < 1000 ? "\(Int(n))" : n < 1_000_000 ? "\(Int((n / 1000).rounded()))k" : String(format: "%.1fM", n / 1_000_000) }
911
+ func sinceText(_ since: Double?, now: Double) -> String {
912
+ guard let s = since else { return "" }
913
+ let sec = max(0, Int((now - s) / 1000))
914
+ if sec < 60 { return "\(sec)초째" }; if sec < 3600 { return "\(sec / 60)분째" }; if sec < 172800 { return "\(sec / 3600)시간째" }
915
+ return "\(sec / 86400)일째"
916
+ }
917
+ func resetText(_ ms: Double?, now: Double) -> String {
918
+ guard let ms = ms else { return "" }
919
+ let sec = Int((ms - now) / 1000); if sec <= 0 { return "" }
920
+ let d = sec / 86400, h = (sec % 86400) / 3600, m = (sec % 3600) / 60
921
+ if d > 0 { return "\(d)일 \(h)시간 뒤 초기화" }; if h > 0 { return "\(h)시간 \(m)분 뒤 초기화" }
922
+ return "\(m)분 뒤 초기화"
923
+ }
924
+ func windowName(_ w: Win) -> String {
925
+ switch w.key {
926
+ case "five_hour": return "5시간"
927
+ case "seven_day": return "7일"
928
+ case "seven_day_opus": return "7일 Opus"
929
+ case "seven_day_sonnet": return "7일 Sonnet"
930
+ default:
931
+ let l = w.label
932
+ if let n = Int(l.dropLast()), let unit = l.last { if unit == "D" { return "\(n)일" }; if unit == "H" { return "\(n)시간" }; if unit == "m" { return "\(n)분" } }
933
+ return l
934
+ }
935
+ }
936
+ func agoText(_ at: Double?, now: Double) -> String {
937
+ guard let at = at else { return "" }
938
+ let sec = max(0, Int((now - at) / 1000))
939
+ if sec < 60 { return "\(sec)초 전" }; if sec < 3600 { return "\(sec / 60)분 전" }; if sec < 172800 { return "\(sec / 3600)시간 전" }
940
+ return "\(sec / 86400)일 전"
941
+ }
942
+ func toolName(_ t: String) -> String { t.hasPrefix("mcp__") ? (t.components(separatedBy: "__").last ?? t) : t }
943
+ func stateColor(_ s: Session) -> Color {
944
+ switch s.state { case "busy", "shell": return Color(red: 0.05, green: 0.64, blue: 0.05); case "idle": return Color(white: 0.55); case "waiting": return Color(red: 0.98, green: 0.70, blue: 0.10); case nil: return Color(white: 0.4); default: return .yellow }
945
+ }
946
+ func activity(_ s: Session, now: Double) -> String {
947
+ var parts: [String] = []
948
+ if let m = s.modelName { parts.append(s.effort.map { "\(m) \($0)" } ?? m) } else if let e = s.effort { parts.append("effort \(e)") }
949
+ switch s.state {
950
+ case "busy": parts.append(s.tools.isEmpty ? "작업 중" : (s.tools.count > 1 ? "\(s.tools[0]) 외 \(s.tools.count - 1)개 실행 중" : "\(s.tools[0]) 실행 중"))
951
+ case "idle": parts.append("입력 대기")
952
+ case "shell": parts.append("셸 명령 실행 중")
953
+ case "waiting": parts.append("확인 대기")
954
+ case nil: parts.append("상태 모름")
955
+ default: parts.append(s.state ?? "")
956
+ }
957
+ if s.subagents > 0 { parts.append("서브에이전트 \(s.subagents)개") }
958
+ let d = sinceText(s.stateSince, now: now); if !d.isEmpty { parts.append(d) }
959
+ return parts.joined(separator: ", ")
960
+ }
961
+
962
+ // ---------- the panel ----------
963
+ struct Bar: View {
964
+ let value: Double; let tint: Color
965
+ var body: some View {
966
+ GeometryReader { g in
967
+ ZStack(alignment: .leading) {
968
+ Capsule().fill(Color.primary.opacity(0.12))
969
+ Capsule().fill(tint).frame(width: max(3, g.size.width * CGFloat(min(1, max(0, value)))))
970
+ }
971
+ }.frame(height: 5)
972
+ }
973
+ }
974
+ /** History the way RunCat draws it: filled areas growing from the right. Grey is the whole machine, the colours are the agents. */
975
+ struct LoadChart: View {
976
+ let sys: [Double], claude: [Double], codex: [Double]
977
+ func area(_ v: [Double], _ size: CGSize) -> Path {
978
+ Path { p in
979
+ guard !v.isEmpty else { return }
980
+ let step = size.width / 59, x0 = size.width - CGFloat(v.count - 1) * step
981
+ p.move(to: CGPoint(x: x0, y: size.height))
982
+ for (i, y) in v.enumerated() { p.addLine(to: CGPoint(x: x0 + CGFloat(i) * step, y: size.height * (1 - CGFloat(min(1, max(0, y)))))) }
983
+ p.addLine(to: CGPoint(x: size.width, y: size.height)); p.closeSubpath()
984
+ }
985
+ }
986
+ var body: some View {
987
+ GeometryReader { g in
988
+ ZStack {
989
+ Color.primary.opacity(0.07)
990
+ area(sys, g.size).fill(Color.primary.opacity(0.26))
991
+ area(zip(claude, codex).map { $0 + $1 }, g.size).fill(CODEX)
992
+ area(claude, g.size).fill(CLAUDE)
993
+ }
994
+ }.frame(height: 32).clipShape(RoundedRectangle(cornerRadius: 3))
995
+ }
996
+ }
997
+ struct Block<Content: View>: View {
998
+ let symbol: String; let title: String; @ViewBuilder var content: Content
999
+ var body: some View {
1000
+ HStack(alignment: .top, spacing: 12) {
1001
+ Image(systemName: symbol).font(.system(size: 22, weight: .regular)).frame(width: 34, height: 26)
1002
+ VStack(alignment: .leading, spacing: 4) {
1003
+ Text(title).font(.system(size: 15.5, weight: .semibold)).monospacedDigit()
1004
+ content
1005
+ }.frame(maxWidth: .infinity, alignment: .leading)
1006
+ }.padding(.vertical, 11).padding(.horizontal, 12)
1007
+ }
1008
+ }
1009
+ struct Legend: View {
1010
+ let color: Color; let label: String; let value: String
1011
+ var body: some View {
1012
+ HStack(spacing: 6) {
1013
+ RoundedRectangle(cornerRadius: 2).fill(color).frame(width: 9, height: 9)
1014
+ Text(label).foregroundColor(.secondary)
1015
+ Text(value).monospacedDigit()
1016
+ }.font(.system(size: 12))
1017
+ }
1018
+ }
1019
+ struct Badge: View {
1020
+ let agent: String
1021
+ var body: some View {
1022
+ Text(agent == "codex" ? "Codex" : "Claude").font(.system(size: 9.5, weight: .bold)).foregroundColor(.white)
1023
+ .padding(.horizontal, 6).padding(.vertical, 2).background(Capsule().fill(agentTint(agent))).fixedSize()
1024
+ }
1025
+ }
1026
+ struct SessionRow: View {
1027
+ let s: Session; let cpu: Double; let mem: Double; let now: Double
1028
+ var body: some View {
1029
+ VStack(alignment: .leading, spacing: 4) {
1030
+ HStack(alignment: .center, spacing: 6) {
1031
+ Badge(agent: s.agent)
1032
+ Text(s.name ?? s.agent).font(.system(size: 13, weight: .semibold)).lineLimit(2).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true)
1033
+ Spacer(minLength: 6)
1034
+ if let c = s.usage?.costUsd { Text(String(format: "$%.2f", c)).font(.system(size: 12.5, weight: .medium)).monospacedDigit().fixedSize().help("이 세션의 비용, 정가 환산") }
1035
+ }
1036
+ HStack(spacing: 6) {
1037
+ Circle().fill(stateColor(s)).frame(width: 7, height: 7)
1038
+ Text(activity(s, now: now)).font(.system(size: 11.5)).foregroundColor(.secondary).lineLimit(1)
1039
+ }
1040
+ if s.context != nil || s.usage != nil {
1041
+ HStack(spacing: 8) {
1042
+ HStack(spacing: 3) { Image(systemName: "cpu").foregroundColor(.secondary); Text(s.cpu == nil ? "-" : pct1(cpu)).monospacedDigit() }.fixedSize().help("CPU, 기기 전체 대비")
1043
+ HStack(spacing: 3) { Image(systemName: "memorychip").foregroundColor(.secondary); Text(s.rssMb == nil ? "-" : memText(mem)).monospacedDigit() }.fixedSize().help("메모리")
1044
+ if let c = s.context {
1045
+ Text("컨텍스트").foregroundColor(.secondary)
1046
+ if let p = c.pct { Bar(value: p / 100, tint: p >= 80 ? .orange : agentTint(s.agent)).frame(width: 54); Text("\(Int(p))%").monospacedDigit() } else { Text(tokText(c.tokens)).monospacedDigit() }
1047
+ }
1048
+ Spacer(minLength: 0)
1049
+ }.font(.system(size: 11.5)).lineLimit(1)
1050
+ }
1051
+ }.padding(.vertical, 7)
1052
+ }
1053
+ }
1054
+ extension View {
1055
+ /** The link hand over things that can be pressed (macOS 15 and later; older systems keep the arrow). */
1056
+ // The pointer style API arrived with the macOS 15 SDK. An older toolchain does not know the name at all, so it gets a
1057
+ // version of this function that leaves the view alone, and the file still compiles there.
1058
+ #if compiler(>=6.0)
1059
+ @ViewBuilder func linkPointer(_ on: Bool = true) -> some View { if #available(macOS 15.0, *) { self.pointerStyle(on ? .link : .default) } else { self } }
1060
+ #else
1061
+ func linkPointer(_ on: Bool = true) -> some View { self }
1062
+ #endif
1063
+ }
1064
+ /**
1065
+ * A plain button that shows it can be pressed: a wash comes over it while the pointer is on it, a stronger one while it is
1066
+ * held, and the pointer turns into the link hand. `grow` lets the wash reach past the label without moving the layout,
1067
+ * `off` is for a choice that is already selected, and `lit` draws the hovered state for a capture.
1068
+ */
1069
+ struct HoverStyle: ButtonStyle {
1070
+ var radius: CGFloat = 6; var grow: CGFloat = 0; var lit = false; var off = false
1071
+ func makeBody(configuration: Configuration) -> some View { HoverWash(c: configuration, radius: radius, grow: grow, lit: lit, off: off) }
1072
+ }
1073
+ struct HoverWash: View {
1074
+ let c: ButtonStyleConfiguration; let radius: CGFloat; let grow: CGFloat; let lit: Bool; let off: Bool
1075
+ @State private var over = false
1076
+ @Environment(\.isEnabled) private var enabled
1077
+ var body: some View {
1078
+ let live = enabled && !off
1079
+ c.label
1080
+ .overlay(RoundedRectangle(cornerRadius: radius).fill(Color.primary.opacity(!live ? 0 : c.isPressed ? 0.22 : (over || lit) ? 0.14 : 0)).padding(-grow).allowsHitTesting(false))
1081
+ .onHover { over = $0 }
1082
+ .animation(.easeOut(duration: 0.10), value: over)
1083
+ .linkPointer(live)
1084
+ }
1085
+ }
1086
+ /** A whole area that can be pressed and may hold buttons of its own (a button inside a button does not get its clicks). Same hover wash and pointer as HoverStyle. */
1087
+ struct Pressable<Content: View>: View {
1088
+ var radius: CGFloat = 8; var lit = false; let action: () -> Void; @ViewBuilder var content: Content
1089
+ @State private var over = false
1090
+ var body: some View {
1091
+ content.overlay(RoundedRectangle(cornerRadius: radius).fill(Color.primary.opacity((over || lit) ? 0.09 : 0)).allowsHitTesting(false))
1092
+ .overlay(RoundedRectangle(cornerRadius: radius).stroke(Color.primary.opacity((over || lit) ? 0.45 : 0), lineWidth: 1).allowsHitTesting(false))
1093
+ .contentShape(Rectangle()).onTapGesture(perform: action).onHover { over = $0 }.animation(.easeOut(duration: 0.10), value: over).linkPointer()
1094
+ }
1095
+ }
1096
+ /** A dot that keeps sending out a ring: something is running right now. */
1097
+ struct LiveDot: View {
1098
+ let color: Color
1099
+ @State private var on = false
1100
+ var body: some View {
1101
+ Circle().fill(color).frame(width: 7, height: 7).overlay(Circle().stroke(color.opacity(0.55), lineWidth: 2).scaleEffect(on ? 2.4 : 1).opacity(on ? 0 : 1))
1102
+ .frame(width: 12, height: 12)
1103
+ .onAppear { withAnimation(.easeOut(duration: 1.3).repeatForever(autoreverses: false)) { on = true } }
1104
+ }
1105
+ }
1106
+ // Controls drawn here, not AppKit's: they match the panel and they show up in a rendered capture.
1107
+ struct Switch: View {
1108
+ let on: Bool; var disabled = false; let flip: () -> Void
1109
+ var body: some View {
1110
+ Button(action: flip) {
1111
+ ZStack(alignment: on ? .trailing : .leading) {
1112
+ Capsule().fill(on ? Color.accentColor : Color.primary.opacity(0.22)).frame(width: 36, height: 21)
1113
+ Circle().fill(Color.white).frame(width: 17, height: 17).padding(2).shadow(color: Color.black.opacity(0.3), radius: 0.8, y: 0.5)
1114
+ }.contentShape(Rectangle())
1115
+ }.buttonStyle(HoverStyle(radius: 12, grow: 3)).disabled(disabled).opacity(disabled ? 0.4 : 1).animation(.easeOut(duration: 0.14), value: on)
1116
+ }
1117
+ }
1118
+ struct Segments: View {
1119
+ let options: [Opt]; let selected: String; var disabled = false; let pick: (String) -> Void
1120
+ var body: some View {
1121
+ HStack(spacing: 2) {
1122
+ ForEach(options) { o in
1123
+ Button(action: { if o.id != selected { pick(o.id) } }) {
1124
+ Text(o.label).font(.system(size: 12, weight: o.id == selected ? .semibold : .regular)).lineLimit(1).frame(maxWidth: .infinity).padding(.vertical, 4)
1125
+ .background(RoundedRectangle(cornerRadius: 5).fill(o.id == selected ? Color.primary.opacity(0.24) : Color.clear)).contentShape(Rectangle())
1126
+ }.buttonStyle(HoverStyle(radius: 5, off: o.id == selected))
1127
+ }
1128
+ }.padding(2).background(RoundedRectangle(cornerRadius: 7).fill(Color.primary.opacity(0.09))).disabled(disabled).opacity(disabled ? 0.4 : 1)
1129
+ }
1130
+ }
1131
+ struct SettingRow<Control: View>: View {
1132
+ let label: String; var caption: String = ""; @ViewBuilder var control: Control
1133
+ var body: some View {
1134
+ HStack(alignment: .center, spacing: 10) {
1135
+ VStack(alignment: .leading, spacing: 1) {
1136
+ Text(label).font(.system(size: 12.5))
1137
+ if !caption.isEmpty { Text(caption).font(.system(size: 10.5)).foregroundColor(.secondary).fixedSize(horizontal: false, vertical: true) }
1138
+ }
1139
+ Spacer(minLength: 4)
1140
+ control
1141
+ }.padding(.top, 3)
1142
+ }
1143
+ }
1144
+ struct SettingsView: View {
1145
+ @ObservedObject var prefs: Prefs
1146
+ var still = false // a rendered capture cannot draw a live text field, so it gets a drawn one
1147
+ var back: () -> Void = {}
1148
+ let levels = [Opt("0", "자세히"), Opt("1", "기본"), Opt("2", "간략"), Opt("3", "최소")]
1149
+ let levelNotes = ["라벨을 길게 풀어 쓰고 모든 칩을 표시합니다", "라벨을 줄이고 모든 칩을 표시합니다", "캐시 적중률과 버전 칩을 빼고 절감 요약 줄을 접습니다", "한도와 컨텍스트와 캐시 만료와 경고만 남깁니다"]
1150
+ func compactText(_ c: CompactS) -> String { c.auto ? "모델 기본값" : c.value.map { "\(Int($0 / 1000))k" } ?? "설정 안 됨" }
1151
+ func compactNote(_ c: CompactS) -> String {
1152
+ if !c.is1m { return "지금 모델은 200k 컨텍스트라 이 값의 영향이 없습니다" }
1153
+ if c.reason == "unset" { return "값이 없어 약 97만 토큰에서야 압축이 걸립니다. \(Int(c.min / 1000))k에서 \(Int(c.max / 1000))k 사이를 권장합니다" }
1154
+ if c.reason == "too-large" { return "값이 커서 압축이 늦게 걸립니다. \(Int(c.min / 1000))k에서 \(Int(c.max / 1000))k 사이를 권장합니다" }
1155
+ switch c.source {
1156
+ case "global": return c.modelKey.map { "전역 설정의 모델별 값(\($0))에서 읽었습니다" } ?? "전역 설정(~/.claude/settings.json)에서 읽었습니다"
1157
+ case "project": return "전역 설정(~/.claude/settings.json)에서 읽었습니다" // the app runs in the home folder, whose project file is the global one
1158
+ case "env": return "환경 변수 CLAUDE_CODE_AUTO_COMPACT_WINDOW에서 읽었습니다. 이 값이 설정 파일보다 앞섭니다"
1159
+ default: return "컨텍스트가 이 크기에 이르면 Claude Code가 대화를 자동으로 요약합니다"
1160
+ }
1161
+ }
1162
+ func clock(_ ms: Double?) -> String {
1163
+ guard let ms = ms else { return "" }
1164
+ let f = DateFormatter(); f.locale = Locale(identifier: "ko_KR"); f.dateFormat = "M월 d일 HH:mm"
1165
+ return f.string(from: Date(timeIntervalSince1970: ms / 1000))
1166
+ }
1167
+ var body: some View {
1168
+ VStack(alignment: .leading, spacing: 10) {
1169
+ HStack(spacing: 6) {
1170
+ Button(action: back) {
1171
+ HStack(spacing: 5) { Image(systemName: "chevron.left").font(.system(size: 13, weight: .semibold)); Text("설정").font(.system(size: 15, weight: .medium)) }.frame(height: 22).contentShape(Rectangle())
1172
+ }.buttonStyle(HoverStyle(radius: 6, grow: 5))
1173
+ Spacer()
1174
+ if prefs.working { Text("적용 중").font(.system(size: 11.5)).foregroundColor(.secondary) }
1175
+ }.padding(.horizontal, 4)
1176
+ if let s = prefs.s {
1177
+ VStack(spacing: 0) {
1178
+ Block(symbol: "arrow.triangle.branch", title: "모델 위임") {
1179
+ SettingRow(label: "하위 모델에 위임", caption: "끄면 다음 세션부터 위임 룰과 힌트를 뺍니다. 등록한 룰은 보관됩니다") {
1180
+ Switch(on: s.routing.enabled, disabled: prefs.working) { prefs.setRouting(!s.routing.enabled) }
1181
+ }
1182
+ SettingRow(label: "한도 창이 끝날 때까지 넓히기", caption: s.routing.relaxed ? "\(clock(s.routing.relaxUntil))까지 위임 범위를 넓힙니다" : "한도가 빠듯할 때 하위 모델에 더 많이 맡깁니다") {
1183
+ Switch(on: s.routing.relaxed, disabled: prefs.working || !s.routing.enabled) { prefs.setRelax(!s.routing.relaxed) }
1184
+ }
1185
+ }
1186
+ Divider().padding(.horizontal, 12)
1187
+ Block(symbol: "rectangle.bottomthird.inset.filled", title: "상태줄") {
1188
+ Text("표시 단계").font(.system(size: 12.5)).padding(.top, 3)
1189
+ Segments(options: levels, selected: String(s.statusline.compact), disabled: prefs.working) { prefs.setLevel(Int($0) ?? 0) }
1190
+ Text(levelNotes[min(3, max(0, s.statusline.compact))]).font(.system(size: 10.5)).foregroundColor(.secondary)
1191
+ if let sample = prefs.samples[min(3, max(0, s.statusline.compact))] {
1192
+ // What this level looks like, in the CLI's own demo render: the labels alone did not say.
1193
+ VStack(alignment: .leading, spacing: 3) {
1194
+ Text("이 단계의 예시").font(.system(size: 10, weight: .medium)).foregroundColor(.secondary)
1195
+ Text(sample).font(.system(size: 10, design: .monospaced)).lineSpacing(2).fixedSize(horizontal: false, vertical: true)
1196
+ }.frame(maxWidth: .infinity, alignment: .leading).padding(8).background(RoundedRectangle(cornerRadius: 6).fill(Color.black.opacity(0.28)))
1197
+ }
1198
+ Text("라벨").font(.system(size: 12.5)).padding(.top, 5)
1199
+ Segments(options: [Opt("icon", "아이콘"), Opt("narrow", "좁은 기호"), Opt("text", "글자")], selected: s.statusline.labels, disabled: prefs.working) { prefs.setLabels($0) }
1200
+ SettingRow(label: "캐시 타이머", caption: "캐시가 만료될 때까지 남은 시간을 표시합니다") {
1201
+ Switch(on: s.statusline.timer, disabled: prefs.working) { prefs.setTimer(!s.statusline.timer) }
1202
+ }
1203
+ }
1204
+ if let c = s.compactWindow {
1205
+ Divider().padding(.horizontal, 12)
1206
+ Block(symbol: "arrow.down.right.and.arrow.up.left", title: "자동 압축 시점: \(compactText(c))") {
1207
+ Text(compactNote(c)).font(.system(size: 10.5)).foregroundColor(c.is1m && !c.ok ? .orange : .secondary).fixedSize(horizontal: false, vertical: true)
1208
+ Segments(options: [Opt("400000", "400k"), Opt("500000", "500k 권장"), Opt("600000", "600k"), Opt("700000", "700k")], selected: c.value.map { String(Int($0)) } ?? "", disabled: prefs.working) { prefs.pendingCompact = Int($0); RELAYOUT() }.padding(.top, 2)
1209
+ if let n = prefs.pendingCompact {
1210
+ HStack(alignment: .center, spacing: 8) {
1211
+ Text("전역 설정의 모든 모델에 \(n / 1000)k를 적용합니다. 같은 파일의 모델별 값은 지워집니다").font(.system(size: 11)).fixedSize(horizontal: false, vertical: true)
1212
+ Spacer(minLength: 4)
1213
+ Pill("취소") { prefs.pendingCompact = nil; RELAYOUT() }
1214
+ Pill("적용", .accent, disabled: prefs.working) { prefs.setCompact(n) }
1215
+ }.padding(8).background(RoundedRectangle(cornerRadius: 6).fill(Color.primary.opacity(0.08)))
1216
+ }
1217
+ SettingRow(label: "값이 없거나 크면 알림", caption: "1M 컨텍스트일 때 상태줄과 세션 시작 안내로 알립니다") {
1218
+ Switch(on: c.warn, disabled: prefs.working) { prefs.setCompactWarn(!c.warn) }
1219
+ }
1220
+ }
1221
+ }
1222
+ Divider().padding(.horizontal, 12)
1223
+ Block(symbol: "building.2", title: "타운") {
1224
+ if s.team.joined {
1225
+ if let t = s.team.teamName { Text("팀: \(t)").font(.system(size: 12)).foregroundColor(.secondary) }
1226
+ Text("표시 이름").font(.system(size: 12.5)).padding(.top, 3)
1227
+ HStack(spacing: 8) {
1228
+ if still {
1229
+ Text(prefs.nameDraft).font(.system(size: 13)).frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 7).padding(.vertical, 4)
1230
+ .background(RoundedRectangle(cornerRadius: 6).fill(Color.primary.opacity(0.10))).overlay(RoundedRectangle(cornerRadius: 6).stroke(Color.primary.opacity(0.18), lineWidth: 1))
1231
+ } else {
1232
+ TextField("타운에 보일 이름", text: $prefs.nameDraft).textFieldStyle(.plain).font(.system(size: 13)).padding(.horizontal, 7).padding(.vertical, 4)
1233
+ .background(RoundedRectangle(cornerRadius: 6).fill(Color.primary.opacity(0.10))).overlay(RoundedRectangle(cornerRadius: 6).stroke(Color.primary.opacity(0.18), lineWidth: 1))
1234
+ .onSubmit { prefs.rename() }.disabled(prefs.working)
1235
+ }
1236
+ Button(action: { prefs.rename() }) {
1237
+ Text("저장").font(.system(size: 12, weight: .medium)).padding(.horizontal, 12).padding(.vertical, 5)
1238
+ .background(RoundedRectangle(cornerRadius: 6).fill(prefs.nameChanged ? Color.accentColor : Color.primary.opacity(0.12))).foregroundColor(prefs.nameChanged ? .white : .secondary)
1239
+ }.buttonStyle(HoverStyle(radius: 6)).disabled(!prefs.nameChanged || prefs.working)
1240
+ }
1241
+ Text("타운과 팀 대시보드에 이 이름으로 나옵니다").font(.system(size: 10.5)).foregroundColor(.secondary)
1242
+ Button(action: { prefs.openTown() }) {
1243
+ HStack(spacing: 5) { Image(systemName: "arrow.up.right.square"); Text("타운 열기") }.font(.system(size: 12, weight: .medium)).padding(.horizontal, 10).padding(.vertical, 5)
1244
+ .background(RoundedRectangle(cornerRadius: 6).fill(Color.primary.opacity(0.12))).contentShape(Rectangle())
1245
+ }.buttonStyle(HoverStyle(radius: 6)).disabled(prefs.working).padding(.top, 4)
1246
+ } else {
1247
+ Text("팀에 참여하지 않았습니다. 터미널에서 sprag team join 으로 참여하면 이름을 정할 수 있습니다").font(.system(size: 12)).foregroundColor(.secondary).fixedSize(horizontal: false, vertical: true)
1248
+ }
1249
+ }
1250
+ Divider().padding(.horizontal, 12)
1251
+ Block(symbol: "globe", title: "안내문 언어") {
1252
+ Segments(options: [Opt("ko", "한국어"), Opt("en", "English")], selected: s.language, disabled: prefs.working) { prefs.setLanguage($0) }.padding(.top, 2)
1253
+ }
1254
+ }.background(RoundedRectangle(cornerRadius: 12).fill(CARD_FILL)).overlay(RoundedRectangle(cornerRadius: 12).stroke(Color.primary.opacity(0.10), lineWidth: 1))
1255
+ } else {
1256
+ Text(prefs.failed ? prefs.note : "설정을 불러오는 중입니다").font(.system(size: 12.5)).foregroundColor(.secondary).frame(maxWidth: .infinity, alignment: .center).padding(.vertical, 26)
1257
+ }
1258
+ if prefs.s != nil && !prefs.note.isEmpty {
1259
+ Text(prefs.note).font(.system(size: 11.5)).foregroundColor(prefs.failed ? .orange : .secondary).lineLimit(3).fixedSize(horizontal: false, vertical: true).padding(.horizontal, 6)
1260
+ }
1261
+ }.padding(12).frame(width: 408)
1262
+ }
1263
+ }
1264
+ enum PillKind { case plain, accent, danger }
1265
+ struct Pill: View {
1266
+ let title: String; let kind: PillKind; let disabled: Bool; let action: () -> Void
1267
+ init(_ title: String, _ kind: PillKind = .plain, disabled: Bool = false, action: @escaping () -> Void) { self.title = title; self.kind = kind; self.disabled = disabled; self.action = action }
1268
+ var body: some View {
1269
+ Button(action: action) {
1270
+ Text(title).font(.system(size: 11.5, weight: .medium)).padding(.horizontal, 10).padding(.vertical, 4)
1271
+ .background(RoundedRectangle(cornerRadius: 6).fill(kind == .accent ? Color.accentColor : kind == .danger ? Color.red.opacity(0.85) : Color.primary.opacity(0.14)))
1272
+ .foregroundColor(kind == .plain ? Color.primary : Color.white).contentShape(Rectangle())
1273
+ }.buttonStyle(HoverStyle(radius: 6)).disabled(disabled).opacity(disabled ? 0.45 : 1).fixedSize()
1274
+ }
1275
+ }
1276
+ struct HeightKey: PreferenceKey { static var defaultValue: CGFloat = 0; static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = max(value, nextValue()) } }
1277
+ /** A scroll view as tall as its content, up to a limit. A scroll view has no height of its own, so the content is measured. */
1278
+ struct FitScroll<Content: View>: View {
1279
+ let limit: CGFloat; var still = false; @ViewBuilder var content: Content
1280
+ @State private var height: CGFloat = 160
1281
+ var body: some View {
1282
+ if still { content } else {
1283
+ ScrollView { content.background(GeometryReader { g in Color.clear.preference(key: HeightKey.self, value: g.size.height) }) }
1284
+ .frame(height: min(max(height, 40), limit))
1285
+ .onPreferenceChange(HeightKey.self) { h in if abs(h - height) > 0.5 { height = h; RELAYOUT() } }
1286
+ }
1287
+ }
1288
+ }
1289
+ struct PageHead: View {
1290
+ let title: String; var busy = false; let back: () -> Void
1291
+ var body: some View {
1292
+ HStack(spacing: 6) {
1293
+ Button(action: back) {
1294
+ HStack(spacing: 5) { Image(systemName: "chevron.left").font(.system(size: 13, weight: .semibold)); Text(title).font(.system(size: 15, weight: .medium)) }.frame(height: 22).contentShape(Rectangle())
1295
+ }.buttonStyle(HoverStyle(radius: 6, grow: 5))
1296
+ Spacer()
1297
+ if busy { Text("적용 중").font(.system(size: 11.5)).foregroundColor(.secondary) }
1298
+ }.padding(.horizontal, 4)
1299
+ }
1300
+ }
1301
+ let CARD = RoundedRectangle(cornerRadius: 12)
1302
+ /** The warnings the statusline is showing, at the top of the panel. A row opens the detail page. */
1303
+ struct WarningList: View {
1304
+ let warnings: [Warn]; let open: (Warn) -> Void
1305
+ var body: some View {
1306
+ let crit = warnings.contains { $0.level == "critical" }
1307
+ HStack(alignment: .top, spacing: 12) {
1308
+ Image(systemName: "exclamationmark.triangle.fill").font(.system(size: 21)).foregroundColor(crit ? .red : .orange).frame(width: 34, height: 26)
1309
+ VStack(alignment: .leading, spacing: 6) {
1310
+ Text("경고 \(warnings.count)건").font(.system(size: 15.5, weight: .semibold))
1311
+ ForEach(warnings) { w in
1312
+ Button(action: { open(w) }) {
1313
+ HStack(alignment: .firstTextBaseline, spacing: 7) {
1314
+ Text(w.chip).font(.system(size: 12.5, weight: .semibold)).foregroundColor(w.level == "critical" ? .red : .orange).fixedSize()
1315
+ Text(w.advice?.first?.title ?? "").font(.system(size: 12)).lineLimit(1).truncationMode(.tail)
1316
+ Spacer(minLength: 4)
1317
+ Image(systemName: "chevron.right").font(.system(size: 10, weight: .semibold)).foregroundColor(.secondary)
1318
+ }.contentShape(Rectangle())
1319
+ }.buttonStyle(HoverStyle(radius: 6, grow: 5))
1320
+ }
1321
+ }.frame(maxWidth: .infinity, alignment: .leading)
1322
+ }.padding(.vertical, 11).padding(.horizontal, 12)
1323
+ }
1324
+ }
1325
+ struct CommandBox: View {
1326
+ let lines: [String]
1327
+ var body: some View {
1328
+ VStack(alignment: .leading, spacing: 4) {
1329
+ ForEach(Array(lines.enumerated()), id: \.offset) { _, l in Text(l).font(.system(size: 11, design: .monospaced)).fixedSize(horizontal: false, vertical: true).textSelection(.enabled) }
1330
+ }.frame(maxWidth: .infinity, alignment: .leading).padding(8).background(RoundedRectangle(cornerRadius: 6).fill(Color.primary.opacity(0.08)))
1331
+ }
1332
+ }
1333
+ struct AdviceView: View {
1334
+ let a: Advice
1335
+ var body: some View {
1336
+ VStack(alignment: .leading, spacing: 6) {
1337
+ if let t = a.title { Text(t).font(.system(size: 13.5, weight: .semibold)).fixedSize(horizontal: false, vertical: true) }
1338
+ if let e = a.explain { Text(e).font(.system(size: 12)).foregroundColor(.secondary).fixedSize(horizontal: false, vertical: true) }
1339
+ ForEach(Array((a.actions ?? []).enumerated()), id: \.offset) { _, act in
1340
+ if let l = act.label { Text(l).font(.system(size: 12, weight: .medium)).fixedSize(horizontal: false, vertical: true).padding(.top, 3) }
1341
+ if let c = act.commands, !c.isEmpty { CommandBox(lines: c) }
1342
+ }
1343
+ if (a.actions ?? []).isEmpty, let tip = a.tip { Text(tip).font(.system(size: 12)).fixedSize(horizontal: false, vertical: true) }
1344
+ }
1345
+ }
1346
+ }
1347
+ /** One warning in full: what it is, since when, and what to do about it, as `sprag last` would print. */
1348
+ struct WarningView: View {
1349
+ let w: Warn?; let now: Double; var limit: CGFloat = 800; var still = false; var back: () -> Void = {}
1350
+ var body: some View {
1351
+ VStack(alignment: .leading, spacing: 10) {
1352
+ PageHead(title: "경고", back: back)
1353
+ if let w = w {
1354
+ let tint: Color = w.level == "critical" ? .red : .orange
1355
+ let when = [w.since.map { "\(sinceText($0, now: now)) 표시 중" } ?? "", resetText(w.resetsAt, now: now)].filter { !$0.isEmpty }.joined(separator: ", ")
1356
+ FitScroll(limit: limit - 70, still: still) {
1357
+ VStack(alignment: .leading, spacing: 10) {
1358
+ Text(w.chip).font(.system(size: 17, weight: .semibold)).foregroundColor(tint)
1359
+ if let d = w.detail { Text(d).font(.system(size: 12.5)).fixedSize(horizontal: false, vertical: true) }
1360
+ if !when.isEmpty { Text(when).font(.system(size: 11.5)).foregroundColor(.secondary) }
1361
+ ForEach(w.advice ?? []) { a in Divider(); AdviceView(a: a) }
1362
+ if (w.advice ?? []).isEmpty { Text("이 경고에 등록된 안내문이 없습니다. 터미널에서 sprag last 로 확인할 수 있습니다").font(.system(size: 12)).foregroundColor(.secondary).fixedSize(horizontal: false, vertical: true) }
1363
+ }.padding(12).frame(maxWidth: .infinity, alignment: .leading)
1364
+ }.background(CARD.fill(CARD_FILL)).overlay(CARD.stroke(Color.primary.opacity(0.10), lineWidth: 1))
1365
+ } else {
1366
+ Text("이 경고는 해소됐습니다").font(.system(size: 12.5)).foregroundColor(.secondary).frame(maxWidth: .infinity, alignment: .center).padding(.vertical, 26)
1367
+ }
1368
+ }.padding(12).frame(width: 408)
1369
+ }
1370
+ }
1371
+ /** One rule: two lines until it is clicked, then the whole text and its buttons. Removal takes a second click. */
1372
+ /** The dates a rule line starts with ("2026-08-01: 2026-08-01: ..."): the first one, and the text without them. */
1373
+ func splitRuleDate(_ text: String) -> (date: String?, body: String) {
1374
+ var rest = Substring(text), first: String? = nil
1375
+ while rest.count > 11 {
1376
+ let head = rest.prefix(10), parts = head.split(separator: "-")
1377
+ guard parts.count == 3, parts[0].count == 4, parts.allSatisfy({ $0.allSatisfy { $0.isNumber } }), rest.dropFirst(10).first == ":" else { break }
1378
+ if first == nil { first = String(head) }
1379
+ rest = rest.dropFirst(11).drop { $0 == " " }
1380
+ }
1381
+ return (first, String(rest))
1382
+ }
1383
+ struct RuleLine: View {
1384
+ @ObservedObject var book: RuleBook
1385
+ let id: String; let tag: String; let text: String
1386
+ var detail = ""; var extra = ""
1387
+ var removeLabel: String? = "삭제"; var removeNote = ""; var remove: () -> Void = {}
1388
+ var second: String? = nil; var secondAction: () -> Void = {}
1389
+ var body: some View {
1390
+ let open = book.expanded == id
1391
+ VStack(alignment: .leading, spacing: 5) {
1392
+ Button(action: { book.expanded = open ? nil : id; book.confirm = nil; RELAYOUT() }) {
1393
+ // The whole rule, always: a rule cut after two lines says nothing. Its date moves under the number so the text starts with the rule.
1394
+ HStack(alignment: .top, spacing: 8) {
1395
+ VStack(alignment: .leading, spacing: 1) {
1396
+ Text(tag).font(.system(size: 11, weight: .semibold, design: .monospaced)).foregroundColor(.secondary)
1397
+ if let d = splitRuleDate(text).date { Text(d.dropFirst(5)).font(.system(size: 9.5, design: .monospaced)).foregroundColor(.secondary).help(d) }
1398
+ }.frame(width: 38, alignment: .leading)
1399
+ Text(splitRuleDate(text).body).font(.system(size: 12)).lineSpacing(2).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true).frame(maxWidth: .infinity, alignment: .leading)
1400
+ Image(systemName: open ? "chevron.up" : "ellipsis").font(.system(size: 11, weight: .semibold)).foregroundColor(.secondary).frame(width: 16, height: 16).help(open ? "접기" : "삭제 같은 동작 보기")
1401
+ }.contentShape(Rectangle())
1402
+ }.buttonStyle(HoverStyle(radius: 6, grow: 4))
1403
+ if open {
1404
+ if !detail.isEmpty { Text(detail).font(.system(size: 11)).foregroundColor(.secondary).fixedSize(horizontal: false, vertical: true).padding(.leading, 46).textSelection(.enabled) }
1405
+ if !extra.isEmpty { Text(extra).font(.system(size: 10.5)).foregroundColor(.secondary).fixedSize(horizontal: false, vertical: true).padding(.leading, 46) }
1406
+ if removeLabel != nil || second != nil {
1407
+ HStack(spacing: 8) {
1408
+ Spacer(minLength: 0)
1409
+ if book.confirm == id {
1410
+ Text(removeNote).font(.system(size: 10.5)).foregroundColor(.secondary).fixedSize(horizontal: false, vertical: true)
1411
+ Pill("취소") { book.confirm = nil; RELAYOUT() }
1412
+ Pill("\(removeLabel ?? "삭제") 확인", .danger, disabled: book.working) { remove() }
1413
+ } else {
1414
+ if let s = second { Pill(s, .accent, disabled: book.working) { secondAction() } }
1415
+ if let r = removeLabel { Pill(r, disabled: book.working) { book.confirm = id; RELAYOUT() } }
1416
+ }
1417
+ }
1418
+ }
1419
+ }
1420
+ }.padding(.vertical, 5)
1421
+ }
1422
+ }
1423
+ struct RuleGroup<Content: View>: View {
1424
+ @ObservedObject var book: RuleBook
1425
+ let id: String; let symbol: String; let title: String; let count: Int
1426
+ var sub = ""; var warn = false
1427
+ @ViewBuilder var content: Content
1428
+ var body: some View {
1429
+ let open = book.open.contains(id)
1430
+ VStack(alignment: .leading, spacing: 0) {
1431
+ Button(action: { if open { book.open.remove(id) } else { book.open.insert(id) }; RELAYOUT() }) {
1432
+ HStack(alignment: .center, spacing: 10) {
1433
+ Image(systemName: symbol).font(.system(size: 17)).frame(width: 28)
1434
+ VStack(alignment: .leading, spacing: 1) {
1435
+ HStack(spacing: 6) {
1436
+ Text(title).font(.system(size: 13.5, weight: .semibold)).lineLimit(1).truncationMode(.middle)
1437
+ Text("\(count)").font(.system(size: 11, weight: .semibold)).monospacedDigit().padding(.horizontal, 6).padding(.vertical, 1).background(Capsule().fill(Color.primary.opacity(0.14)))
1438
+ }
1439
+ if !sub.isEmpty { Text(sub).font(.system(size: 10.5)).foregroundColor(warn ? .orange : .secondary).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true) }
1440
+ }
1441
+ Spacer(minLength: 4)
1442
+ Image(systemName: open ? "chevron.up" : "chevron.down").font(.system(size: 10.5, weight: .semibold)).foregroundColor(.secondary)
1443
+ }.padding(.vertical, 9).padding(.horizontal, 12).contentShape(Rectangle())
1444
+ }.buttonStyle(HoverStyle(radius: 8))
1445
+ if open { VStack(alignment: .leading, spacing: 0) { content }.padding(.horizontal, 12).padding(.bottom, 8) }
1446
+ }
1447
+ }
1448
+ }
1449
+ struct AddRule: View {
1450
+ @ObservedObject var book: RuleBook
1451
+ let id: String; var still = false; let add: (String) -> Void
1452
+ var body: some View {
1453
+ let text = book.drafts[id] ?? ""
1454
+ let ok = text.trimmingCharacters(in: .whitespaces).count >= 8 && text.trimmingCharacters(in: .whitespaces).contains(" ")
1455
+ let box = RoundedRectangle(cornerRadius: 6)
1456
+ HStack(spacing: 8) {
1457
+ if still {
1458
+ Text(text.isEmpty ? "조건이면 행동, 한 줄로 적습니다" : text).font(.system(size: 12)).foregroundColor(.secondary).frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 7).padding(.vertical, 4)
1459
+ .background(box.fill(Color.primary.opacity(0.10))).overlay(box.stroke(Color.primary.opacity(0.18), lineWidth: 1))
1460
+ } else {
1461
+ TextField("조건이면 행동, 한 줄로 적습니다", text: Binding(get: { book.drafts[id] ?? "" }, set: { book.drafts[id] = $0 })).textFieldStyle(.plain).font(.system(size: 12)).padding(.horizontal, 7).padding(.vertical, 4)
1462
+ .background(box.fill(Color.primary.opacity(0.10))).overlay(box.stroke(Color.primary.opacity(0.18), lineWidth: 1))
1463
+ .onSubmit { if ok { add(text) } }.disabled(book.working)
1464
+ }
1465
+ Pill("추가", .accent, disabled: !ok || book.working) { add(text) }
1466
+ }.padding(.top, 7)
1467
+ }
1468
+ }
1469
+ /** Every rule source in one place: what is loaded into each session, and the buttons the CLI already has for it. */
1470
+ struct RulesView: View {
1471
+ @ObservedObject var book: RuleBook
1472
+ var limit: CGFloat = 800; var still = false; var back: () -> Void = {}
1473
+ func num(_ n: Int) -> String { let f = NumberFormatter(); f.numberStyle = .decimal; return f.string(from: NSNumber(value: n)) ?? "\(n)" }
1474
+ func fileNote(_ exists: Bool, _ tokens: Int, _ budget: Int) -> String {
1475
+ if !exists { return "파일이 아직 없습니다" }
1476
+ return "약 \(num(tokens)) 토큰이 모든 요청에 실립니다" + (tokens > budget ? ". 권장 \(num(budget)) 토큰을 넘었습니다" : "")
1477
+ }
1478
+ func ratchetRows(_ rules: [RuleItem], scope: String, root: String?, key: String) -> some View {
1479
+ Group {
1480
+ AddRule(book: book, id: key, still: still) { book.addRatchet(scope: scope, root: root, key: key, text: $0) }
1481
+ Divider()
1482
+ ForEach(rules, id: \.index) { r in
1483
+ RuleLine(book: book, id: "\(key)#\(r.index)", tag: "#\(r.index)", text: r.text, removeNote: "지우기 전 내용은 ratchet.md.bak 에 남깁니다", remove: { book.removeRatchet(scope: scope, root: root, index: r.index, text: r.text) })
1484
+ if r.index != rules.last?.index { Divider() }
1485
+ }
1486
+ }
1487
+ }
1488
+ func modelExtra(_ r: ModelRule) -> String {
1489
+ var parts: [String] = [r.scope == "project" ? "프로젝트 \(r.root.map { ($0 as NSString).lastPathComponent } ?? "")" : "전역"]
1490
+ if r.status == "review" { parts.append("오류율이 기준을 넘어 재검토 필요") }
1491
+ if let c = r.count, c > 0 { parts.append("반복 \(Int(c))회") }
1492
+ if let s = r.savedUsd, s > 0 { parts.append(String(format: "절감 약 $%.0f", s)) }
1493
+ return parts.joined(separator: ", ")
1494
+ }
1495
+ func groups(_ d: Rules) -> some View {
1496
+ VStack(spacing: 0) {
1497
+ RuleGroup(book: book, id: "global", symbol: "globe", title: "전역 래칫", count: d.global.rules.count, sub: fileNote(d.global.exists, d.global.tokens, d.budgetTokens), warn: d.global.tokens > d.budgetTokens) {
1498
+ ratchetRows(d.global.rules, scope: "global", root: nil, key: "global")
1499
+ }
1500
+ ForEach(d.projects, id: \.root) { p in
1501
+ Divider().padding(.horizontal, 12)
1502
+ RuleGroup(book: book, id: "project:\(p.root)", symbol: "folder", title: p.name, count: p.rules.count, sub: "프로젝트 래칫. " + fileNote(p.exists, p.tokens, d.budgetTokens), warn: p.tokens > d.budgetTokens) {
1503
+ ratchetRows(p.rules, scope: "project", root: p.root, key: "project:\(p.root)")
1504
+ }
1505
+ }
1506
+ Divider().padding(.horizontal, 12)
1507
+ RuleGroup(book: book, id: "preset", symbol: "shippingbox", title: "프리셋", count: d.preset.rules.count, sub: d.preset.pending.isEmpty ? "sprag에 동봉된 추천 룰 가운데 전역으로 등록한 것입니다" : "아직 답하지 않은 추천이 \(d.preset.pending.count)개 있습니다") {
1508
+ ForEach(d.preset.pending, id: \.id) { r in
1509
+ RuleLine(book: book, id: "pending:\(r.id)", tag: "추천", text: r.text, extra: r.id, removeLabel: "건너뛰기", removeNote: "다시 권하지 않습니다", remove: { book.skipPreset(r.id) }, second: "전역 등록", secondAction: { book.acceptPreset(r.id) })
1510
+ Divider()
1511
+ }
1512
+ ForEach(d.preset.rules, id: \.id) { r in
1513
+ RuleLine(book: book, id: "preset:\(r.id)", tag: "등록", text: r.text, extra: r.id, removeLabel: "빼기", removeNote: "프리셋 파일에서 빼고 다시 권하지 않습니다", remove: { book.skipPreset(r.id) })
1514
+ Divider()
1515
+ }
1516
+ }
1517
+ Divider().padding(.horizontal, 12)
1518
+ RuleGroup(book: book, id: "model", symbol: "arrow.triangle.branch", title: "모델 위임 룰", count: d.model.rules.count, sub: d.model.enabled ? "작업 기록을 보고 자동으로 갱신하는 룰입니다" : "모델 위임이 꺼져 있어 지금은 적용되지 않습니다", warn: !d.model.enabled) {
1519
+ ForEach(d.model.rules, id: \.index) { r in
1520
+ RuleLine(book: book, id: "model#\(r.index)", tag: r.tier ?? "#\(r.index)", text: r.label ?? r.text, detail: r.text, extra: modelExtra(r), removeNote: "등록부에서 지웁니다. 되돌리려면 다시 등록해야 합니다", remove: { book.removeModel(index: r.index, text: r.text) })
1521
+ Divider()
1522
+ }
1523
+ }
1524
+ Divider().padding(.horizontal, 12)
1525
+ RuleGroup(book: book, id: "team", symbol: "person.2", title: "조직과 팀 규칙", count: d.team.rules.count, sub: !d.team.joined ? "팀에 참여하지 않았습니다" : d.team.rules.isEmpty ? "관리자가 내려보낸 규칙이 없습니다" : "관리자가 정한 규칙이라 여기서는 볼 수만 있습니다") {
1526
+ ForEach(Array(d.team.rules.enumerated()), id: \.offset) { i, r in
1527
+ RuleLine(book: book, id: "team:\(i)", tag: r.level == "org" ? "조직" : "팀", text: r.text, extra: r.scope == "model" ? "모델 위임 규칙" : "래칫 규칙", removeLabel: nil)
1528
+ Divider()
1529
+ }
1530
+ }
1531
+ }
1532
+ }
1533
+ var body: some View {
1534
+ VStack(alignment: .leading, spacing: 10) {
1535
+ PageHead(title: "규칙", busy: book.working, back: back)
1536
+ if let d = book.data {
1537
+ FitScroll(limit: limit - 96, still: still) { groups(d) }
1538
+ .background(CARD.fill(CARD_FILL)).overlay(CARD.stroke(Color.primary.opacity(0.10), lineWidth: 1))
1539
+ } else {
1540
+ Text(book.failed ? book.note : "규칙을 불러오는 중입니다").font(.system(size: 12.5)).foregroundColor(.secondary).frame(maxWidth: .infinity, alignment: .center).padding(.vertical, 26)
1541
+ }
1542
+ if book.data != nil && !book.note.isEmpty {
1543
+ Text(book.note).font(.system(size: 11.5)).foregroundColor(book.failed ? .orange : .secondary).lineLimit(3).fixedSize(horizontal: false, vertical: true).padding(.horizontal, 6)
1544
+ }
1545
+ }.padding(12).frame(width: 408)
1546
+ }
1547
+ }
1548
+ struct ToolLine: View {
1549
+ let c: ToolCall; let now: Double
1550
+ var body: some View {
1551
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
1552
+ Circle().fill(c.pending == true ? Color.green : Color.primary.opacity(0.25)).frame(width: 5, height: 5).offset(y: -2)
1553
+ Text(toolName(c.tool)).font(.system(size: 11, weight: .medium, design: .monospaced)).lineLimit(1).fixedSize()
1554
+ Text(c.target ?? "").font(.system(size: 11)).foregroundColor(.secondary).lineLimit(4).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true)
1555
+ Spacer(minLength: 4)
1556
+ Text(c.pending == true ? "실행 중" : agoText(c.at, now: now)).font(.system(size: 10)).foregroundColor(c.pending == true ? .green : .secondary).fixedSize()
1557
+ }
1558
+ }
1559
+ }
1560
+ /** What a session is working on: the request, the last reply, the recent tool calls and the heaviest child processes. */
1561
+ struct WorkSummary: View {
1562
+ let d: Detail?; let now: Double
1563
+ var textLines = 5; var calls = 8; var procs = 5; var off = false
1564
+ func head(_ title: String, _ side: String = "") -> some View {
1565
+ HStack { Text(title).font(.system(size: 10.5, weight: .semibold)).foregroundColor(.secondary); Spacer(); Text(side).font(.system(size: 10)).foregroundColor(.secondary) }.padding(.top, 3)
1566
+ }
1567
+ var body: some View {
1568
+ VStack(alignment: .leading, spacing: 4) {
1569
+ if let d = d {
1570
+ head("요청", agoText(d.prompt?.at, now: now))
1571
+ Text(d.prompt?.text ?? "최근 기록에서 요청을 찾지 못했습니다").font(.system(size: 12)).foregroundColor(d.prompt == nil ? .secondary : .primary).lineLimit(textLines).fixedSize(horizontal: false, vertical: true)
1572
+ if let r = d.reply {
1573
+ head("마지막 응답", agoText(r.at, now: now))
1574
+ Text(r.text).font(.system(size: 11.5)).foregroundColor(.secondary).lineLimit(textLines).fixedSize(horizontal: false, vertical: true)
1575
+ }
1576
+ let recent = Array((d.recent ?? []).suffix(calls).reversed())
1577
+ if !recent.isEmpty {
1578
+ head("최근 도구 호출")
1579
+ ForEach(Array(recent.enumerated()), id: \.offset) { _, c in ToolLine(c: c, now: now) }
1580
+ }
1581
+ let ps = Array((d.procs ?? []).prefix(procs))
1582
+ if !ps.isEmpty {
1583
+ head("자식 프로세스")
1584
+ ForEach(ps, id: \.pid) { p in
1585
+ HStack(spacing: 6) {
1586
+ Text(p.name).font(.system(size: 11, design: .monospaced)).lineLimit(1).truncationMode(.middle)
1587
+ Spacer(minLength: 4)
1588
+ Text(p.cpuPct.map { pct1($0) } ?? "-").font(.system(size: 11)).monospacedDigit().frame(width: 46, alignment: .trailing)
1589
+ Text(memText(p.rssMb)).font(.system(size: 11)).monospacedDigit().foregroundColor(.secondary).frame(width: 58, alignment: .trailing)
1590
+ }
1591
+ }
1592
+ }
1593
+ } else {
1594
+ Text(off ? "이 sprag 버전은 세션 상세를 내지 않습니다" : "상세를 불러오는 중입니다").font(.system(size: 11.5)).foregroundColor(.secondary).padding(.vertical, 6)
1595
+ }
1596
+ }
1597
+ }
1598
+ }
1599
+ struct Fact: View {
1600
+ let label: String; let value: String
1601
+ var body: some View {
1602
+ HStack(alignment: .firstTextBaseline, spacing: 8) {
1603
+ Text(label).foregroundColor(.secondary).frame(width: 62, alignment: .leading)
1604
+ Text(value).monospacedDigit().fixedSize(horizontal: false, vertical: true)
1605
+ Spacer(minLength: 0)
1606
+ }.font(.system(size: 11.5))
1607
+ }
1608
+ }
1609
+ func tokenLine(_ u: SUsage) -> String { "입력 \(tokText(u.tokens.input)), 캐시 읽기 \(tokText(u.tokens.cacheRead)), 캐시 쓰기 \(tokText(u.tokens.cacheWrite)), 출력 \(tokText(u.tokens.output))" }
1610
+ func contextLine(_ c: Ctx) -> String { c.pct.map { "\(Int($0))% (\(tokText(c.tokens))" + (c.window.map { " / \(tokText($0)))" } ?? ")") } ?? tokText(c.tokens) }
1611
+ /** One session in full, opened by clicking its row. */
1612
+ struct SessionView: View {
1613
+ let s: Session?; let cpu: Double; let mem: Double; let now: Double
1614
+ var off = false; var limit: CGFloat = 800; var still = false; var back: () -> Void = {}
1615
+ var body: some View {
1616
+ VStack(alignment: .leading, spacing: 10) {
1617
+ PageHead(title: "세션", back: back)
1618
+ if let s = s {
1619
+ FitScroll(limit: limit - 70, still: still) {
1620
+ VStack(alignment: .leading, spacing: 6) {
1621
+ HStack(spacing: 7) { Badge(agent: s.agent); Text(s.name ?? s.agent).font(.system(size: 15, weight: .semibold)).lineLimit(1).truncationMode(.middle) }
1622
+ if let c = s.cwd { Text(c).font(.system(size: 10.5, design: .monospaced)).foregroundColor(.secondary).lineLimit(1).truncationMode(.head).textSelection(.enabled) }
1623
+ HStack(spacing: 6) { Circle().fill(stateColor(s)).frame(width: 7, height: 7); Text(activity(s, now: now)).font(.system(size: 12)) }
1624
+ Divider().padding(.vertical, 2)
1625
+ Fact(label: "모델", value: [s.modelName ?? s.model ?? "알 수 없음", s.effort.map { "effort \($0)" } ?? ""].filter { !$0.isEmpty }.joined(separator: ", "))
1626
+ if let c = s.context { Fact(label: "컨텍스트", value: contextLine(c)) }
1627
+ if let u = s.usage {
1628
+ Fact(label: "토큰", value: tokenLine(u))
1629
+ Fact(label: "비용", value: [u.costUsd.map { String(format: "$%.2f (정가 환산)", $0) } ?? "가격표 없음", u.requests.map { "요청 \(Int($0))회" } ?? ""].filter { !$0.isEmpty }.joined(separator: ", "))
1630
+ }
1631
+ Fact(label: "자원", value: s.cpu == nil ? "측정 못 함" : "CPU \(pct1(cpu)) (기기 전체 기준), 메모리 \(memText(mem)), 프로세스 \(s.procs ?? 0)개")
1632
+ Fact(label: "PID", value: String(s.pid))
1633
+ Divider().padding(.vertical, 2)
1634
+ WorkSummary(d: s.detail, now: now, off: off)
1635
+ }.padding(12).frame(maxWidth: .infinity, alignment: .leading)
1636
+ }.background(CARD.fill(CARD_FILL)).overlay(CARD.stroke(Color.primary.opacity(0.10), lineWidth: 1))
1637
+ } else {
1638
+ Text("이 세션은 끝났습니다").font(.system(size: 12.5)).foregroundColor(.secondary).frame(maxWidth: .infinity, alignment: .center).padding(.vertical, 26)
1639
+ }
1640
+ }.padding(12).frame(width: 408)
1641
+ }
1642
+ }
1643
+ func hex(_ v: UInt32) -> Color { Color(red: Double((v >> 16) & 0xff) / 255, green: Double((v >> 8) & 0xff) / 255, blue: Double(v & 0xff) / 255) }
1644
+ /** Chart colours: the two agent hues and the status steps, each chosen for its surface and checked for colour-blind separation and contrast. */
1645
+ struct Pal {
1646
+ let dark: Bool
1647
+ var surface: Color { dark ? hex(0x1a1a19) : hex(0xfcfcfb) }
1648
+ var tile: Color { dark ? hex(0x2a2a29) : hex(0xefeeea) }
1649
+ var group: Color { dark ? hex(0x212120) : hex(0xf6f5f2) } // the plate under one project's tiles, a step off the surface
1650
+ var well: Color { dark ? hex(0x313130) : hex(0xe6e5e1) }
1651
+ var text: Color { dark ? hex(0xf2f1ec) : hex(0x0b0b0b) }
1652
+ var text2: Color { dark ? hex(0xc3c2b7) : hex(0x52514e) }
1653
+ var neutral: Color { dark ? hex(0x8f8e86) : hex(0x8a8982) } // a series that belongs to no agent, such as the whole machine
1654
+ var claude: Color { dark ? hex(0xd95926) : hex(0xeb6834) }
1655
+ var codex: Color { dark ? hex(0x199e70) : hex(0x1baf7a) }
1656
+ var left: Color { dark ? hex(0x9085e9) : hex(0x6250d6) } // what ended sessions left running
1657
+ let warning = hex(0xfab219), critical = hex(0xd03b3b), good = hex(0x0ca30c)
1658
+ /** The colour of a state. The agent's own colour stays on its badge; it never says how a session is doing. */
1659
+ func state(_ p: Phase) -> Color { p == .active ? good : p == .needsUser ? warning : neutral }
1660
+ func agent(_ a: String) -> Color { a == "codex" ? codex : claude }
1661
+ }
1662
+ func spanText(_ from: Double?, _ to: Double?) -> String {
1663
+ guard let a = from, let b = to, b > a else { return "" }
1664
+ let sec = Int(b - a)
1665
+ return sec < 90 ? "최근 \(sec)초" : "최근 \(Int((Double(sec) / 60).rounded()))분"
1666
+ }
1667
+ func toolSymbol(_ t: String) -> String {
1668
+ switch t {
1669
+ case "Bash": return "terminal"
1670
+ case "Read": return "doc.text"
1671
+ case "Edit", "Write", "NotebookEdit": return "pencil"
1672
+ case "Grep", "Glob": return "magnifyingglass"
1673
+ case "Agent", "Task": return "person.2"
1674
+ case "WebSearch", "WebFetch": return "globe"
1675
+ case "Skill": return "sparkles"
1676
+ case "TodoWrite": return "checklist"
1677
+ default: return t.hasPrefix("mcp__") ? "puzzlepiece.extension" : "wrench.and.screwdriver"
1678
+ }
1679
+ }
1680
+ func stateMark(_ s: Session) -> (symbol: String, label: String) {
1681
+ switch s.state {
1682
+ case "busy": return ("bolt.fill", "작업 중")
1683
+ case "idle": return ("pause.circle", "입력 대기")
1684
+ case "shell": return ("terminal.fill", "셸 실행")
1685
+ case "waiting": return ("hand.raised.fill", "확인 대기")
1686
+ default: return ("questionmark.circle", s.state ?? "상태 모름")
1687
+ }
1688
+ }
1689
+ /** A trend line: 2 pt line over a faint wash, and a ringed dot on the newest value. Several series share one scale through `top`. */
1690
+ struct Spark: View {
1691
+ let values: [Double]; let color: Color; let surface: Color
1692
+ var top: Double? = nil; var slots = 60; var dot = true
1693
+ var body: some View {
1694
+ GeometryReader { g in
1695
+ let hi = max(top ?? 0, values.max() ?? 0, 0.000001)
1696
+ let step = (g.size.width - 12) / CGFloat(max(1, slots - 1))
1697
+ let pts: [CGPoint] = values.enumerated().map { i, v in
1698
+ CGPoint(x: g.size.width - 6 - CGFloat(values.count - 1 - i) * step, y: 5 + (g.size.height - 10) * (1 - CGFloat(min(1, max(0, v / hi)))))
1699
+ }
1700
+ ZStack {
1701
+ if pts.count > 1 {
1702
+ Path { p in p.move(to: CGPoint(x: pts[0].x, y: g.size.height)); for q in pts { p.addLine(to: q) }; p.addLine(to: CGPoint(x: pts[pts.count - 1].x, y: g.size.height)); p.closeSubpath() }.fill(color.opacity(0.10))
1703
+ Path { p in p.move(to: pts[0]); for q in pts.dropFirst() { p.addLine(to: q) } }.stroke(color, style: StrokeStyle(lineWidth: 2, lineCap: .round, lineJoin: .round))
1704
+ }
1705
+ if dot, let last = pts.last { Circle().fill(color).frame(width: 8, height: 8).overlay(Circle().stroke(surface, lineWidth: 2).frame(width: 10, height: 10)).position(last) }
1706
+ }
1707
+ }
1708
+ }
1709
+ }
1710
+ /**
1711
+ * A trend that can be read: the top and bottom of the scale are printed, the caption gives the time it covers and the
1712
+ * highest value in it, and every series has its name and latest value. The line always spans the whole width, so a
1713
+ * short history is a coarse line, not a sliver at one edge.
1714
+ */
1715
+ struct TrendChart: View {
1716
+ struct Line: Identifiable { let id: String; let values: [Double]; let color: Color; var fill = false }
1717
+ let title: String; let lines: [Line]; let top: Double; let fmt: (Double) -> String; let span: String; let pal: Pal
1718
+ var height: CGFloat = 44
1719
+ func points(_ v: [Double], _ size: CGSize) -> [CGPoint] {
1720
+ guard v.count > 1 else { return [] }
1721
+ let step = size.width / CGFloat(v.count - 1), hi = max(top, 0.000001)
1722
+ return v.enumerated().map { i, x in CGPoint(x: CGFloat(i) * step, y: 1 + (size.height - 2) * (1 - CGFloat(min(1, max(0, x / hi))))) }
1723
+ }
1724
+ var body: some View {
1725
+ let peak = lines.first?.values.max() ?? 0
1726
+ VStack(alignment: .leading, spacing: 3) {
1727
+ HStack(spacing: 8) {
1728
+ Text(title).font(.system(size: 11.5, weight: .semibold)).foregroundColor(pal.text).fixedSize()
1729
+ ForEach(lines) { l in
1730
+ HStack(spacing: 3) { Circle().fill(l.color).frame(width: 6, height: 6); Text("\(l.id) \(fmt(l.values.last ?? 0))").font(.system(size: 10.5)).monospacedDigit().foregroundColor(pal.text2) }.fixedSize()
1731
+ }
1732
+ Spacer(minLength: 0)
1733
+ }
1734
+ HStack(alignment: .top, spacing: 5) {
1735
+ VStack(alignment: .trailing, spacing: 0) {
1736
+ Text(fmt(top)).font(.system(size: 9.5)).monospacedDigit().foregroundColor(pal.text2)
1737
+ Spacer(minLength: 0)
1738
+ Text(fmt(0)).font(.system(size: 9.5)).monospacedDigit().foregroundColor(pal.text2)
1739
+ }.frame(width: 42, height: height, alignment: .trailing)
1740
+ GeometryReader { g in
1741
+ ZStack {
1742
+ Path { p in
1743
+ p.move(to: CGPoint(x: 0, y: 0.5)); p.addLine(to: CGPoint(x: g.size.width, y: 0.5))
1744
+ p.move(to: CGPoint(x: 0, y: g.size.height - 0.5)); p.addLine(to: CGPoint(x: g.size.width, y: g.size.height - 0.5))
1745
+ }.stroke(pal.well, lineWidth: 1)
1746
+ ForEach(lines) { l in
1747
+ let pts = points(l.values, g.size)
1748
+ if pts.count > 1 {
1749
+ if l.fill { Path { p in p.move(to: CGPoint(x: pts[0].x, y: g.size.height)); for q in pts { p.addLine(to: q) }; p.addLine(to: CGPoint(x: pts[pts.count - 1].x, y: g.size.height)); p.closeSubpath() }.fill(l.color.opacity(0.12)) }
1750
+ Path { p in p.move(to: pts[0]); for q in pts.dropFirst() { p.addLine(to: q) } }.stroke(l.color, style: StrokeStyle(lineWidth: 2, lineCap: .round, lineJoin: .round))
1751
+ }
1752
+ }
1753
+ }
1754
+ }.frame(height: height)
1755
+ }
1756
+ Text(span.isEmpty ? "값을 모으는 중입니다" : "\(span), 최고 \(fmt(peak))").font(.system(size: 9.5)).monospacedDigit().foregroundColor(pal.text2).padding(.leading, 47)
1757
+ }
1758
+ }
1759
+ }
1760
+ /** One ratio against a limit. The track is a lighter step of the fill's own hue, so the state reads along the whole bar. */
1761
+ struct Meter: View {
1762
+ let value: Double; let fill: Color; var height: CGFloat = 8; var tick: Double? = nil; var tickColor: Color = .white
1763
+ var body: some View {
1764
+ GeometryReader { g in
1765
+ ZStack(alignment: .leading) {
1766
+ Capsule().fill(fill.opacity(0.24))
1767
+ if value > 0.0005 { Capsule().fill(fill).frame(width: max(3, g.size.width * CGFloat(min(1, max(0, value))))) }
1768
+ if let t = tick { Rectangle().fill(tickColor).frame(width: 2, height: height + 4).offset(x: g.size.width * CGFloat(min(1, max(0, t))) - 1) }
1769
+ }
1770
+ }.frame(height: height)
1771
+ }
1772
+ }
1773
+ /** What a use percentage means: past 90 it is critical, past 70 a warning. The colour never stands alone; `symbol` goes with it. */
1774
+ func severity(_ pct: Double, _ base: Color, _ pal: Pal, warnAt: Double = 70, critAt: Double = 90) -> (color: Color, symbol: String?) {
1775
+ pct >= critAt ? (pal.critical, "exclamationmark.octagon.fill") : pct >= warnAt ? (pal.warning, "exclamationmark.triangle.fill") : (base, nil)
1776
+ }
1777
+ struct StatTile<Plot: View>: View {
1778
+ let label: String; let value: String; var note = ""; let pal: Pal; @ViewBuilder var plot: Plot
1779
+ var body: some View {
1780
+ VStack(alignment: .leading, spacing: 3) {
1781
+ Text(label).font(.system(size: 11)).foregroundColor(pal.text2).lineLimit(1)
1782
+ Text(value).font(.system(size: 22, weight: .semibold)).foregroundColor(pal.text).lineLimit(1).minimumScaleFactor(0.7)
1783
+ plot.frame(height: 34)
1784
+ Text(note.isEmpty ? " " : note).font(.system(size: 10)).foregroundColor(pal.text2).lineLimit(1)
1785
+ }.padding(12).frame(maxWidth: .infinity, minHeight: 118, alignment: .topLeading).background(RoundedRectangle(cornerRadius: 10).fill(pal.tile))
1786
+ }
1787
+ }
1788
+ struct ToolIcon: View {
1789
+ let c: ToolCall; let tint: Color; let pal: Pal
1790
+ var body: some View {
1791
+ let on = c.pending == true
1792
+ Image(systemName: toolSymbol(c.tool)).font(.system(size: 11, weight: .medium)).foregroundColor(on ? Color.white : pal.text2)
1793
+ .frame(width: 22, height: 22).background(RoundedRectangle(cornerRadius: 5).fill(on ? tint : pal.well))
1794
+ .help("\(toolName(c.tool))" + ((c.target ?? "").isEmpty ? "" : ": \(c.target ?? "")") + (on ? " (실행 중)" : ""))
1795
+ }
1796
+ }
1797
+ struct IconStat: View {
1798
+ let symbol: String; let value: String; let tip: String; let pal: Pal
1799
+ var label = "" // a word in place of the icon, for figures no icon says (tokens, processes)
1800
+ var body: some View {
1801
+ HStack(spacing: 4) {
1802
+ if label.isEmpty { Image(systemName: symbol).font(.system(size: 10.5)).foregroundColor(pal.text2) } else { Text(label).font(.system(size: 11)).foregroundColor(pal.text2) }
1803
+ Text(value).font(.system(size: 11.5, weight: .medium)).monospacedDigit().foregroundColor(pal.text)
1804
+ }.lineLimit(1).fixedSize().help(tip) // the name beside it gives way, never the number
1805
+ }
1806
+ }
1807
+ /** A session that another session started, in one line: they come in batches and each is small. */
1808
+ struct SubTile: View {
1809
+ let s: Session; let now: Double; let selected: Bool; let pal: Pal; let phase: Phase
1810
+ var body: some View {
1811
+ let tint = pal.agent(s.agent), mark = stateMark(s), edge = pal.state(phase)
1812
+ HStack(spacing: 7) {
1813
+ Image(systemName: "arrow.turn.down.right").font(.system(size: 10, weight: .semibold)).foregroundColor(pal.text2)
1814
+ if phase == .active { LiveDot(color: edge) } else { Image(systemName: mark.symbol).font(.system(size: 10.5)).foregroundColor(phase == .idle ? pal.text2 : edge).frame(width: 12) }
1815
+ Text(s.name ?? s.agent).font(.system(size: 12, weight: .medium)).foregroundColor(pal.text).lineLimit(1).truncationMode(.head)
1816
+ Spacer(minLength: 4)
1817
+ Text("\(mark.label) \(sinceText(s.stateSince, now: now))").font(.system(size: 10.5)).foregroundColor(pal.text2).lineLimit(1).fixedSize()
1818
+ if let c = s.context { Text(c.pct.map { "\(Int($0))%" } ?? tokText(c.tokens)).font(.system(size: 11, weight: .medium)).monospacedDigit().foregroundColor(pal.text).fixedSize().help("컨텍스트") }
1819
+ if let c = s.usage?.costUsd { Text(String(format: "$%.2f", c)).font(.system(size: 11, weight: .medium)).monospacedDigit().foregroundColor(pal.text).fixedSize() }
1820
+ Button(action: { jump(to: s) }) { Image(systemName: "arrow.up.forward.app").font(.system(size: 12)).foregroundColor(pal.text2).frame(width: 22, height: 18).contentShape(Rectangle()) }
1821
+ .buttonStyle(HoverStyle(radius: 5)).help("이 세션이 열려 있는 터미널로 이동")
1822
+ }.opacity(phase == .idle ? 0.55 : 1).padding(.horizontal, 10).padding(.vertical, 8).frame(maxWidth: .infinity, alignment: .leading)
1823
+ .background(RoundedRectangle(cornerRadius: 9).fill(pal.tile)).overlay(RoundedRectangle(cornerRadius: 9).stroke(selected ? tint : Color.clear, lineWidth: 2)).contentShape(Rectangle())
1824
+ }
1825
+ }
1826
+ /** One session as marks: its state, how full its context is, its load over time and what it has been calling. The words are behind a click. */
1827
+ struct SessionTile: View {
1828
+ let s: Session; let cpu: Double; let mem: Double; let gpu: Double; let hist: [Hist]; let now: Double; let selected: Bool; let pal: Pal
1829
+ var parentName: String? = nil
1830
+ var use: Usage? = nil
1831
+ var phase: Phase = .active
1832
+ var work: [(name: String, w: Work)] = []
1833
+ var subs = 0, subsActive = 0 // sessions this one started, and how many of them are working
1834
+ func mini<V: View>(_ label: String, _ value: String, @ViewBuilder _ plot: () -> V) -> some View {
1835
+ VStack(alignment: .leading, spacing: 3) {
1836
+ Text(label).font(.system(size: 10)).foregroundColor(pal.text2)
1837
+ Text(value).font(.system(size: 15, weight: .semibold)).foregroundColor(pal.text).lineLimit(1).minimumScaleFactor(0.7)
1838
+ plot().frame(height: 22)
1839
+ }.frame(maxWidth: .infinity, alignment: .leading)
1840
+ }
1841
+ var body: some View {
1842
+ let tint = pal.agent(s.agent), mark = stateMark(s)
1843
+ let calls = Array((s.detail?.recent ?? []).suffix(12))
1844
+ let pending = phase == .idle ? nil : calls.last { $0.pending == true }
1845
+ let edge = pal.state(phase)
1846
+ // A session whose agent sits at its prompt while its programs work is working: say so, not "waiting for input".
1847
+ let byLoad = phase == .active && s.state != "busy" && s.state != "shell" && s.subagents == 0
1848
+ VStack(alignment: .leading, spacing: 10) {
1849
+ HStack(spacing: 7) {
1850
+ Text(s.agent == "codex" ? "Codex" : "Claude").font(.system(size: 9.5, weight: .bold)).foregroundColor(.white).padding(.horizontal, 6).padding(.vertical, 2).background(Capsule().fill(tint)).fixedSize()
1851
+ if let up = parentName { Image(systemName: "arrow.turn.down.right").font(.system(size: 10.5, weight: .semibold)).foregroundColor(pal.text2).help("\(up) 세션이 띄운 세션") }
1852
+ Text(s.name ?? s.agent).font(.system(size: 13.5, weight: .semibold)).foregroundColor(pal.text).lineLimit(1).truncationMode(.middle).help(s.name ?? s.agent)
1853
+ Spacer(minLength: 6)
1854
+ }
1855
+ HStack(spacing: 5) {
1856
+ if phase == .active { LiveDot(color: edge) }
1857
+ Image(systemName: byLoad ? "gearshape.2.fill" : mark.symbol).font(.system(size: 11)).foregroundColor(phase == .idle ? pal.text2 : edge)
1858
+ Text(byLoad ? "프로그램 실행 중" : mark.label).font(.system(size: 11.5, weight: phase == .idle ? .medium : .semibold)).foregroundColor(pal.text)
1859
+ Text(sinceText(s.stateSince, now: now)).font(.system(size: 11)).foregroundColor(pal.text2)
1860
+ Spacer(minLength: 4)
1861
+ Text([s.modelName ?? "", s.effort ?? ""].filter { !$0.isEmpty }.joined(separator: " ")).font(.system(size: 11)).foregroundColor(pal.text2).lineLimit(1)
1862
+ }
1863
+ HStack(alignment: .top, spacing: 12) {
1864
+ if let c = s.context, let p = c.pct {
1865
+ let sv = severity(p, tint, pal, warnAt: 80, critAt: 95)
1866
+ mini("컨텍스트", "\(Int(p))%") {
1867
+ HStack(spacing: 5) { Meter(value: p / 100, fill: sv.color); if let sym = sv.symbol { Image(systemName: sym).font(.system(size: 10)).foregroundColor(sv.color) } }.frame(maxHeight: .infinity, alignment: .center)
1868
+ }
1869
+ } else { mini("컨텍스트", s.context.map { tokText($0.tokens) } ?? "-") { Color.clear } }
1870
+ // Each bar is this session's share of the whole machine, the same scale on every tile. The session's own trend is in its detail.
1871
+ mini("CPU", s.cpu == nil ? "-" : pct1(cpu)) { Meter(value: cpu / 100, fill: tint).frame(maxHeight: .infinity, alignment: .center).help("막대는 기기 전체 CPU에서 이 세션이 쓰는 몫입니다") }
1872
+ mini("메모리", s.rssMb == nil ? "-" : memText(mem)) { Meter(value: mem / RAM_MB, fill: tint).frame(maxHeight: .infinity, alignment: .center).help("막대는 기기 메모리 \(Int((RAM_MB / 1024).rounded())) GB에서 이 세션이 쓰는 몫입니다") }
1873
+ mini("GPU", pct1(gpu * 100)) { Meter(value: gpu, fill: tint).frame(maxHeight: .infinity, alignment: .center).help("막대는 GPU 시간에서 이 세션이 쓰는 몫입니다") }
1874
+ }
1875
+ // What is running now: the tool call in flight and the heaviest programs. A resting session shows its last calls instead.
1876
+ VStack(alignment: .leading, spacing: 4) {
1877
+ if let p = pending {
1878
+ HStack(spacing: 6) {
1879
+ ToolIcon(c: p, tint: tint, pal: pal)
1880
+ Text((p.target ?? "").isEmpty ? toolName(p.tool) : (p.target ?? "")).font(.system(size: 11.5)).foregroundColor(pal.text).lineLimit(1).truncationMode(.tail)
1881
+ Spacer(minLength: 0)
1882
+ }
1883
+ }
1884
+ if subs > 0 && pending == nil {
1885
+ HStack(spacing: 6) {
1886
+ Image(systemName: "arrow.turn.down.right").font(.system(size: 10, weight: .bold)).foregroundColor(.white).frame(width: 22, height: 22).background(RoundedRectangle(cornerRadius: 5).fill(subsActive > 0 ? tint : pal.well))
1887
+ Text("띄운 세션 \(subs)개").font(.system(size: 11.5, weight: .medium)).foregroundColor(pal.text)
1888
+ Spacer(minLength: 4)
1889
+ Text("작업 중 \(subsActive)").font(.system(size: 11.5, weight: .medium)).monospacedDigit().foregroundColor(pal.text)
1890
+ }
1891
+ }
1892
+ ForEach(Array(work.prefix(pending == nil && subs == 0 ? 2 : 1).enumerated()), id: \.offset) { _, it in
1893
+ HStack(spacing: 6) {
1894
+ Image(systemName: "gearshape.2.fill").font(.system(size: 10)).foregroundColor(.white).frame(width: 22, height: 22).background(RoundedRectangle(cornerRadius: 5).fill(tint))
1895
+ Text(it.name).font(.system(size: 11.5, weight: .medium)).foregroundColor(pal.text).lineLimit(2).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true)
1896
+ Spacer(minLength: 4)
1897
+ if it.w.gpu >= 0.01 { IconStat(symbol: "display", value: pct1(it.w.gpu * 100), tip: "이 프로그램의 GPU", pal: pal) }
1898
+ if it.w.cpu >= 0.004 { IconStat(symbol: "cpu", value: pct1(it.w.cpu * 100), tip: "이 프로그램의 CPU, 기기 전체 대비", pal: pal) }
1899
+ if it.w.mem >= 512 { IconStat(symbol: "memorychip", value: memText(it.w.mem), tip: "이 프로그램의 메모리", pal: pal) }
1900
+ }
1901
+ }
1902
+ if pending == nil && work.isEmpty && subs == 0 && phase == .active && s.state == "busy" {
1903
+ HStack(spacing: 6) {
1904
+ Image(systemName: "ellipsis.bubble.fill").font(.system(size: 10)).foregroundColor(.white).frame(width: 22, height: 22).background(RoundedRectangle(cornerRadius: 5).fill(tint))
1905
+ Text("응답을 쓰는 중").font(.system(size: 11.5)).foregroundColor(pal.text)
1906
+ Spacer(minLength: 0)
1907
+ }
1908
+ } else if pending == nil && work.isEmpty && subs == 0 {
1909
+ HStack(spacing: 4) {
1910
+ if calls.isEmpty { Text(s.detail == nil ? " " : "최근 도구 호출 없음").font(.system(size: 10.5)).foregroundColor(pal.text2).frame(height: 22) }
1911
+ ForEach(Array(calls.enumerated()), id: \.offset) { _, c in ToolIcon(c: c, tint: tint, pal: pal) }
1912
+ Spacer(minLength: 0)
1913
+ }
1914
+ }
1915
+ }.frame(height: 48, alignment: .top)
1916
+ HStack(spacing: 12) {
1917
+ if let c = s.usage?.costUsd { Text(String(format: "$%.2f", c)).font(.system(size: 13, weight: .semibold)).monospacedDigit().foregroundColor(pal.text).fixedSize().help("이 세션의 비용, 정가 환산") }
1918
+ if let u = use, u.tree.n > 0 {
1919
+ IconStat(symbol: "gearshape.2", value: u.detached.n > 0 ? "\(u.tree.n), 분리 \(u.detached.n)" : "\(u.tree.n)", tip: u.detached.n > 0 ? "세션 아래 프로세스 \(u.tree.n)개, 세션에서 떼어 띄운 프로세스 \(u.detached.n)개" : "세션 아래 프로세스 수", pal: pal, label: "프로세스")
1920
+ } else if let n = s.procs { IconStat(symbol: "gearshape.2", value: "\(n)", tip: "세션 아래 프로세스 수", pal: pal, label: "프로세스") }
1921
+ Spacer(minLength: 0)
1922
+ Button(action: { jump(to: s) }) {
1923
+ HStack(spacing: 3) { Image(systemName: "arrow.up.forward.app"); Text("세션으로 이동") }.font(.system(size: 11, weight: .medium)).foregroundColor(pal.text2).lineLimit(1).fixedSize().padding(.horizontal, 6).frame(height: 20).contentShape(Rectangle())
1924
+ }.buttonStyle(HoverStyle(radius: 5)).help("이 세션이 열려 있는 터미널로 이동")
1925
+ }
1926
+ }.opacity(phase == .idle ? 0.55 : 1).padding(12).padding(.leading, 5).frame(maxWidth: .infinity, alignment: .topLeading)
1927
+ .background(RoundedRectangle(cornerRadius: 12).fill(pal.tile))
1928
+ .overlay(alignment: .leading) { if phase != .idle { Capsule().fill(edge).frame(width: 4).padding(.vertical, 12).padding(.leading, 5) } }
1929
+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(selected ? tint : Color.clear, lineWidth: 2))
1930
+ .contentShape(Rectangle())
1931
+ }
1932
+ }
1933
+ /** Every session on one screen, in a window of its own: numbers, meters, trend lines and icons. A session's text shows when its tile is clicked. */
1934
+ struct DashboardView: View {
1935
+ @ObservedObject var model: Model
1936
+ var still = false
1937
+ var stillWidth: CGFloat = 1480
1938
+ var lit: Int? = nil // draw this session's tile as if the pointer were on it, for a capture
1939
+ @State private var selected: Int?
1940
+ @State private var hoverPid: Int? // the session whose row in a largest-users list is under the pointer
1941
+ @State private var busyLeft: Set<String> = [] // leftover lines with an open connection: left unticked, something may be using them
1942
+ @State private var cleaning = false // the leftover plate is showing its clean-up choices
1943
+ @State private var picked: Set<String> = []
1944
+ @State private var cleanNote = ""
1945
+ @Environment(\.colorScheme) private var scheme
1946
+ init(model: Model, still: Bool = false, preselect: Int? = nil, width: CGFloat = 1480, lit: Int? = nil, cleaning: Bool = false) { self.model = model; self.still = still; self.stillWidth = width; self.lit = lit; if cleaning { let ids = model.leftoverItems.map { $0.id }.filter { !model.leftoverShared.contains($0) }; let busy = model.leftoverBusy(ids); _cleaning = State(initialValue: true); _busyLeft = State(initialValue: busy); _picked = State(initialValue: Set(ids.filter { !busy.contains($0) })) }; _selected = State(initialValue: preselect) }
1947
+ func key(_ c: Color, _ t: String, _ pal: Pal) -> some View { HStack(spacing: 3) { Circle().fill(c).frame(width: 6, height: 6); Text(t).font(.system(size: 10)).foregroundColor(pal.text2).lineLimit(1) } }
1948
+ func chip(_ symbol: String, _ color: Color, _ text: String, _ pal: Pal) -> some View {
1949
+ HStack(spacing: 4) { Image(systemName: symbol).font(.system(size: 10)).foregroundColor(color).frame(width: 13); Text(text).font(.system(size: 11, weight: .medium)).foregroundColor(pal.text) }.lineLimit(1).fixedSize()
1950
+ }
1951
+ func smallTile<V: View>(_ label: String, _ pal: Pal, @ViewBuilder _ content: () -> V) -> some View {
1952
+ VStack(alignment: .leading, spacing: 5) { Text(label).font(.system(size: 11)).foregroundColor(pal.text2).lineLimit(1); content() }
1953
+ .padding(12).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading).background(RoundedRectangle(cornerRadius: 10).fill(pal.tile))
1954
+ }
1955
+ /** The GPU split the same way as CPU and memory: who is on it, by name, and what is left over. */
1956
+ func gpuCard(_ snap: Snapshot, _ pal: Pal) -> some View {
1957
+ let g = (model.gpu ?? 0) * 100
1958
+ let hasCodex = snap.sessions.contains { $0.agent == "codex" }
1959
+ let cl = min(100, snap.sessions.filter { $0.agent != "codex" }.reduce(0) { $0 + (model.gpuBySession[$1.pid] ?? 0) } * 100)
1960
+ let cx = min(100, snap.sessions.filter { $0.agent == "codex" }.reduce(0) { $0 + (model.gpuBySession[$1.pid] ?? 0) } * 100)
1961
+ let left = min(100, model.gpuUse.filter { $0.left }.reduce(0) { $0 + $1.share } * 100)
1962
+ var parts = [Part(id: "Claude 세션", value: cl, color: pal.claude)]
1963
+ if hasCodex { parts.append(Part(id: "Codex 세션", value: cx, color: pal.codex)) }
1964
+ parts.append(Part(id: "끝난 세션이 남긴 것", value: left, color: pal.left))
1965
+ parts.append(Part(id: "그 밖", value: max(0, g - cl - cx - left), color: pal.neutral))
1966
+ let top: [Top] = model.gpuLines(snap.sessions, max: 5).map { l in
1967
+ let s = l.pid.flatMap { p in snap.sessions.first { $0.pid == p } }
1968
+ return Top(id: l.id, name: l.label, value: l.share * 100,
1969
+ color: l.agent == nil ? pal.neutral : l.agent == "left" ? pal.left : pal.agent(l.agent ?? "claude"),
1970
+ pid: s?.pid, program: s == nil || l.note.isEmpty ? nil : l.note, doing: s.flatMap { doingNow($0) },
1971
+ origin: s != nil ? nil : l.agent == "left" ? "끝난 세션이 남긴 것" : "세션과 무관한 프로그램", originSymbol: l.agent == "left" ? "moon.zzz.fill" : "macwindow")
1972
+ }
1973
+ return machineTile(title: "GPU", total: pct1(g), sub: "기기 전체", parts: parts, scale: 100, fmt: { pct1($0) }, top: top, series: [],
1974
+ tip: "전체 값은 GPU 장치의 사용률이고 이름별 값은 각 프로그램이 GPU를 쓴 시간의 비율입니다. 재는 방식이 달라 합이 조금 어긋날 수 있습니다", pal: pal)
1975
+ }
1976
+ func kpis(_ snap: Snapshot, _ pal: Pal, width: CGFloat) -> some View {
1977
+ let sm = model.samples, span = spanText(sm.first?.at, sm.last?.at)
1978
+ let costs = sm.map { $0.cost }, costUp = (costs.last ?? 0) - (costs.first ?? 0)
1979
+ let mainOnes = snap.sessions.filter { model.parentSession[$0.pid] == nil }
1980
+ let phases = mainOnes.map { model.phase($0) }
1981
+ let nUser = phases.filter { $0 == .needsUser }.count, nIdle = phases.filter { $0 == .idle }.count, nSubs = snap.sessions.count - mainOnes.count
1982
+ let wins = snap.usage?.claude?.windows ?? []
1983
+ let working = smallTile("작업 중인 세션", pal) {
1984
+ HStack(alignment: .firstTextBaseline, spacing: 5) {
1985
+ Text("\(phases.filter { $0 == .active }.count)").font(.system(size: 40, weight: .semibold)).foregroundColor(pal.text)
1986
+ Text("/ \(mainOnes.count)").font(.system(size: 16, weight: .medium)).foregroundColor(pal.text2)
1987
+ }
1988
+ VStack(alignment: .leading, spacing: 2) {
1989
+ if nUser > 0 { chip("hand.raised.fill", pal.warning, "확인 대기 \(nUser)", pal) }
1990
+ if nIdle > 0 { chip("pause.circle", pal.text2, "입력 대기 \(nIdle)", pal) }
1991
+ if nSubs > 0 { chip("arrow.turn.down.right", pal.text2, "띄운 세션 \(nSubs)", pal) }
1992
+ }
1993
+ }
1994
+ let cost = smallTile("세션 비용, 정가 환산", pal) {
1995
+ Text(snap.totals.costUsd.map { String(format: "$%.2f", $0) } ?? "-").font(.system(size: 22, weight: .semibold)).monospacedDigit().foregroundColor(pal.text).lineLimit(1).fixedSize()
1996
+ Text("실행 중인 세션 \(snap.sessions.count)개 합계").font(.system(size: 10.5)).foregroundColor(pal.text2).lineLimit(1)
1997
+ if costUp > 0.005 { Text(String(format: "%@ 동안 +$%.2f", span, costUp)).font(.system(size: 10.5)).monospacedDigit().foregroundColor(pal.text2).lineLimit(1) }
1998
+ }.help("구독 청구액이 아니라 쓴 토큰을 정가로 환산한 값입니다")
1999
+ let limits = smallTile("Claude 한도", pal) {
2000
+ if wins.isEmpty { Text("받은 값이 없습니다").font(.system(size: 11)).foregroundColor(pal.text2) }
2001
+ ForEach(wins, id: \.key) { w in
2002
+ let sv = severity(w.usedPct, pal.claude, pal)
2003
+ VStack(alignment: .leading, spacing: 3) {
2004
+ HStack(spacing: 5) {
2005
+ Text(windowName(w)).font(.system(size: 11.5, weight: .medium)).foregroundColor(pal.text)
2006
+ if let sym = sv.symbol { Image(systemName: sym).font(.system(size: 10)).foregroundColor(sv.color) }
2007
+ Spacer(minLength: 4)
2008
+ Text("\(Int(w.usedPct.rounded()))%").font(.system(size: 15, weight: .semibold)).monospacedDigit().foregroundColor(pal.text).fixedSize()
2009
+ }
2010
+ Meter(value: w.usedPct / 100, fill: sv.color)
2011
+ Text(resetText(w.resetsAt, now: snap.at)).font(.system(size: 10.5)).foregroundColor(pal.text2).lineLimit(1).minimumScaleFactor(0.85)
2012
+ }
2013
+ }
2014
+ }
2015
+ let rank = smallTile("이달의 랭킹", pal) {
2016
+ if let st = snap.standing {
2017
+ HStack(spacing: 8) {
2018
+ Text(st.emoji).font(.system(size: 28)).fixedSize()
2019
+ VStack(alignment: .leading, spacing: 0) {
2020
+ HStack(spacing: 4) { Text(st.name).font(.system(size: 14, weight: .semibold)).foregroundColor(pal.text).lineLimit(1); if st.crown == true { Image(systemName: "crown.fill").font(.system(size: 9.5)).foregroundColor(pal.warning) } }
2021
+ Text(st.rank != nil && st.ranked != nil ? "\(Int(st.ranked!))명 중 \(Int(st.rank!))위" : "집계 전").font(.system(size: 11.5)).foregroundColor(pal.text2).lineLimit(1)
2022
+ }
2023
+ }
2024
+ if let p = st.scorePct {
2025
+ Meter(value: p / 100, fill: pal.neutral, tick: st.next?.floorPct.map { $0 / 100 }, tickColor: pal.text)
2026
+ Text("점수 백분위 \(Int(p))%" + (st.next.map { ", 다음 \($0.emoji) \($0.floorPct.map { "\(Int($0))%" } ?? "")" } ?? "")).font(.system(size: 10.5)).foregroundColor(pal.text2).lineLimit(1)
2027
+ }
2028
+ } else { Text("팀에 참여하면 나옵니다").font(.system(size: 11)).foregroundColor(pal.text2) }
2029
+ }
2030
+ return Group {
2031
+ if width >= 980 {
2032
+ HStack(alignment: .top, spacing: 10) {
2033
+ if model.gpu != nil { gpuCard(snap, pal) }
2034
+ working.frame(width: 132); cost.frame(width: 156); limits.frame(width: 170); rank.frame(width: 170)
2035
+ }.fixedSize(horizontal: false, vertical: true)
2036
+ } else {
2037
+ VStack(spacing: 10) {
2038
+ if model.gpu != nil { gpuCard(snap, pal) }
2039
+ HStack(alignment: .top, spacing: 10) { working; cost }.fixedSize(horizontal: false, vertical: true)
2040
+ HStack(alignment: .top, spacing: 10) { limits; rank }.fixedSize(horizontal: false, vertical: true)
2041
+ }
2042
+ }
2043
+ }
2044
+ }
2045
+ /** Trends at a size and with the labels that let them be read: the machine against the sessions, for CPU, memory and GPU. */
2046
+ func trends(_ pal: Pal) -> some View {
2047
+ let sm = model.samples, span = spanText(sm.first?.at, sm.last?.at)
2048
+ let whole: (Double) -> String = { "\(Int($0.rounded()))%" }
2049
+ return VStack(alignment: .leading, spacing: 12) {
2050
+ Text("추이").font(.system(size: 13, weight: .semibold)).foregroundColor(pal.text)
2051
+ TrendChart(title: "CPU", lines: [.init(id: "기기 전체", values: sm.map { $0.sysCpu * 100 }, color: pal.neutral, fill: true), .init(id: "세션", values: sm.map { ($0.claudeCpu + $0.codexCpu) * 100 }, color: pal.claude)], top: 100, fmt: whole, span: span, pal: pal)
2052
+ TrendChart(title: "메모리", lines: [.init(id: "기기 전체", values: sm.map { $0.sysMem * RAM_MB }, color: pal.neutral, fill: true), .init(id: "세션", values: sm.map { ($0.claudeMem + $0.codexMem) * RAM_MB }, color: pal.claude)], top: RAM_MB, fmt: { memText($0) }, span: span, pal: pal)
2053
+ if model.gpu != nil {
2054
+ TrendChart(title: "GPU", lines: [.init(id: "기기 전체", values: sm.map { $0.gpu * 100 }, color: pal.neutral, fill: true), .init(id: "세션", values: sm.map { ($0.claudeGpu + $0.codexGpu) * 100 }, color: pal.claude)], top: 100, fmt: whole, span: span, pal: pal)
2055
+ }
2056
+ }
2057
+ }
2058
+ /** One session's own trends, each on a scale that fits it and says so. */
2059
+ func sessionTrends(_ s: Session, _ pal: Pal) -> some View {
2060
+ let h = model.hist[s.pid] ?? [], span = spanText(h.first?.at, h.last?.at), tint = pal.agent(s.agent)
2061
+ let cpuTop = max(5, ((h.map { $0.cpu }.max() ?? 0) / 5).rounded(.up) * 5), memTop = max(1024, ((h.map { $0.mem }.max() ?? 0) / 1024).rounded(.up) * 1024)
2062
+ let gpuTop = max(10, ((h.map { $0.gpu * 100 }.max() ?? 0) / 10).rounded(.up) * 10)
2063
+ return VStack(alignment: .leading, spacing: 12) {
2064
+ TrendChart(title: "CPU", lines: [.init(id: "이 세션", values: h.map { $0.cpu }, color: tint, fill: true)], top: cpuTop, fmt: { pct1($0) }, span: span, pal: pal)
2065
+ TrendChart(title: "메모리", lines: [.init(id: "이 세션", values: h.map { $0.mem }, color: tint, fill: true)], top: memTop, fmt: { memText($0) }, span: span, pal: pal)
2066
+ TrendChart(title: "GPU", lines: [.init(id: "이 세션", values: h.map { $0.gpu * 100 }, color: tint, fill: true)], top: gpuTop, fmt: { pct1($0) }, span: span, pal: pal)
2067
+ }
2068
+ }
2069
+ func inspector(_ s: Session, _ snap: Snapshot, _ pal: Pal) -> some View {
2070
+ let body = VStack(alignment: .leading, spacing: 6) {
2071
+ HStack(spacing: 7) {
2072
+ Text(s.name ?? s.agent).font(.system(size: 15, weight: .semibold)).lineLimit(1).truncationMode(.middle)
2073
+ Spacer(minLength: 6)
2074
+ Button(action: { jump(to: s) }) { HStack(spacing: 4) { Image(systemName: "arrow.up.forward.app"); Text("세션으로 이동") }.font(.system(size: 11.5, weight: .medium)).padding(.horizontal, 8).padding(.vertical, 4).background(RoundedRectangle(cornerRadius: 6).fill(pal.well)).contentShape(Rectangle()) }
2075
+ .buttonStyle(HoverStyle(radius: 6)).help("이 세션이 열려 있는 터미널 앱을 앞으로 가져옵니다")
2076
+ Button(action: { selected = nil }) { Image(systemName: "xmark.circle.fill").font(.system(size: 15)).foregroundColor(pal.text2).contentShape(Rectangle()) }.buttonStyle(HoverStyle(radius: 10, grow: 4)).help("닫기")
2077
+ }
2078
+ if let c = s.cwd { Text(c).font(.system(size: 10.5, design: .monospaced)).foregroundColor(pal.text2).lineLimit(1).truncationMode(.head) }
2079
+ Text(activity(s, now: snap.at)).font(.system(size: 12)).fixedSize(horizontal: false, vertical: true)
2080
+ Divider().padding(.vertical, 2)
2081
+ if let c = s.context { Fact(label: "컨텍스트", value: contextLine(c)) }
2082
+ if let u = s.usage {
2083
+ Fact(label: "토큰", value: tokenLine(u))
2084
+ Fact(label: "비용", value: [u.costUsd.map { String(format: "$%.2f (정가 환산)", $0) } ?? "가격표 없음", u.requests.map { "요청 \(Int($0))회" } ?? ""].filter { !$0.isEmpty }.joined(separator: ", "))
2085
+ }
2086
+ if let u = model.usage[s.pid], u.detached.n > 0 {
2087
+ Fact(label: "분리 실행", value: u.names.sorted { $0.value.mem > $1.value.mem }.prefix(4).map { "\($0.key) \(memText($0.value.mem))" }.joined(separator: ", "))
2088
+ }
2089
+ let onGpu = model.gpuUse.filter { $0.session == s.pid }
2090
+ if !onGpu.isEmpty { Fact(label: "GPU", value: "\(pct1(min(1, onGpu.reduce(0) { $0 + $1.share }) * 100)) (\(onGpu.prefix(3).map { "\($0.name) \(pct1($0.share * 100))" }.joined(separator: ", ")))") }
2091
+ Divider().padding(.vertical, 2)
2092
+ WorkSummary(d: s.detail, now: snap.at, textLines: 12, calls: 12, procs: 5, off: model.detailOff)
2093
+ Divider().padding(.vertical, 2)
2094
+ sessionTrends(s, pal)
2095
+ }.padding(14).frame(width: 372, alignment: .topLeading).foregroundColor(pal.text)
2096
+ return Group { if still { body } else { ScrollView { body } } }.frame(width: 372).frame(maxHeight: still ? nil : .infinity, alignment: .top).background(pal.tile)
2097
+ }
2098
+ struct Part: Identifiable { let id: String; let value: Double; let color: Color }
2099
+ struct Top: Identifiable {
2100
+ let id: String; let name: String; let value: Double; let color: Color
2101
+ var pid: Int? = nil // a live session: the row picks it
2102
+ var program: String? = nil // what in that session is using it, with its own share
2103
+ var doing: String? = nil // what that session is doing now
2104
+ var origin: String? = nil // outside any live session: where it comes from
2105
+ var originSymbol = "moon.zzz.fill"
2106
+ }
2107
+ /** What a session is doing now, in one line: the tool call in flight, else the request it is on, else that it is waiting. */
2108
+ func doingNow(_ s: Session) -> String? {
2109
+ if s.state == "waiting" { return "확인을 기다리는 중" }
2110
+ let ask = s.detail?.prompt?.text.split(whereSeparator: \.isNewline).first.map { String($0).trimmingCharacters(in: .whitespaces) }
2111
+ if model.phase(s) == .idle { return ask.map { "입력 대기 중, 마지막 요청: \($0)" } ?? "입력 대기 중" }
2112
+ if let p = s.detail?.recent?.last(where: { $0.pending == true }) { return p.target.map { "\(p.tool): \($0)" } ?? p.tool }
2113
+ if let a = ask { return "요청: \(a)" }
2114
+ return s.tools.first
2115
+ }
2116
+ /** The one program behind most of a session's figure, with its own share: the answer to "what in that session is using it". */
2117
+ func heaviest(_ s: Session, total: Double, _ part: (Work) -> Double, _ fmt: (Double) -> String) -> String? {
2118
+ guard let u = model.usage[s.pid] else { return nil }
2119
+ let named = u.work.filter { !$0.key.isEmpty }.map { (name: $0.key, v: part($0.value)) }
2120
+ let own = max(0, total - named.reduce(0) { $0 + $1.v })
2121
+ let all = named + [(name: s.agent == "codex" ? "Codex 자체" : "Claude Code 자체", v: own)]
2122
+ guard let top = all.max(by: { $0.v < $1.v }), top.v > 0 else { return nil }
2123
+ return "\(top.name) \(fmt(top.v))"
2124
+ }
2125
+ func leftOrigin(_ id: String) -> String { model.leftoverWhere[id].map { "끝난 세션이 남긴 것, 폴더 \($0)" } ?? "끝난 세션이 남긴 것" }
2126
+ /** A line under a largest-user row: an icon and the reason, small and in secondary ink. */
2127
+ func why(_ symbol: String, _ text: String, _ pal: Pal) -> some View {
2128
+ HStack(alignment: .firstTextBaseline, spacing: 4) {
2129
+ Image(systemName: symbol).font(.system(size: 8.5)).foregroundColor(pal.text2).frame(width: 12)
2130
+ Text(text).font(.system(size: 10.5)).foregroundColor(pal.text2).lineLimit(2).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true)
2131
+ }.padding(.leading, 12)
2132
+ }
2133
+ /** One machine resource: the total, a thin bar split by who is using it with its legend, a trend, and the largest users by name. */
2134
+ func machineTile(title: String, total: String, sub: String, parts: [Part], scale: Double, fmt: @escaping (Double) -> String, top: [Top], series: [(v: [Double], c: Color)], tip: String, pal: Pal) -> some View {
2135
+ let full = max(scale, parts.reduce(0) { $0 + $1.value }, 0.000001)
2136
+ let topMax = max(top.map { $0.value }.max() ?? 0, 0.000001)
2137
+ // The figure, bar and legend take a fixed narrow column, so every remaining point of width goes to the names of the largest users.
2138
+ return HStack(alignment: .top, spacing: 14) {
2139
+ VStack(alignment: .leading, spacing: 6) {
2140
+ Text(title).font(.system(size: 11)).foregroundColor(pal.text2)
2141
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
2142
+ Text(total).font(.system(size: 26, weight: .semibold)).foregroundColor(pal.text).lineLimit(1).fixedSize()
2143
+ Text(sub).font(.system(size: 11)).foregroundColor(pal.text2).lineLimit(1)
2144
+ }
2145
+ GeometryReader { g in
2146
+ HStack(spacing: 2) {
2147
+ ForEach(parts) { p in if p.value > 0 { Rectangle().fill(p.color).frame(width: max(3, (g.size.width - 2 * CGFloat(parts.count)) * CGFloat(p.value / full))) } }
2148
+ Rectangle().fill(pal.well).frame(maxWidth: .infinity)
2149
+ }.clipShape(Capsule())
2150
+ }.frame(height: 8)
2151
+ VStack(alignment: .leading, spacing: 3) {
2152
+ ForEach(parts) { p in
2153
+ HStack(spacing: 5) {
2154
+ Circle().fill(p.color).frame(width: 6, height: 6)
2155
+ Text(p.id).font(.system(size: 10.5)).foregroundColor(pal.text2).lineLimit(1)
2156
+ Spacer(minLength: 4)
2157
+ Text(fmt(p.value)).font(.system(size: 10.5, weight: .medium)).monospacedDigit().foregroundColor(pal.text).fixedSize()
2158
+ }
2159
+ }
2160
+ }
2161
+ }.frame(width: 196, alignment: .topLeading)
2162
+ VStack(alignment: .leading, spacing: 3) {
2163
+ Text("많이 쓰는 곳").font(.system(size: 10)).foregroundColor(pal.text2).padding(.leading, 6)
2164
+ if top.isEmpty { Text("지금 쓰는 곳이 없습니다").font(.system(size: 11)).foregroundColor(pal.text2).padding(.leading, 6) }
2165
+ ForEach(top) { t in
2166
+ // The bar is the row's own background, so it costs the name no width. Under the name come what in that
2167
+ // session is using it and what the session is doing: a figure next to a bare name answers nothing.
2168
+ let row = VStack(alignment: .leading, spacing: 2) {
2169
+ HStack(spacing: 6) {
2170
+ Circle().fill(t.color).frame(width: 6, height: 6)
2171
+ Text(t.name).font(.system(size: 11.5, weight: t.pid == nil ? .regular : .medium)).foregroundColor(pal.text).lineLimit(3).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true)
2172
+ Spacer(minLength: 4)
2173
+ Text(fmt(t.value)).font(.system(size: 11.5, weight: .medium)).monospacedDigit().foregroundColor(pal.text).fixedSize()
2174
+ }
2175
+ if let p = t.program { why("gearshape.2.fill", p, pal) }
2176
+ if let d = t.doing { why("text.bubble.fill", d, pal) }
2177
+ if let o = t.origin { why(t.originSymbol, o, pal) }
2178
+ }.padding(.horizontal, 6).padding(.vertical, 3)
2179
+ .background(alignment: .topLeading) { GeometryReader { g in RoundedRectangle(cornerRadius: 4).fill(t.color.opacity(0.22)).frame(width: max(4, g.size.width * CGFloat(t.value / topMax)), height: 20) } }
2180
+ if let pid = t.pid {
2181
+ Pressable(radius: 5, lit: selected == pid, action: { selected = selected == pid ? nil : pid }) { row }
2182
+ .onHover { inside in hoverPid = inside ? pid : (hoverPid == pid ? nil : hoverPid) }
2183
+ .help(([t.name, t.program, t.doing].compactMap { $0 } + ["눌러서 이 세션의 상세를 봅니다"]).joined(separator: "\n"))
2184
+ } else { row.help([t.name, t.origin].compactMap { $0 }.joined(separator: "\n")) }
2185
+ }
2186
+ }.frame(maxWidth: .infinity, alignment: .topLeading)
2187
+ }.padding(12).frame(maxWidth: .infinity, minHeight: 104, alignment: .topLeading).background(RoundedRectangle(cornerRadius: 10).fill(pal.tile)).help(tip)
2188
+ }
2189
+ func machine(_ snap: Snapshot, _ pal: Pal, width: CGFloat) -> some View {
2190
+ let sm = model.samples, ses = snap.sessions
2191
+ let cl = ses.filter { $0.agent != "codex" }, cx = ses.filter { $0.agent == "codex" }
2192
+ let cpuCl = cl.reduce(0) { $0 + model.cpuOf($1) }, cpuCx = cx.reduce(0) { $0 + model.cpuOf($1) }, cpuLeft = model.leftover.cpu * 100
2193
+ let cpuAll = max((model.sysCpu ?? 0) * 100, cpuCl + cpuCx + cpuLeft)
2194
+ let memCl = cl.reduce(0) { $0 + model.memOf($1) }, memCx = cx.reduce(0) { $0 + model.memOf($1) }, memLeft = model.leftover.mem
2195
+ let memAll = model.sysMemMb ?? 0
2196
+ var cpuParts = [Part(id: "Claude 세션", value: cpuCl, color: pal.claude)], memParts = [Part(id: "Claude 세션", value: memCl, color: pal.claude)]
2197
+ if !cx.isEmpty { cpuParts.append(Part(id: "Codex 세션", value: cpuCx, color: pal.codex)); memParts.append(Part(id: "Codex 세션", value: memCx, color: pal.codex)) }
2198
+ cpuParts.append(Part(id: "끝난 세션이 남긴 것", value: cpuLeft, color: pal.left)); memParts.append(Part(id: "끝난 세션이 남긴 것", value: memLeft, color: pal.left))
2199
+ cpuParts.append(Part(id: "그 밖", value: max(0, cpuAll - cpuCl - cpuCx - cpuLeft), color: pal.neutral)); memParts.append(Part(id: "다른 프로그램", value: model.others.reduce(0) { $0 + $1.mem }, color: pal.neutral))
2200
+ func tops(_ pick: (AppLoad) -> Double, _ of: (Session) -> Double, _ part: (Work) -> Double, _ show: (Double) -> String) -> [Top] {
2201
+ var t = ses.map { s in Top(id: "s\(s.pid)", name: s.name ?? s.agent, value: of(s), color: pal.agent(s.agent), pid: s.pid, program: heaviest(s, total: of(s), part, show), doing: doingNow(s)) }
2202
+ t += model.leftoverItems.map { Top(id: "l\($0.id)", name: $0.name, value: pick($0), color: pal.left, origin: leftOrigin($0.id)) }
2203
+ t += model.others.map { Top(id: "o\($0.id)", name: $0.name, value: pick($0), color: pal.neutral, origin: "세션과 무관한 프로그램", originSymbol: "macwindow") }
2204
+ return Array(t.sorted { $0.value > $1.value }.prefix(5))
2205
+ }
2206
+ let a = machineTile(title: "CPU", total: pct1(cpuAll), sub: "기기 전체", parts: cpuParts, scale: 100, fmt: { pct1($0) }, top: tops({ $0.cpu * 100 }, { model.cpuOf($0) }, { $0.cpu * 100 }, { pct1($0) }),
2207
+ series: [(sm.map { $0.sysCpu * 100 }, pal.neutral), (sm.map { ($0.claudeCpu + $0.codexCpu) * 100 }, pal.claude)],
2208
+ tip: "세션 값에는 세션이 따로 떼어 띄운 프로세스도 들어갑니다. 회색 선은 기기 전체, 색 선은 실행 중인 세션입니다", pal: pal)
2209
+ let b = machineTile(title: "메모리", total: memText(memAll), sub: "/ \(Int((RAM_MB / 1024).rounded())) GB 사용", parts: memParts, scale: RAM_MB, fmt: { memText($0) }, top: tops({ $0.mem }, { model.memOf($0) }, { $0.mem }, { memText($0) }),
2210
+ series: [(sm.map { $0.sysMem * 100 }, pal.neutral), (sm.map { ($0.claudeMem + $0.codexMem) * 100 }, pal.claude)],
2211
+ tip: "프로그램별 값은 압축된 메모리와 GPU 메모리까지 센 점유량입니다. 그래서 합이 실제 사용량보다 클 수 있습니다", pal: pal)
2212
+ return Group { if width >= 900 { HStack(alignment: .top, spacing: 10) { a; b } } else { VStack(spacing: 10) { a; b } } }
2213
+ }
2214
+ /**
2215
+ * What ended sessions left running, by program: nothing here belongs to a session that is still open. "정리" turns
2216
+ * the lines into a checklist: everything is ticked except apps, virtual machines and databases, which cannot be
2217
+ * ticked at all, and nothing is stopped until the second button is pressed.
2218
+ */
2219
+ func leftoverPlate(_ pal: Pal) -> some View {
2220
+ let items = Array(model.leftoverItems.prefix(12))
2221
+ let can = items.filter { !model.leftoverShared.contains($0.id) }
2222
+ let chosen = can.filter { picked.contains($0.id) }
2223
+ return VStack(alignment: .leading, spacing: 6) {
2224
+ HStack(spacing: 12) {
2225
+ HStack(spacing: 5) {
2226
+ Image(systemName: "moon.zzz.fill").font(.system(size: 11)).foregroundColor(pal.left)
2227
+ Text("끝난 세션이 남긴 프로세스").font(.system(size: 12.5, weight: .semibold)).foregroundColor(pal.text)
2228
+ Text("\(model.leftover.n)").font(.system(size: 10.5, weight: .bold)).foregroundColor(pal.text).padding(.horizontal, 6).padding(.vertical, 1).background(Capsule().fill(pal.well))
2229
+ }.help("Claude 세션이 띄웠고 그 세션이 끝난 뒤에도 돌고 있는 프로세스입니다")
2230
+ if !cleanNote.isEmpty { Text(cleanNote).font(.system(size: 11)).foregroundColor(pal.text2).lineLimit(1) }
2231
+ Spacer(minLength: 4)
2232
+ IconStat(symbol: "cpu", value: pct1(model.leftover.cpu * 100), tip: "CPU 합계", pal: pal)
2233
+ IconStat(symbol: "memorychip", value: memText(model.leftover.mem), tip: "메모리 합계", pal: pal)
2234
+ if !cleaning && !can.isEmpty {
2235
+ Button(action: { busyLeft = model.leftoverBusy(can.map { $0.id }); picked = Set(can.map { $0.id }.filter { !busyLeft.contains($0) }); cleanNote = ""; cleaning = true }) {
2236
+ HStack(spacing: 3) { Image(systemName: "trash"); Text("정리") }.font(.system(size: 11, weight: .medium)).foregroundColor(pal.text).lineLimit(1).fixedSize()
2237
+ .padding(.horizontal, 8).frame(height: 20).background(RoundedRectangle(cornerRadius: 5).fill(pal.well)).contentShape(Rectangle())
2238
+ }.buttonStyle(HoverStyle(radius: 5)).help("남은 프로세스를 골라서 끕니다. 고르는 화면이 먼저 나오고 앱과 가상 머신과 데이터베이스는 빠집니다")
2239
+ }
2240
+ }.padding(.horizontal, 4).frame(height: 22)
2241
+ LazyVGrid(columns: [GridItem(.adaptive(minimum: 330), spacing: 8, alignment: .top)], alignment: .leading, spacing: 8) {
2242
+ ForEach(items) { it in
2243
+ let fixed = model.leftoverShared.contains(it.id), on = picked.contains(it.id)
2244
+ let row = HStack(spacing: 8) {
2245
+ if cleaning {
2246
+ Image(systemName: fixed ? "lock.fill" : on ? "checkmark.square.fill" : "square").font(.system(size: 12)).foregroundColor(fixed ? pal.text2 : on ? pal.left : pal.text2).frame(width: 14)
2247
+ } else { Circle().fill(pal.left).frame(width: 6, height: 6) }
2248
+ VStack(alignment: .leading, spacing: 1) {
2249
+ Text(it.name).font(.system(size: 12, weight: .medium)).foregroundColor(pal.text).lineLimit(1).truncationMode(.middle)
2250
+ if let w = model.leftoverWhere[it.id] { Text("폴더 \(w)").font(.system(size: 10.5)).foregroundColor(pal.text2).lineLimit(1).truncationMode(.middle) }
2251
+ }
2252
+ if it.n > 1 { Text("\(it.n)개").font(.system(size: 11)).foregroundColor(pal.text2).fixedSize() }
2253
+ if cleaning && busyLeft.contains(it.id) { Text("연결 중").font(.system(size: 10, weight: .medium)).foregroundColor(pal.text).padding(.horizontal, 5).padding(.vertical, 1).background(Capsule().fill(pal.well)).fixedSize() }
2254
+ Spacer(minLength: 4)
2255
+ IconStat(symbol: "cpu", value: pct1(it.cpu * 100), tip: "CPU, 기기 전체 대비", pal: pal)
2256
+ IconStat(symbol: "memorychip", value: memText(it.mem), tip: "메모리", pal: pal)
2257
+ }.padding(.horizontal, 10).padding(.vertical, 7).background(RoundedRectangle(cornerRadius: 8).fill(pal.tile)).opacity(cleaning && fixed ? 0.6 : 1)
2258
+ if cleaning && !fixed {
2259
+ Pressable(radius: 8, action: { if on { picked.remove(it.id) } else { picked.insert(it.id) } }) { row }.help(it.name)
2260
+ } else {
2261
+ row.help(cleaning && fixed ? "앱, 가상 머신, 데이터베이스는 다른 작업이 쓰고 있을 수 있어 여기서 끄지 않습니다. 그 프로그램에서 직접 끄십시오" : it.name)
2262
+ }
2263
+ }
2264
+ }
2265
+ if cleaning {
2266
+ HStack(alignment: .center, spacing: 10) {
2267
+ Text("고른 \(chosen.count)개를 끄면 CPU \(pct1(chosen.reduce(0) { $0 + $1.cpu } * 100))와 메모리 \(memText(chosen.reduce(0) { $0 + $1.mem }))가 돌아옵니다. 자물쇠가 붙은 것은 앱이나 가상 머신이나 데이터베이스라 뺐습니다. 연결 중이라고 적힌 것은 무언가 쓰고 있을 수 있어 선택하지 않았습니다.")
2268
+ .font(.system(size: 11)).foregroundColor(pal.text2).fixedSize(horizontal: false, vertical: true)
2269
+ Spacer(minLength: 8)
2270
+ Pill("취소") { cleaning = false }
2271
+ Pill("고른 \(chosen.count)개 종료", .danger, disabled: chosen.isEmpty) {
2272
+ let n = model.stopLeftovers(chosen.map { $0.id })
2273
+ cleanNote = "프로세스 \(n)개에 종료를 요청했습니다"; cleaning = false
2274
+ }
2275
+ }.padding(.horizontal, 4).padding(.top, 2)
2276
+ }
2277
+ }.padding(8).background(RoundedRectangle(cornerRadius: 16).fill(pal.group))
2278
+ }
2279
+ func groupHead(_ g: SessionGroup, _ pal: Pal) -> some View {
2280
+ let many = g.sessions.count > 1
2281
+ let cost = g.sessions.compactMap { $0.usage?.costUsd }.reduce(0, +)
2282
+ let cpu = g.sessions.reduce(0) { $0 + model.cpuOf($1) }, mem = g.sessions.reduce(0) { $0 + model.memOf($1) }
2283
+ let gpu = g.sessions.reduce(0) { $0 + (model.gpuBySession[$1.pid] ?? 0) }
2284
+ return HStack(spacing: 12) {
2285
+ HStack(spacing: 5) {
2286
+ Image(systemName: many ? "folder.fill" : "folder").font(.system(size: 11)).foregroundColor(pal.text2)
2287
+ Text(g.name).font(.system(size: 12.5, weight: .semibold)).foregroundColor(pal.text).lineLimit(1).truncationMode(.middle)
2288
+ if many { Text("\(g.sessions.count)").font(.system(size: 10.5, weight: .bold)).foregroundColor(pal.text).padding(.horizontal, 6).padding(.vertical, 1).background(Capsule().fill(pal.well)).help("이 프로젝트에서 실행 중인 세션 수") }
2289
+ }
2290
+ Spacer(minLength: 4)
2291
+ if many {
2292
+ IconStat(symbol: "dollarsign.circle", value: String(format: "%.2f", cost), tip: "이 프로젝트 세션의 비용 합계, 정가 환산", pal: pal)
2293
+ IconStat(symbol: "cpu", value: pct1(cpu), tip: "이 프로젝트 세션의 CPU 합계", pal: pal)
2294
+ IconStat(symbol: "memorychip", value: memText(mem), tip: "이 프로젝트 세션의 메모리 합계", pal: pal)
2295
+ if gpu >= 0.001 { IconStat(symbol: "display", value: pct1(gpu * 100), tip: "이 프로젝트 세션의 GPU 합계", pal: pal) }
2296
+ }
2297
+ }.padding(.horizontal, 4).frame(height: 20)
2298
+ }
2299
+ /**
2300
+ * Project groups laid out on a grid of equal cells: a group takes one cell per session, up to a whole row, and starts
2301
+ * a new row when the cells left on this one are too few. Sessions of one project never end up apart.
2302
+ */
2303
+ func groupsView(_ snap: Snapshot, _ pal: Pal, width: CGFloat) -> some View {
2304
+ let gap: CGFloat = 12, minCell: CGFloat = 318
2305
+ let cols = max(1, Int((width + gap) / (minCell + gap)))
2306
+ let cell = (width - CGFloat(cols - 1) * gap) / CGFloat(cols)
2307
+ let names = Dictionary(snap.sessions.map { ($0.pid, $0.name ?? $0.agent) }, uniquingKeysWith: { a, _ in a })
2308
+ // A group is as wide as its main sessions need, and at least wide enough to lay its started sessions side by side.
2309
+ let isSub: (Session, SessionGroup) -> Bool = { s, g in model.parentSession[s.pid].map { up in g.sessions.contains { $0.pid == up } } ?? false }
2310
+ let spanOf: (SessionGroup) -> Int = { g in
2311
+ let subs = g.sessions.filter { isSub($0, g) }.count
2312
+ return min(cols, max(1, g.sessions.count - subs, min(subs, cols)))
2313
+ }
2314
+ var rows: [[SessionGroup]] = [[]], used = 0
2315
+ for g in groupSessions(model.ordered(snap.sessions), parents: model.parentSession) {
2316
+ let span = spanOf(g)
2317
+ if used + span > cols { rows.append([]); used = 0 }
2318
+ rows[rows.count - 1].append(g); used += span
2319
+ }
2320
+ return VStack(alignment: .leading, spacing: gap) {
2321
+ ForEach(Array(rows.enumerated()), id: \.offset) { _, row in
2322
+ HStack(alignment: .top, spacing: gap) {
2323
+ ForEach(row) { g in
2324
+ let span = spanOf(g)
2325
+ let mains = g.sessions.filter { !isSub($0, g) }, subs = g.sessions.filter { isSub($0, g) }
2326
+ let grid = Array(repeating: GridItem(.flexible(), spacing: 8, alignment: .top), count: span)
2327
+ VStack(alignment: .leading, spacing: 6) {
2328
+ groupHead(g, pal)
2329
+ LazyVGrid(columns: grid, alignment: .leading, spacing: 8) {
2330
+ ForEach(mains) { s in
2331
+ Pressable(radius: 12, lit: lit == s.pid || hoverPid == s.pid, action: { selected = selected == s.pid ? nil : s.pid }) {
2332
+ SessionTile(s: s, cpu: model.cpuOf(s), mem: model.memOf(s), gpu: model.gpuBySession[s.pid] ?? 0, hist: model.hist[s.pid] ?? [], now: snap.at, selected: selected == s.pid, pal: pal,
2333
+ parentName: nil, use: model.usage[s.pid], phase: model.phase(s), work: model.working(s),
2334
+ subs: subs.filter { model.parentSession[$0.pid] == s.pid }.count, subsActive: subs.filter { model.parentSession[$0.pid] == s.pid && model.phase($0) == .active }.count)
2335
+ }
2336
+ }
2337
+ }
2338
+ if !subs.isEmpty {
2339
+ HStack(spacing: 5) {
2340
+ Image(systemName: "arrow.turn.down.right").font(.system(size: 10, weight: .semibold))
2341
+ Text("이 프로젝트의 세션이 띄운 세션 \(subs.count)개").font(.system(size: 11))
2342
+ }.foregroundColor(pal.text2).padding(.horizontal, 4).padding(.top, 2)
2343
+ LazyVGrid(columns: grid, alignment: .leading, spacing: 6) {
2344
+ ForEach(subs) { s in
2345
+ Pressable(radius: 9, lit: lit == s.pid, action: { selected = selected == s.pid ? nil : s.pid }) {
2346
+ SubTile(s: s, now: snap.at, selected: selected == s.pid, pal: pal, phase: model.phase(s))
2347
+ }.help(model.parentSession[s.pid].flatMap { names[$0] }.map { "\($0) 세션이 띄운 세션" } ?? "")
2348
+ }
2349
+ }
2350
+ }
2351
+ }.padding(8).frame(width: CGFloat(span) * cell + CGFloat(span - 1) * gap, alignment: .topLeading)
2352
+ .background(RoundedRectangle(cornerRadius: 16).fill(pal.group))
2353
+ }
2354
+ }
2355
+ }
2356
+ if model.leftover.n > 0 { leftoverPlate(pal) }
2357
+ }
2358
+ }
2359
+ func stats(_ w: Work, _ pal: Pal) -> some View {
2360
+ HStack(spacing: 10) {
2361
+ if w.gpu >= 0.01 { IconStat(symbol: "display", value: pct1(w.gpu * 100), tip: "GPU", pal: pal) }
2362
+ if w.cpu >= 0.004 { IconStat(symbol: "cpu", value: pct1(w.cpu * 100), tip: "CPU, 기기 전체 대비", pal: pal) }
2363
+ if w.mem >= 512 { IconStat(symbol: "memorychip", value: memText(w.mem), tip: "메모리", pal: pal) }
2364
+ }
2365
+ }
2366
+ /** The right column while no session is picked: what is running now, whoever needs the user first. Picking a session shows its detail in this same column. */
2367
+ func nowColumn(_ snap: Snapshot, _ pal: Pal) -> some View {
2368
+ let everyone = model.ordered(snap.sessions)
2369
+ let all = everyone.filter { model.parentSession[$0.pid] == nil }
2370
+ let subsOf: (Session) -> [Session] = { up in everyone.filter { model.parentSession[$0.pid] == up.pid } }
2371
+ let busy: (Session) -> Bool = { s in model.phase(s) != .idle || subsOf(s).contains { model.phase($0) != .idle } }
2372
+ let live = all.filter { busy($0) }, idle = all.filter { !busy($0) }
2373
+ let body = VStack(alignment: .leading, spacing: 10) {
2374
+ Text("지금 도는 것").font(.system(size: 15, weight: .semibold)).foregroundColor(pal.text)
2375
+ if live.isEmpty { Text("작업 중인 세션이 없습니다").font(.system(size: 12)).foregroundColor(pal.text2) }
2376
+ ForEach(live) { s in
2377
+ let ph = model.phase(s), tint = pal.state(ph), mark = stateMark(s)
2378
+ let byLoad = ph == .active && s.state != "busy" && s.state != "shell" && s.subagents == 0
2379
+ let pending = (s.detail?.recent ?? []).last { $0.pending == true }
2380
+ Pressable(radius: 8, action: { selected = s.pid }) {
2381
+ VStack(alignment: .leading, spacing: 6) {
2382
+ HStack(spacing: 6) {
2383
+ if ph == .active { LiveDot(color: tint) } else { Image(systemName: mark.symbol).font(.system(size: 11)).foregroundColor(tint).frame(width: 12) }
2384
+ Text(s.name ?? s.agent).font(.system(size: 12.5, weight: .semibold)).foregroundColor(pal.text).lineLimit(1).truncationMode(.middle)
2385
+ Spacer(minLength: 4)
2386
+ Text(byLoad ? "프로그램 실행 중" : "\(mark.label) \(sinceText(s.stateSince, now: snap.at))").font(.system(size: 11)).foregroundColor(pal.text2).lineLimit(1).fixedSize()
2387
+ }
2388
+ if let p = pending {
2389
+ HStack(alignment: .top, spacing: 6) {
2390
+ Image(systemName: toolSymbol(p.tool)).font(.system(size: 10)).foregroundColor(pal.text2).frame(width: 12, height: 14)
2391
+ Text((p.target ?? "").isEmpty ? toolName(p.tool) : (p.target ?? "")).font(.system(size: 11.5)).foregroundColor(pal.text).lineLimit(2).fixedSize(horizontal: false, vertical: true)
2392
+ }
2393
+ }
2394
+ ForEach(Array(model.working(s, max: 3).enumerated()), id: \.offset) { _, it in
2395
+ VStack(alignment: .leading, spacing: 2) {
2396
+ HStack(spacing: 6) {
2397
+ Image(systemName: "gearshape.2.fill").font(.system(size: 9.5)).foregroundColor(pal.text2).frame(width: 12)
2398
+ Text(it.name).font(.system(size: 11.5, weight: .medium)).foregroundColor(pal.text).lineLimit(1).truncationMode(.middle).help(it.name)
2399
+ }
2400
+ stats(it.w, pal).padding(.leading, 18)
2401
+ }
2402
+ }
2403
+ let subs = subsOf(s)
2404
+ if !subs.isEmpty {
2405
+ HStack(spacing: 6) {
2406
+ Image(systemName: "arrow.turn.down.right").font(.system(size: 9.5, weight: .semibold)).foregroundColor(pal.text2).frame(width: 12)
2407
+ Text("띄운 세션 \(subs.count)개").font(.system(size: 11.5)).foregroundColor(pal.text)
2408
+ Spacer(minLength: 4)
2409
+ Text("작업 중 \(subs.filter { model.phase($0) == .active }.count)").font(.system(size: 11, weight: .medium)).monospacedDigit().foregroundColor(pal.text)
2410
+ }
2411
+ }
2412
+ }.padding(10).frame(maxWidth: .infinity, alignment: .leading).background(RoundedRectangle(cornerRadius: 8).fill(pal.well.opacity(0.55)))
2413
+ }
2414
+ }
2415
+ if !idle.isEmpty {
2416
+ Text("입력 대기").font(.system(size: 11)).foregroundColor(pal.text2).padding(.top, 4)
2417
+ ForEach(idle) { s in
2418
+ Pressable(radius: 6, action: { selected = s.pid }) {
2419
+ HStack(spacing: 6) {
2420
+ Image(systemName: "pause.circle").font(.system(size: 11)).foregroundColor(pal.text2).frame(width: 12)
2421
+ Text(s.name ?? s.agent).font(.system(size: 12)).foregroundColor(pal.text2).lineLimit(1).truncationMode(.middle)
2422
+ Spacer(minLength: 4)
2423
+ Text(sinceText(s.stateSince, now: snap.at)).font(.system(size: 10.5)).foregroundColor(pal.text2)
2424
+ }.padding(.vertical, 5).padding(.horizontal, 10).frame(maxWidth: .infinity, alignment: .leading)
2425
+ }
2426
+ }
2427
+ }
2428
+ if model.leftover.n > 0 {
2429
+ HStack(spacing: 6) {
2430
+ Image(systemName: "moon.zzz.fill").font(.system(size: 11)).foregroundColor(pal.left).frame(width: 12)
2431
+ Text("끝난 세션이 남긴 프로세스 \(model.leftover.n)개").font(.system(size: 11.5)).foregroundColor(pal.text)
2432
+ Spacer(minLength: 4)
2433
+ Text("\(pct1(model.leftover.cpu * 100)), \(memText(model.leftover.mem))").font(.system(size: 11, weight: .medium)).monospacedDigit().foregroundColor(pal.text)
2434
+ }.padding(.top, 6).padding(.horizontal, 10)
2435
+ }
2436
+ Divider().padding(.vertical, 4)
2437
+ trends(pal)
2438
+ }.padding(14).frame(width: 372, alignment: .topLeading)
2439
+ return Group { if still { body } else { ScrollView { body } } }
2440
+ }
2441
+ func content(_ width: CGFloat) -> some View {
2442
+ let pal = Pal(dark: scheme == .dark)
2443
+ let open = selected.flatMap { pid in model.snap?.sessions.first { $0.pid == pid } }
2444
+ let inner = max(318, width - 372 - 36)
2445
+ return HStack(alignment: .top, spacing: 0) {
2446
+ VStack(alignment: .leading, spacing: 12) {
2447
+ if let snap = model.snap {
2448
+ machine(snap, pal, width: inner)
2449
+ kpis(snap, pal, width: inner)
2450
+ if let ws = snap.warnings, !ws.isEmpty {
2451
+ HStack(spacing: 8) {
2452
+ ForEach(ws) { w in
2453
+ HStack(spacing: 6) {
2454
+ Image(systemName: w.level == "critical" ? "exclamationmark.octagon.fill" : "exclamationmark.triangle.fill").font(.system(size: 11)).foregroundColor(w.level == "critical" ? pal.critical : pal.warning)
2455
+ Text(w.chip.replacingOccurrences(of: "⚠ ", with: "").replacingOccurrences(of: "🚨 ", with: "")).font(.system(size: 12, weight: .medium)).foregroundColor(pal.text)
2456
+ }.padding(.horizontal, 9).padding(.vertical, 5).background(Capsule().fill(pal.tile)).help(w.advice?.first?.tip ?? w.advice?.first?.title ?? "")
2457
+ }
2458
+ Spacer(minLength: 0)
2459
+ }
2460
+ }
2461
+ if snap.sessions.isEmpty { Text("실행 중인 세션이 없습니다").font(.system(size: 13)).foregroundColor(pal.text2).frame(maxWidth: .infinity, maxHeight: .infinity) }
2462
+ else if still { groupsView(snap, pal, width: inner) } else { ScrollView { groupsView(snap, pal, width: inner) } }
2463
+ } else {
2464
+ Text(model.failure ?? "불러오는 중입니다").font(.system(size: 13)).foregroundColor(pal.text2).frame(maxWidth: .infinity, maxHeight: .infinity)
2465
+ }
2466
+ }.padding(.horizontal, 18).padding(.bottom, 18).padding(.top, 38).frame(maxWidth: .infinity, maxHeight: still ? nil : .infinity, alignment: .topLeading)
2467
+ if let snap = model.snap {
2468
+ Group { if let s = open { inspector(s, snap, pal) } else { nowColumn(snap, pal) } }.padding(.top, still ? 0 : 28).frame(width: 372, alignment: .top)
2469
+ }
2470
+ }.frame(minWidth: 1060, maxWidth: .infinity, minHeight: 420, maxHeight: still ? nil : .infinity, alignment: .topLeading)
2471
+ .background(alignment: .topTrailing) { Rectangle().fill(pal.tile).frame(width: 372) }.background(pal.surface)
2472
+ }
2473
+ var body: some View {
2474
+ if still { content(stillWidth) } else { GeometryReader { g in content(g.size.width) } }
2475
+ }
2476
+ }
2477
+ /** The animal is a rank, so the rank is said beside it: which species, where in the company, and what comes next. */
2478
+ struct RankHead: View {
2479
+ let st: Standing
2480
+ var body: some View {
2481
+ let place: String = st.idle == true ? "이번 달 사용 기록 없음" : (st.rank != nil && st.ranked != nil ? "종합 \(Int(st.ranked!))명 중 \(Int(st.rank!))위" : "순위 집계 전")
2482
+ let parts: [String] = [st.scorePct.map { "점수 백분위 \(Int($0))%" } ?? "", st.next.map { "다음 \($0.emoji) \($0.name)" + ($0.floorPct.map { " \(Int($0))%부터" } ?? "") } ?? "",
2483
+ st.next == nil && st.spendRank != nil && st.dlgRank != nil ? "사용량 \(Int(st.spendRank!))위, 위임 비율 \(Int(st.dlgRank!))위" : ""].filter { !$0.isEmpty }
2484
+ HStack(spacing: 9) {
2485
+ Text(st.emoji).font(.system(size: 25))
2486
+ VStack(alignment: .leading, spacing: 1) {
2487
+ HStack(spacing: 5) {
2488
+ Text("이달의 랭킹").font(.system(size: 10.5, weight: .medium)).foregroundColor(.secondary)
2489
+ if st.crown == true { Image(systemName: "crown.fill").font(.system(size: 9.5)).foregroundColor(.yellow) }
2490
+ }
2491
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
2492
+ Text(st.name).font(.system(size: 14, weight: .semibold))
2493
+ Text(place).font(.system(size: 12.5)).monospacedDigit()
2494
+ }.lineLimit(1)
2495
+ if !parts.isEmpty { Text(parts.joined(separator: ", ")).font(.system(size: 10.5)).foregroundColor(.secondary).lineLimit(2).fixedSize(horizontal: false, vertical: true) }
2496
+ }
2497
+ }
2498
+ }
2499
+ }
2500
+ struct LimitLine: Identifiable { let id: String; let agent: String; let name: String; let pct: Double; let reset: String }
2501
+ func planName(_ p: String?) -> String? {
2502
+ guard let p = p, !p.isEmpty else { return nil }
2503
+ return p == "free" ? "무료 플랜" : "\(p.prefix(1).uppercased())\(p.dropFirst()) 플랜"
2504
+ }
2505
+ /** How old a figure is, said only once it is old enough to matter. */
2506
+ func ageText(_ at: Double?, now: Double) -> String? {
2507
+ guard let at = at else { return nil }
2508
+ let min = Int((now - at) / 60000); if min < 10 { return nil }
2509
+ return min < 60 ? "\(min)분 전 기록" : "\(min / 60)시간 전 기록"
2510
+ }
2511
+ struct PanelView: View {
2512
+ @ObservedObject var model: Model
2513
+ @ObservedObject var prefs: Prefs
2514
+ @ObservedObject var nav: Nav
2515
+ @ObservedObject var book: RuleBook
2516
+ var still = false // a rendered capture shows the whole page, without the scroll view
2517
+ var lit: Int? = nil // draw this session's row as if the pointer were on it, for a capture
2518
+ @Environment(\.colorScheme) private var scheme
2519
+ var maxHeight: CGFloat = 900
2520
+ var onMenu: () -> Void = {}
2521
+ var onDashboard: () -> Void = {}
2522
+ func limits(_ snap: Snapshot) -> [LimitLine] {
2523
+ var out: [LimitLine] = []
2524
+ // An account limit says nothing to someone who is not running that agent: Codex shows only while a Codex session runs.
2525
+ let codex = snap.sessions.contains { $0.agent == "codex" }
2526
+ for (agent, l) in [("claude", snap.usage?.claude), ("codex", codex ? snap.usage?.codex : nil)] {
2527
+ // The Codex figure is whatever its last run wrote down, so say which plan it is and how old the record is.
2528
+ let about = [planName(l?.plan), ageText(l?.at, now: snap.at)].compactMap { $0 }
2529
+ for w in l?.windows ?? [] {
2530
+ let r = resetText(w.resetsAt, now: snap.at)
2531
+ out.append(LimitLine(id: "\(agent)-\(w.key)", agent: agent, name: windowName(w), pct: w.usedPct, reset: (about + (r.isEmpty ? [] : [r])).joined(separator: ", ")))
2532
+ }
2533
+ }
2534
+ return out
2535
+ }
2536
+ var body: some View {
2537
+ Group {
2538
+ switch nav.page {
2539
+ case .status: status
2540
+ case .settings: SettingsView(prefs: prefs, back: { nav.page = .status })
2541
+ case .rules: RulesView(book: book, limit: maxHeight, back: { nav.page = .status })
2542
+ case .session(let pid):
2543
+ let s = model.snap?.sessions.first { $0.pid == pid }
2544
+ SessionView(s: s, cpu: s.map { model.cpuOf($0) } ?? 0, mem: s.map { model.memOf($0) } ?? 0, now: model.snap?.at ?? 0, off: model.detailOff, limit: maxHeight, back: { nav.page = .status })
2545
+ case .warning(let chip): WarningView(w: model.snap?.warnings?.first { $0.chip == chip }, now: model.snap?.at ?? 0, limit: maxHeight, back: { nav.page = .status })
2546
+ }
2547
+ }
2548
+ }
2549
+ /** How many sessions, and how they stand: working, waiting for a go-ahead, waiting for input. Sessions another one started are counted apart. */
2550
+ func sessionsTitle(_ snap: Snapshot) -> String {
2551
+ let mains = snap.sessions.filter { model.parentSession[$0.pid] == nil }, phases = mains.map { model.phase($0) }
2552
+ var parts = ["세션 \(mains.count)개", "작업 중 \(phases.filter { $0 == .active }.count)"]
2553
+ let user = phases.filter { $0 == .needsUser }.count, idle = phases.filter { $0 == .idle }.count
2554
+ if user > 0 { parts.append("확인 대기 \(user)") }
2555
+ if idle > 0 { parts.append("입력 대기 \(idle)") }
2556
+ if snap.sessions.count > mains.count { parts.append("띄운 세션 \(snap.sessions.count - mains.count)") }
2557
+ return parts.joined(separator: ", ")
2558
+ }
2559
+ func headButton(_ symbol: String, _ tip: String, _ action: @escaping () -> Void) -> some View {
2560
+ Button(action: action) { Image(systemName: symbol).font(.system(size: 14, weight: .medium)).frame(width: 26, height: 22).contentShape(Rectangle()) }.buttonStyle(HoverStyle(radius: 6)).help(tip)
2561
+ }
2562
+ var status: some View {
2563
+ VStack(alignment: .leading, spacing: 10) {
2564
+ HStack(spacing: 8) {
2565
+ if let st = model.snap?.standing { RankHead(st: st) } else {
2566
+ Text("✇").font(.system(size: 17))
2567
+ Text("Sprag").font(.system(size: 15, weight: .medium)).foregroundColor(.secondary)
2568
+ }
2569
+ Spacer()
2570
+ headButton("rectangle.grid.2x2", "대시보드", onDashboard)
2571
+ headButton("checklist", "규칙") { nav.page = .rules }
2572
+ headButton("gearshape", "설정") { nav.page = .settings }
2573
+ headButton("ellipsis", "메뉴", onMenu)
2574
+ }.padding(.horizontal, 4)
2575
+ if let snap = model.snap {
2576
+ // The whole card scrolls once it is taller than the screen; guessing which block to shrink went wrong as blocks were added.
2577
+ FitScroll(limit: maxHeight - 92, still: still) { VStack(spacing: 0) {
2578
+ let cpuAll = model.share(nil), memAll = model.mem(nil)
2579
+ let hasCodex = snap.sessions.contains { $0.agent == "codex" }
2580
+ let warns = snap.warnings ?? []
2581
+ if !warns.isEmpty {
2582
+ WarningList(warnings: warns) { nav.page = .warning($0.chip) }
2583
+ Divider().padding(.horizontal, 12)
2584
+ }
2585
+ Block(symbol: "terminal", title: snap.totals.sessions == 0 ? "실행 중인 세션 없음" : sessionsTitle(snap)) {
2586
+ let groups = groupSessions(model.ordered(snap.sessions), parents: model.parentSession)
2587
+ let rows = VStack(alignment: .leading, spacing: 0) {
2588
+ ForEach(groups) { g in
2589
+ let many = g.sessions.count > 1
2590
+ if many {
2591
+ HStack(spacing: 5) {
2592
+ Image(systemName: "folder.fill").font(.system(size: 10))
2593
+ Text(g.name).font(.system(size: 11, weight: .semibold)).lineLimit(1).truncationMode(.middle)
2594
+ Text("세션 \(g.sessions.count)개").font(.system(size: 10.5))
2595
+ Spacer(minLength: 0)
2596
+ }.foregroundColor(.secondary).padding(.top, 8).padding(.bottom, 2)
2597
+ }
2598
+ VStack(alignment: .leading, spacing: 0) {
2599
+ // A session that another one here started is one line under it, as on the dashboard: they come in batches.
2600
+ ForEach(g.sessions) { s in
2601
+ let sub = model.parentSession[s.pid].map { up in g.sessions.contains { $0.pid == up } } ?? false
2602
+ if sub {
2603
+ Pressable(radius: 9, action: { nav.page = .session(s.pid) }) { SubTile(s: s, now: snap.at, selected: false, pal: Pal(dark: scheme == .dark), phase: model.phase(s)) }
2604
+ .padding(.vertical, 2).help("눌러서 이 세션의 상세 보기")
2605
+ } else {
2606
+ if s.id != g.sessions.first?.id { Divider() }
2607
+ Button(action: { nav.page = .session(s.pid) }) { SessionRow(s: s, cpu: model.cpuOf(s), mem: model.memOf(s), now: snap.at).contentShape(Rectangle()) }
2608
+ .buttonStyle(HoverStyle(radius: 7, grow: 4, lit: lit == s.pid)).help("눌러서 이 세션의 상세 보기")
2609
+ }
2610
+ }
2611
+ }.padding(.leading, many ? 10 : 0).overlay(alignment: .leading) { if many { Rectangle().fill(Color.primary.opacity(0.22)).frame(width: 2).padding(.vertical, 7) } }
2612
+ if g.id != groups.last?.id { Divider() }
2613
+ }
2614
+ }
2615
+ rows
2616
+ }
2617
+ Divider().padding(.horizontal, 12)
2618
+ let pal = Pal(dark: scheme == .dark), sm = model.samples, span = spanText(sm.first?.at, sm.last?.at)
2619
+ let cpuCl = model.share("claude"), cpuCx = model.share("codex"), cpuLeft = model.leftover.cpu * 100
2620
+ let cpuDev = max((model.sysCpu ?? 0) * 100, cpuAll + cpuLeft)
2621
+ let memCl = model.mem("claude"), memCx = model.mem("codex"), memLeft = model.leftover.mem, memOther = model.others.reduce(0) { $0 + $1.mem }
2622
+ let grey = Color.primary.opacity(0.35)
2623
+ // The machine's total and who makes it up, as parts of one bar; then a trend with its scale written on it.
2624
+ Block(symbol: "cpu", title: "CPU: 기기 전체 \(pct1(cpuDev)), 세션 \(pct1(cpuAll))") {
2625
+ SplitBar(parts: [(cpuCl, CLAUDE), (cpuCx, CODEX), (cpuLeft, LEFT), (max(0, cpuDev - cpuAll - cpuLeft), grey)], scale: 100).padding(.vertical, 2)
2626
+ Legend(color: CLAUDE, label: "Claude 세션:", value: pct1(cpuCl))
2627
+ if hasCodex { Legend(color: CODEX, label: "Codex 세션:", value: pct1(cpuCx)) }
2628
+ if model.leftover.n > 0 { Legend(color: LEFT, label: "끝난 세션이 남긴 것:", value: "\(pct1(cpuLeft)), 프로세스 \(model.leftover.n)개") }
2629
+ Legend(color: grey, label: "그 밖:", value: pct1(max(0, cpuDev - cpuAll - cpuLeft)))
2630
+ TrendChart(title: "추이", lines: [.init(id: "기기 전체", values: sm.map { $0.sysCpu * 100 }, color: pal.neutral, fill: true), .init(id: "세션", values: sm.map { ($0.claudeCpu + $0.codexCpu) * 100 }, color: CLAUDE)],
2631
+ top: 100, fmt: { "\(Int($0.rounded()))%" }, span: span, pal: pal, height: 34).padding(.top, 4)
2632
+ }
2633
+ Divider().padding(.horizontal, 12)
2634
+ Block(symbol: "memorychip", title: "메모리: 기기 전체 \(memText(model.sysMemMb)), 세션 \(memText(memAll))") {
2635
+ SplitBar(parts: [(memCl, CLAUDE), (memCx, CODEX), (memLeft, LEFT), (memOther, grey)], scale: RAM_MB).padding(.vertical, 2)
2636
+ Legend(color: CLAUDE, label: "Claude 세션:", value: memText(memCl))
2637
+ if hasCodex { Legend(color: CODEX, label: "Codex 세션:", value: memText(memCx)) }
2638
+ if model.leftover.n > 0 { Legend(color: LEFT, label: "끝난 세션이 남긴 것:", value: memText(memLeft)) }
2639
+ Legend(color: grey, label: "다른 프로그램:", value: memText(memOther))
2640
+ TrendChart(title: "추이", lines: [.init(id: "기기 전체", values: sm.map { $0.sysMem * RAM_MB }, color: pal.neutral, fill: true), .init(id: "세션", values: sm.map { ($0.claudeMem + $0.codexMem) * RAM_MB }, color: CLAUDE)],
2641
+ top: RAM_MB, fmt: { memText($0) }, span: span, pal: pal, height: 34).padding(.top, 4)
2642
+ }
2643
+ if let g = model.gpu {
2644
+ Divider().padding(.horizontal, 12)
2645
+ Block(symbol: "display", title: "GPU: \(pct1(g * 100))") {
2646
+ let gCl = min(100, snap.sessions.filter { $0.agent != "codex" }.reduce(0) { $0 + (model.gpuBySession[$1.pid] ?? 0) } * 100)
2647
+ let gCx = min(100, snap.sessions.filter { $0.agent == "codex" }.reduce(0) { $0 + (model.gpuBySession[$1.pid] ?? 0) } * 100)
2648
+ let gLeft = min(100, model.gpuUse.filter { $0.left }.reduce(0) { $0 + $1.share } * 100)
2649
+ SplitBar(parts: [(gCl, CLAUDE), (gCx, CODEX), (gLeft, LEFT), (max(0, g * 100 - gCl - gCx - gLeft), grey)], scale: 100).padding(.vertical, 2)
2650
+ Legend(color: CLAUDE, label: "Claude 세션:", value: pct1(gCl))
2651
+ if hasCodex { Legend(color: CODEX, label: "Codex 세션:", value: pct1(gCx)) }
2652
+ if gLeft >= 0.1 { Legend(color: LEFT, label: "끝난 세션이 남긴 것:", value: pct1(gLeft)) }
2653
+ Legend(color: grey, label: "그 밖:", value: "\(pct1(max(0, g * 100 - gCl - gCx - gLeft))), GPU 메모리 \(memText(model.gpuMemMb))")
2654
+ Text("많이 쓰는 곳").font(.system(size: 10.5)).foregroundColor(.secondary).padding(.top, 3)
2655
+ let lines = model.gpuLines(snap.sessions, max: 4)
2656
+ ForEach(lines) { l in
2657
+ HStack(spacing: 6) {
2658
+ RoundedRectangle(cornerRadius: 2).fill(l.agent == nil ? Color.primary.opacity(0.35) : l.agent == "left" ? LEFT : l.agent == "codex" ? CODEX : CLAUDE).frame(width: 9, height: 9)
2659
+ Text(l.label).lineLimit(1).truncationMode(.middle)
2660
+ if !l.note.isEmpty { Text(l.note).foregroundColor(.secondary).lineLimit(1).truncationMode(.tail) }
2661
+ Spacer(minLength: 4)
2662
+ Text(pct1(l.share * 100)).monospacedDigit()
2663
+ }.font(.system(size: 12)).help(l.agent == nil ? "세션과 무관한 프로그램" : l.agent == "left" ? "끝난 세션이 남긴 프로세스" : "이 세션이 띄운 프로세스가 쓰는 GPU")
2664
+ }
2665
+ if lines.isEmpty { Text("지금 GPU를 쓰는 프로세스가 없습니다").font(.system(size: 10.5)).foregroundColor(.secondary) }
2666
+ TrendChart(title: "추이", lines: [.init(id: "기기 전체", values: sm.map { $0.gpu * 100 }, color: pal.neutral, fill: true), .init(id: "세션", values: sm.map { ($0.claudeGpu + $0.codexGpu) * 100 }, color: CLAUDE)],
2667
+ top: 100, fmt: { "\(Int($0.rounded()))%" }, span: span, pal: pal, height: 34).padding(.top, 4)
2668
+ }
2669
+ }
2670
+ Divider().padding(.horizontal, 12)
2671
+ let lines = limits(snap)
2672
+ Block(symbol: "speedometer", title: "사용량") {
2673
+ if lines.isEmpty { Text("한도 정보가 아직 없습니다").font(.system(size: 12)).foregroundColor(.secondary) }
2674
+ ForEach(lines) { l in
2675
+ VStack(alignment: .leading, spacing: 2) {
2676
+ HStack(spacing: 7) {
2677
+ Badge(agent: l.agent)
2678
+ Text(l.name).font(.system(size: 12, weight: .medium)).frame(width: 62, alignment: .leading)
2679
+ Bar(value: l.pct / 100, tint: l.pct >= 90 ? .red : l.pct >= 70 ? .orange : agentTint(l.agent))
2680
+ Text("\(Int(l.pct.rounded()))%").font(.system(size: 12, weight: .medium)).monospacedDigit().frame(width: 38, alignment: .trailing)
2681
+ }
2682
+ if !l.reset.isEmpty { Text(l.reset).font(.system(size: 10.5)).foregroundColor(.secondary) }
2683
+ }.padding(.top, 1)
2684
+ }
2685
+ if let c = snap.totals.costUsd {
2686
+ HStack(spacing: 6) { Text("실행 중 세션 합계(정가 환산):").foregroundColor(.secondary); Text(String(format: "$%.2f", c)).monospacedDigit().fontWeight(.medium) }.font(.system(size: 12)).padding(.top, 3)
2687
+ }
2688
+ }
2689
+ } }.background(RoundedRectangle(cornerRadius: 12).fill(CARD_FILL)).overlay(RoundedRectangle(cornerRadius: 12).stroke(Color.primary.opacity(0.10), lineWidth: 1))
2690
+ } else {
2691
+ Text(model.failure ?? "불러오는 중입니다").font(.system(size: 12.5)).foregroundColor(.secondary).frame(maxWidth: .infinity, alignment: .center).padding(.vertical, 26)
2692
+ }
2693
+ }.padding(12).frame(width: 408)
2694
+ }
2695
+ }
2696
+
2697
+ // ---------- the menu bar item and its window ----------
2698
+ final class FloatPanel: NSPanel { override var canBecomeKey: Bool { true } }
2699
+ func dockIcon() -> NSImage {
2700
+ NSImage(size: NSSize(width: 512, height: 512), flipped: false) { r in
2701
+ NSColor(red: 0.10, green: 0.10, blue: 0.098, alpha: 1).setFill()
2702
+ NSBezierPath(roundedRect: r.insetBy(dx: 44, dy: 44), xRadius: 96, yRadius: 96).fill()
2703
+ let glyph = NSAttributedString(string: "✇", attributes: [.font: NSFont.systemFont(ofSize: 280, weight: .bold), .foregroundColor: NSColor(red: 0.85, green: 0.35, blue: 0.15, alpha: 1)])
2704
+ let size = glyph.size()
2705
+ glyph.draw(at: NSPoint(x: r.midX - size.width / 2, y: r.midY - size.height / 2))
2706
+ return true
2707
+ }
2708
+ }
2709
+ /** The few menu commands a window needs once the app is a regular one: close, minimise, quit. */
2710
+ func dashboardMenu() -> NSMenu {
2711
+ let bar = NSMenu()
2712
+ let appItem = NSMenuItem(), appMenu = NSMenu()
2713
+ appMenu.addItem(NSMenuItem(title: "Sprag 끝내기", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))
2714
+ appItem.submenu = appMenu; bar.addItem(appItem)
2715
+ let winItem = NSMenuItem(), winMenu = NSMenu(title: "윈도우")
2716
+ winMenu.addItem(NSMenuItem(title: "닫기", action: #selector(NSWindow.performClose(_:)), keyEquivalent: "w"))
2717
+ winMenu.addItem(NSMenuItem(title: "최소화", action: #selector(NSWindow.performMiniaturize(_:)), keyEquivalent: "m"))
2718
+ winItem.submenu = winMenu; bar.addItem(winItem)
2719
+ return bar
2720
+ }
2721
+ extension App: NSApplicationDelegate {
2722
+ /** A click on the Dock icon: show the dashboard again, wherever it went. */
2723
+ func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { showDashboard(); return false }
2724
+ func applicationWillTerminate(_ notification: Notification) { if let dir = dataDir, selftest == nil { try? FileManager.default.removeItem(atPath: dir + "/bar-app.json") } }
2725
+ }
2726
+ final class App: NSObject {
2727
+ let model = Model()
2728
+ let prefs = Prefs()
2729
+ let nav = Nav()
2730
+ let book = RuleBook()
2731
+ let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
2732
+ var panel: FloatPanel!
2733
+ var hosting: NSHostingView<PanelView>!
2734
+ var frame = 0
2735
+ var outside: Any?, keys: Any?
2736
+ var dash: NSWindow?
2737
+ var isOpen: Bool { panel.isVisible }
2738
+ var dashOpen: Bool { dash?.isVisible == true }
2739
+ /** Each session's work is asked for only while something that shows it is on screen. */
2740
+ func syncDetail() {
2741
+ var page = false
2742
+ if case .session = nav.page { page = true }
2743
+ let want = dashOpen || (isOpen && page)
2744
+ if want != model.wantDetail { model.wantDetail = want; if want { model.refresh() } }
2745
+ }
2746
+ @objc func showDashboard() {
2747
+ if isOpen { close() }
2748
+ if dash == nil {
2749
+ let room = NSScreen.main?.visibleFrame.size ?? NSSize(width: 1480, height: 900)
2750
+ let w = NSWindow(contentRect: NSRect(x: 0, y: 0, width: min(1480, room.width - 40), height: min(900, room.height - 60)), styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView], backing: .buffered, defer: false)
2751
+ w.title = "Sprag 대시보드"; w.isReleasedWhenClosed = false; w.titlebarAppearsTransparent = true; w.minSize = NSSize(width: 1060, height: 560)
2752
+ // A plain surface, not a see-through material: the chart colours were checked against this one.
2753
+ w.contentView = NSHostingView(rootView: DashboardView(model: model)); w.center()
2754
+ NotificationCenter.default.addObserver(forName: NSWindow.willCloseNotification, object: w, queue: .main) { [weak self] _ in DispatchQueue.main.async { self?.syncDetail(); NSApp.setActivationPolicy(.accessory) } }
2755
+ dash = w
2756
+ }
2757
+ // A menu bar app has no Dock icon, so a dashboard that slipped behind other windows could only be found through the
2758
+ // menu bar again. While the window is open the app is a regular one: Dock icon, app switcher, and a click on either brings it back.
2759
+ NSApp.setActivationPolicy(.regular)
2760
+ NSApp.applicationIconImage = dockIcon()
2761
+ if NSApp.mainMenu == nil { NSApp.mainMenu = dashboardMenu() }
2762
+ NSApp.activate(ignoringOtherApps: true)
2763
+ if dash?.isMiniaturized == true { dash?.deminiaturize(nil) }
2764
+ dash?.makeKeyAndOrderFront(nil)
2765
+ syncDetail()
2766
+ }
2767
+ func start() {
2768
+ panel = FloatPanel(contentRect: NSRect(x: 0, y: 0, width: 408, height: 300), styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: true)
2769
+ panel.isOpaque = false; panel.backgroundColor = .clear; panel.hasShadow = true; panel.level = .popUpMenu
2770
+ panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .transient]
2771
+ let fx = NSVisualEffectView(frame: panel.contentLayoutRect)
2772
+ fx.material = .popover; fx.blendingMode = .behindWindow; fx.state = .active
2773
+ fx.wantsLayer = true; fx.layer?.cornerRadius = 14; fx.layer?.masksToBounds = true
2774
+ let cap = (NSScreen.main?.visibleFrame.height ?? 900) - 12
2775
+ hosting = NSHostingView(rootView: PanelView(model: model, prefs: prefs, nav: nav, book: book, maxHeight: cap, onMenu: { [weak self] in self?.showMenu() }, onDashboard: { [weak self] in self?.showDashboard() }))
2776
+ // The page changed or its content grew: fit the window again once SwiftUI has laid it out.
2777
+ RELAYOUT = { [weak self] in DispatchQueue.main.async { if self?.isOpen == true { self?.place() } } }
2778
+ prefs.onLayout = RELAYOUT
2779
+ nav.onChange = { [weak self] page in
2780
+ guard let self = self else { return }
2781
+ if page == .settings { self.prefs.open() }
2782
+ if page == .rules { self.book.note = ""; self.book.failed = false; self.book.confirm = nil; self.book.expanded = nil; self.book.load() }
2783
+ self.syncDetail()
2784
+ RELAYOUT()
2785
+ }
2786
+ hosting.frame = fx.bounds; hosting.autoresizingMask = [.width, .height]
2787
+ fx.addSubview(hosting); panel.contentView = fx
2788
+ item.button?.imagePosition = .imageLeading
2789
+ item.button?.font = NSFont.monospacedDigitSystemFont(ofSize: 12, weight: .regular)
2790
+ item.button?.target = self; item.button?.action = #selector(toggle)
2791
+ model.onUpdate = { [weak self] in self?.title(); if self?.isOpen == true { self?.place() } }
2792
+ animate(); poll()
2793
+ }
2794
+ func title() {
2795
+ guard let s = model.snap, let b = item.button else { item.button?.title = ""; return }
2796
+ let text = model.sysCpu != nil ? String(format: " %.0f%%", (model.sysCpu ?? 0) * 100) : " \(s.totals.busy)/\(s.totals.sessions)"
2797
+ let out = NSMutableAttributedString()
2798
+ if let w = s.warnings, !w.isEmpty { // the statusline's warning, where it is seen without looking at a terminal
2799
+ let tint = w.contains { $0.level == "critical" } ? NSColor.systemRed : NSColor.systemOrange
2800
+ // Two palette colours: with one, the exclamation mark took the triangle's colour and vanished.
2801
+ let conf = NSImage.SymbolConfiguration(pointSize: 13, weight: .bold).applying(NSImage.SymbolConfiguration(paletteColors: [NSColor.white, tint]))
2802
+ if let sym = NSImage(systemSymbolName: "exclamationmark.triangle.fill", accessibilityDescription: "경고")?.withSymbolConfiguration(conf) {
2803
+ let a = NSTextAttachment(); a.image = sym; a.bounds = NSRect(x: 0, y: -2, width: sym.size.width, height: sym.size.height)
2804
+ out.append(NSAttributedString(string: " ")); out.append(NSAttributedString(attachment: a))
2805
+ }
2806
+ }
2807
+ if model.sysCpu != nil, let chip = NSImage(systemSymbolName: "cpu", accessibilityDescription: "CPU")?.withSymbolConfiguration(NSImage.SymbolConfiguration(pointSize: 10.5, weight: .regular)) {
2808
+ chip.isTemplate = true
2809
+ let a = NSTextAttachment(); a.image = chip; a.bounds = NSRect(x: 0, y: -1.5, width: chip.size.width, height: chip.size.height)
2810
+ out.append(NSAttributedString(string: " ")); out.append(NSAttributedString(attachment: a))
2811
+ }
2812
+ out.append(NSAttributedString(string: text, attributes: [.font: NSFont.monospacedDigitSystemFont(ofSize: 12, weight: .regular), .foregroundColor: NSColor.labelColor, .baselineOffset: 0.5]))
2813
+ b.attributedTitle = out
2814
+ b.toolTip = model.sysCpu != nil ? String(format: "기기 전체 CPU %.0f%%, 그중 AI 세션 %.0f%%. 세션 %d개 실행 중", (model.sysCpu ?? 0) * 100, model.share(nil), s.totals.sessions) : "작업 중인 세션 수 / 실행 중인 세션 수"
2815
+ }
2816
+ func animate() {
2817
+ // RunCat's rule, on the same thing RunCat measures: the whole machine. A runner that strolls while the machine is
2818
+ // flat out, because the agent sessions' own share happens to be small, reads as wrong.
2819
+ let load = min(100, max(0, (model.sysCpu ?? 0) * 100))
2820
+ item.button?.image = runner(frame: frame, idle: load < 5)
2821
+ frame += 1
2822
+ // RunCat's own curve: one stride takes (100 - load) / 60 seconds, so the pace climbs steeply as the machine fills up.
2823
+ // The stride is spread over this runner's poses, and a frame never comes faster than a display shows it.
2824
+ let gap = load < 5 ? 0.8 : max(1.0 / 60, (100 - load) / 60 / Double(GALLOP.count))
2825
+ DispatchQueue.main.asyncAfter(deadline: .now() + gap) { [weak self] in self?.animate() }
2826
+ }
2827
+ func poll() {
2828
+ model.refresh()
2829
+ DispatchQueue.main.asyncAfter(deadline: .now() + (isOpen ? 2 : dashOpen ? 3 : 4)) { [weak self] in self?.poll() }
2830
+ }
2831
+ /** Size the window to its content and hang it under the menu bar item, wholly inside the screen. */
2832
+ func place() {
2833
+ guard let b = item.button, let bw = b.window, let screen = bw.screen ?? NSScreen.main else { return }
2834
+ hosting.layoutSubtreeIfNeeded()
2835
+ let vis = screen.visibleFrame, fit = hosting.fittingSize
2836
+ let w = fit.width, h = min(fit.height, vis.height - 12)
2837
+ let anchor = bw.convertToScreen(b.convert(b.bounds, to: nil))
2838
+ let x = min(max(anchor.midX - w / 2, vis.minX + 8), vis.maxX - w - 8)
2839
+ let top = min(anchor.minY - 5, vis.maxY - 5)
2840
+ panel.setFrame(NSRect(x: x, y: top - h, width: w, height: h), display: true)
2841
+ }
2842
+ func showMenu() {
2843
+ let m = NSMenu()
2844
+ let r = NSMenuItem(title: "지금 새로 고침", action: #selector(refreshNow), keyEquivalent: "r"); r.target = self; m.addItem(r)
2845
+ let d = NSMenuItem(title: "대시보드", action: #selector(showDashboard), keyEquivalent: "d"); d.target = self; m.addItem(d)
2846
+ let k = NSMenuItem(title: "규칙…", action: #selector(showRules), keyEquivalent: ""); k.target = self; m.addItem(k)
2847
+ let g = NSMenuItem(title: "설정…", action: #selector(showSettings), keyEquivalent: ","); g.target = self; m.addItem(g)
2848
+ m.addItem(.separator())
2849
+ let off = NSMenuItem(title: "자동으로 띄우지 않기 (sprag bar off)", action: #selector(turnOff), keyEquivalent: ""); off.target = self; m.addItem(off)
2850
+ let q = NSMenuItem(title: "Sprag Bar 끝내기", action: #selector(quit), keyEquivalent: "q"); q.target = self; m.addItem(q)
2851
+ m.popUp(positioning: nil, at: NSEvent.mouseLocation, in: nil)
2852
+ }
2853
+ @objc func refreshNow() { model.refresh() }
2854
+ @objc func showSettings() { nav.page = .settings }
2855
+ @objc func showRules() { nav.page = .rules }
2856
+ @objc func quit() { NSApp.terminate(nil) }
2857
+ /** `sprag bar off` records the choice and stops this app; quitting alone only lasts until the next session starts. */
2858
+ @objc func turnOff() { sprag(["bar", "off"], timeout: 8) { _, _, _ in NSApp.terminate(nil) } }
2859
+ @objc func toggle() {
2860
+ // The second click of a double click: the first one opened or closed the panel, this one asks for the dashboard.
2861
+ if NSApp.currentEvent?.clickCount == 2 { showDashboard(); return }
2862
+ if isOpen { close() } else { open() }
2863
+ }
2864
+ func open() {
2865
+ model.refresh(); place(); panel.orderFrontRegardless(); panel.makeKey(); item.button?.highlight(true)
2866
+ outside = NSEvent.addGlobalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown]) { [weak self] _ in self?.close() }
2867
+ keys = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] e in if e.keyCode == 53 { self?.close(); return nil }; return e }
2868
+ }
2869
+ func close() {
2870
+ panel.orderOut(nil); item.button?.highlight(false)
2871
+ if nav.page != .status { nav.page = .status } // the next click opens on the status page
2872
+ syncDetail()
2873
+ if let m = outside { NSEvent.removeMonitor(m); outside = nil }
2874
+ if let m = keys { NSEvent.removeMonitor(m); keys = nil }
2875
+ }
2876
+ }
2877
+
2878
+ var args = Array(CommandLine.arguments.dropFirst())
2879
+ var ttl: Double = 0, selftest: String? = nil, selftestWrite = false, selftestWait = 9.5 // ttl 0: run until quit
2880
+ var selftestClean: String? = nil // self-test only: the one leftover line to stop, by its exact name
2881
+ var dataDir: String? = nil, versionTag = "" // where sprag keeps its state, and the sprag version that built this copy
2882
+ let app = NSApplication.shared
2883
+ app.setActivationPolicy(.accessory)
2884
+ let main = App()
2885
+ app.delegate = main // after main exists: a global read before its own line is still empty
2886
+ while !args.isEmpty {
2887
+ let a = args.removeFirst()
2888
+ switch a {
2889
+ case "--node": NODE = args.removeFirst()
2890
+ case "--cli": CLI = args.removeFirst()
2891
+ case "--trace": TRACE = true
2892
+ case "--selftest-write": selftestWrite = true
2893
+ case "--selftest-wait": selftestWait = Double(args.removeFirst()) ?? 9.5 // a longer wait gathers more history for the trend lines
2894
+ case "--ttl": ttl = Double(args.removeFirst()) ?? 0
2895
+ case "--data-dir": dataDir = args.removeFirst()
2896
+ case "--selftest-clean": selftestClean = args.removeFirst()
2897
+ case "--version-tag": versionTag = args.removeFirst()
2898
+ case "--selftest": selftest = args.removeFirst()
2899
+ default: break
2900
+ }
2901
+ }
2902
+ func png(_ image: NSImage, _ path: String) {
2903
+ guard let tiff = image.tiffRepresentation, let rep = NSBitmapImageRep(data: tiff), let data = rep.representation(using: .png, properties: [:]) else { return }
2904
+ try? data.write(to: URL(fileURLWithPath: path)); print("SNAP \(path)")
2905
+ }
2906
+ /** A view as the window really draws it, laid over roughly the colour the window's material has (the material itself is not captured). */
2907
+ func liveShot(_ view: NSView, _ path: String, forceDark: Bool = false) {
2908
+ guard let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { return }
2909
+ view.cacheDisplay(in: view.bounds, to: rep)
2910
+ let dark = forceDark || view.effectiveAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua
2911
+ guard let out = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: rep.pixelsWide, pixelsHigh: rep.pixelsHigh, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0),
2912
+ let ctx = NSGraphicsContext(bitmapImageRep: out) else { return }
2913
+ NSGraphicsContext.saveGraphicsState(); NSGraphicsContext.current = ctx
2914
+ let r = NSRect(x: 0, y: 0, width: rep.pixelsWide, height: rep.pixelsHigh)
2915
+ (dark ? NSColor(white: 0.17, alpha: 1) : NSColor(white: 0.93, alpha: 1)).setFill(); r.fill(); rep.draw(in: r)
2916
+ NSGraphicsContext.restoreGraphicsState()
2917
+ if let data = out.representation(using: .png, properties: [:]) { try? data.write(to: URL(fileURLWithPath: path)); print("SNAP \(path) (\(dark ? "dark" : "light") appearance)") }
2918
+ }
2919
+ func fitCheck(_ label: String) {
2920
+ guard let screen = main.panel.screen ?? NSScreen.main else { return }
2921
+ let f = main.panel.frame, vis = screen.visibleFrame, fit = main.hosting.fittingSize
2922
+ print("\(label) GEOMETRY panel \(Int(f.width))x\(Int(f.height)) top \(Int(f.maxY)) | visible top \(Int(vis.maxY)) bottom \(Int(vis.minY)) | content \(Int(fit.width))x\(Int(fit.height))")
2923
+ print("\(label) CHECK top inside screen: \(f.maxY <= vis.maxY) | bottom inside screen: \(f.minY >= vis.minY) | whole content shown: \(f.height >= fit.height - 0.5) | right inside: \(f.maxX <= vis.maxX)")
2924
+ }
2925
+ @MainActor func render<V: View>(_ view: V, _ path: String, dark: Bool = true) {
2926
+ let r = ImageRenderer(content: view.background(dark ? Color(white: 0.17) : Color(white: 0.93)).environment(\.colorScheme, dark ? .dark : .light))
2927
+ r.scale = 2
2928
+ if let img = r.nsImage { png(img, path) }
2929
+ }
2930
+ let SANDBOX = ProcessInfo.processInfo.environment["SPRAGBAR_SANDBOX"] == "1" && ProcessInfo.processInfo.environment["XDG_CONFIG_HOME"] != nil
2931
+ typealias Step = (String, (@escaping () -> Void) -> Void, () -> Bool)
2932
+ /** Run the steps one after another. Each reports whether what the CLI reads back is what the step meant to set. */
2933
+ func runSteps(_ label: String, _ list: [Step], note: @escaping () -> String, done: @escaping () -> Void) {
2934
+ var steps = list
2935
+ func next() {
2936
+ if steps.isEmpty { done(); return }
2937
+ let (name, run, ok) = steps.removeFirst()
2938
+ run { print("\(label) \(name): \(ok() ? "ok" : "FAILED") | note '\(note())'"); fflush(stdout); next() }
2939
+ }
2940
+ next()
2941
+ }
2942
+ main.start()
2943
+ if let prefix = selftest {
2944
+ DispatchQueue.main.asyncAfter(deadline: .now() + selftestWait) {
2945
+ main.open()
2946
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {
2947
+ fitCheck("STATUS")
2948
+ render(PanelView(model: main.model, prefs: Prefs(), nav: Nav(), book: RuleBook(), still: true), "\(prefix)-panel-dark.png")
2949
+ render(PanelView(model: main.model, prefs: Prefs(), nav: Nav(), book: RuleBook(), still: true), "\(prefix)-panel-light.png", dark: false)
2950
+ let n = GALLOP.count + 2, k: CGFloat = 8
2951
+ let RW = runner(frame: 0, idle: true).size.width, RH = runner(frame: 0, idle: true).size.height
2952
+ let sheet = NSImage(size: NSSize(width: RW * k * CGFloat(n), height: RH * k * 2), flipped: false) { _ in
2953
+ NSColor(white: 0.93, alpha: 1).setFill(); NSRect(x: 0, y: RH * k, width: RW * k * CGFloat(n), height: RH * k).fill()
2954
+ NSColor(white: 0.14, alpha: 1).setFill(); NSRect(x: 0, y: 0, width: RW * k * CGFloat(n), height: RH * k).fill()
2955
+ for row in 0..<2 {
2956
+ for i in 0..<n {
2957
+ let im = runner(frame: i < GALLOP.count ? i : i - GALLOP.count, idle: i >= GALLOP.count)
2958
+ let tinted = NSImage(size: im.size, flipped: false) { r in im.draw(in: r); (row == 0 ? NSColor.white : NSColor.black).set(); r.fill(using: .sourceAtop); return true }
2959
+ tinted.draw(in: NSRect(x: CGFloat(i) * RW * k, y: row == 0 ? 0 : RH * k, width: RW * k, height: RH * k))
2960
+ }
2961
+ }
2962
+ return true
2963
+ }
2964
+ png(sheet, "\(prefix)-runner.png")
2965
+ liveShot(main.hosting, "\(prefix)-panel-live.png")
2966
+ if let b = main.item.button { liveShot(b, "\(prefix)-item-live.png", forceDark: true) } // the menu bar item itself, warning mark included
2967
+ let s = main.model.snap
2968
+ print("TITLE '\(main.item.button?.attributedTitle.string ?? "")' | warnings \(s?.warnings?.map { $0.chip } ?? []) | standing \(s?.standing.map { "\($0.name) \(Int($0.rank ?? 0))/\(Int($0.ranked ?? 0))" } ?? "none") | codex rows \(s?.sessions.filter { $0.agent == "codex" }.count ?? 0) | sysCpu \(main.model.sysCpu.map { pct1($0 * 100) } ?? "nil")"); fflush(stdout)
2969
+ settingsTest(prefix)
2970
+ }
2971
+ }
2972
+ }
2973
+ /** Open the settings page, check the window still fits, capture it, and with --selftest-write change each setting through the CLI. */
2974
+ func settingsTest(_ prefix: String) {
2975
+ let p = main.prefs
2976
+ func state() -> String {
2977
+ guard let s = p.s else { return "settings not loaded" }
2978
+ let cw = s.compactWindow.map { "\($0.value.map { String(Int($0)) } ?? "unset") warn=\($0.warn) 1m=\($0.is1m)" } ?? "none"
2979
+ return "routing=\(s.routing.enabled ? "on" : "off") relaxed=\(s.routing.relaxed) compact=\(s.statusline.compact) labels=\(s.statusline.labels) timer=\(s.statusline.timer) lang=\(s.language) joined=\(s.team.joined) compactWindow=\(cw) samples=\(p.samples.count)"
2980
+ }
2981
+ main.nav.page = .settings
2982
+ DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
2983
+ print("SETTINGS \(state())"); fitCheck("SETTINGS")
2984
+ render(SettingsView(prefs: p, still: true), "\(prefix)-settings-dark.png")
2985
+ liveShot(main.hosting, "\(prefix)-settings-live.png")
2986
+ fflush(stdout)
2987
+ guard selftestWrite else { rulesTest(prefix); return }
2988
+ guard SANDBOX else { print("WRITE refused: not a sandbox"); fflush(stdout); rulesTest(prefix); return }
2989
+ let steps: [Step] = [
2990
+ ("routing off", { p.setRouting(false, then: $0) }, { p.s?.routing.enabled == false }),
2991
+ ("compact=2", { p.setLevel(2, then: $0) }, { p.s?.statusline.compact == 2 }),
2992
+ ("compact=3", { p.setLevel(3, then: $0) }, { p.s?.statusline.compact == 3 }),
2993
+ ("compact=1", { p.setLevel(1, then: $0) }, { p.s?.statusline.compact == 1 }),
2994
+ ("labels text", { p.setLabels("text", then: $0) }, { p.s?.statusline.labels == "text" }),
2995
+ ("labels narrow", { p.setLabels("narrow", then: $0) }, { p.s?.statusline.labels == "narrow" }),
2996
+ ("timer off", { p.setTimer(false, then: $0) }, { p.s?.statusline.timer == false }),
2997
+ ("lang en", { p.setLanguage("en", then: $0) }, { p.s?.language == "en" }),
2998
+ ("routing on", { p.setRouting(true, then: $0) }, { p.s?.routing.enabled == true }),
2999
+ ("relax on", { p.setRelax(true, then: $0) }, { p.s?.routing.relaxed == true && p.s?.routing.relaxUntil != nil }),
3000
+ ("relax off", { p.setRelax(false, then: $0) }, { p.s?.routing.relaxed == false }),
3001
+ ("compact window 500k", { p.setCompact(500_000, then: $0) }, { p.s?.compactWindow?.value == 500_000 }),
3002
+ ("compact window 600k", { p.setCompact(600_000, then: $0) }, { p.s?.compactWindow?.value == 600_000 }),
3003
+ ("compact warn off", { p.setCompactWarn(false, then: $0) }, { p.s?.compactWindow?.warn == false }),
3004
+ ("compact warn on", { p.setCompactWarn(true, then: $0) }, { p.s?.compactWindow?.warn == true }),
3005
+ ]
3006
+ runSteps("WRITE", steps, note: { p.note }) { print("SETTINGS \(state())"); fflush(stdout); rulesTest(prefix) }
3007
+ }
3008
+ }
3009
+ /** Open the rules page, capture it, and in a sandbox add and remove a rule in each source that has commands for it. */
3010
+ func rulesTest(_ prefix: String) {
3011
+ let b = main.book
3012
+ func state() -> String {
3013
+ guard let d = b.data else { return "not loaded: \(b.note)" }
3014
+ return "global \(d.global.rules.count) (\(d.global.tokens) tokens, budget \(d.budgetTokens)) | projects \(d.projects.map { String($0.rules.count) }.joined(separator: ",")) | preset \(d.preset.rules.count) pending \(d.preset.pending.count) | model \(d.model.rules.count) enabled \(d.model.enabled) | team \(d.team.rules.count) joined \(d.team.joined)"
3015
+ }
3016
+ main.nav.page = .rules
3017
+ DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
3018
+ print("RULES \(state())")
3019
+ b.open = ["global", "preset"]
3020
+ if let first = b.data?.global.rules.first { b.expanded = "global#\(first.index)" }
3021
+ RELAYOUT()
3022
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
3023
+ fitCheck("RULES")
3024
+ render(RulesView(book: b, still: true), "\(prefix)-rules-dark.png")
3025
+ liveShot(main.hosting, "\(prefix)-rules-live.png")
3026
+ fflush(stdout)
3027
+ guard selftestWrite, SANDBOX else { warningTest(prefix); return }
3028
+ let text = "셀프테스트 조건이면 셀프테스트 행동을 합니다"
3029
+ let count = { b.data?.global.rules.count ?? -1 }
3030
+ let n0 = count(), m0 = b.data?.model.rules.count ?? 0
3031
+ let pending = b.data?.preset.pending.first?.id ?? ""
3032
+ var steps: [Step] = [
3033
+ ("add global rule", { b.addRatchet(scope: "global", root: nil, key: "global", text: text, then: $0) }, { count() == n0 + 1 && (b.data?.global.rules.last?.text.contains(text) ?? false) }),
3034
+ ("refuse a removal whose text no longer matches", { b.removeRatchet(scope: "global", root: nil, index: n0 + 1, text: "다른 문장", then: $0) }, { count() == n0 + 1 && b.failed }),
3035
+ ("remove global rule", { b.removeRatchet(scope: "global", root: nil, index: n0 + 1, text: b.data?.global.rules.last?.text ?? "", then: $0) }, { count() == n0 && !b.failed }),
3036
+ ]
3037
+ if let pr = b.data?.projects.first {
3038
+ let key = "project:\(pr.root)"
3039
+ let pc = { b.data?.projects.first { $0.root == pr.root }?.rules.count ?? -1 }
3040
+ let p0 = pc()
3041
+ steps.append(("add project rule", { b.addRatchet(scope: "project", root: pr.root, key: key, text: text, then: $0) }, { pc() == p0 + 1 && count() == n0 }))
3042
+ steps.append(("remove project rule", { b.removeRatchet(scope: "project", root: pr.root, index: p0 + 1, text: b.data?.projects.first { $0.root == pr.root }?.rules.last?.text ?? "", then: $0) }, { pc() == p0 && !b.failed }))
3043
+ }
3044
+ if !pending.isEmpty {
3045
+ steps.append(("accept preset", { b.acceptPreset(pending, then: $0) }, { b.data?.preset.rules.contains { $0.id == pending } == true }))
3046
+ steps.append(("drop preset", { b.skipPreset(pending, then: $0) }, { b.data?.preset.rules.contains { $0.id == pending } == false && b.data?.preset.pending.contains { $0.id == pending } == false }))
3047
+ }
3048
+ if m0 > 0, let r = b.data?.model.rules.first {
3049
+ steps.append(("remove model rule", { b.removeModel(index: r.index, text: r.text, then: $0) }, { b.data?.model.rules.count == m0 - 1 && !b.failed }))
3050
+ }
3051
+ runSteps("RULE", steps, note: { b.note }) { print("RULES \(state())"); fflush(stdout); warningTest(prefix) }
3052
+ }
3053
+ }
3054
+ }
3055
+ /** Open the detail page of the first active warning and capture it. */
3056
+ func warningTest(_ prefix: String) {
3057
+ guard let w = main.model.snap?.warnings?.first else { print("WARNING none active"); fflush(stdout); sessionTest(prefix); return }
3058
+ main.nav.page = .warning(w.chip)
3059
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
3060
+ print("WARNING '\(w.chip)' level \(w.level) advice \(w.advice?.count ?? 0) actions \(w.advice?.first?.actions?.count ?? 0) detail \(w.detail != nil) | all \(main.model.snap?.warnings?.map { $0.chip } ?? [])")
3061
+ fitCheck("WARNING")
3062
+ render(WarningView(w: w, now: main.model.snap?.at ?? 0, still: true), "\(prefix)-warning-dark.png")
3063
+ liveShot(main.hosting, "\(prefix)-warning-live.png")
3064
+ fflush(stdout); sessionTest(prefix)
3065
+ }
3066
+ }
3067
+ /** Open the first session's page, then the dashboard window, and capture both. Counts only: the texts are the user's own prompts. */
3068
+ func sessionTest(_ prefix: String) {
3069
+ let m = main.model
3070
+ func shape(_ s: Session?) -> String {
3071
+ guard let s = s else { return "none" }
3072
+ guard let d = s.detail else { return "effort \(s.effort ?? "nil") | no detail (detailOff \(m.detailOff))" }
3073
+ return "effort \(s.effort ?? "nil") | prompt \(d.prompt != nil) reply \(d.reply != nil) recent \(d.recent?.count ?? 0) pending \(d.recent?.filter { $0.pending == true }.count ?? 0) procs \(d.procs?.count ?? 0)"
3074
+ }
3075
+ guard let first = m.snap?.sessions.first else { print("SESSION none running"); fflush(stdout); dashboardTest(prefix); return }
3076
+ main.nav.page = .session(first.pid)
3077
+ DispatchQueue.main.asyncAfter(deadline: .now() + 3.5) {
3078
+ let s = m.snap?.sessions.first { $0.pid == first.pid }
3079
+ print("SESSION \(shape(s)) | asked for detail \(m.wantDetail)")
3080
+ fitCheck("SESSION")
3081
+ render(SessionView(s: s, cpu: s.map { m.cpuOf($0) } ?? 0, mem: s.map { m.memOf($0) } ?? 0, now: m.snap?.at ?? 0, off: m.detailOff, still: true), "\(prefix)-session-dark.png")
3082
+ liveShot(main.hosting, "\(prefix)-session-live.png")
3083
+ fflush(stdout); dashboardTest(prefix)
3084
+ }
3085
+ }
3086
+ func dashboardTest(_ prefix: String) {
3087
+ main.showDashboard()
3088
+ DispatchQueue.main.asyncAfter(deadline: .now() + 4.0) {
3089
+ let m = main.model
3090
+ print("DASHBOARD window \(main.dash.map { "\(Int($0.frame.width))x\(Int($0.frame.height)) visible \($0.isVisible)" } ?? "none") | panel closed \(!main.isOpen) | asked for detail \(m.wantDetail) | sessions \(m.snap?.sessions.count ?? 0) with detail \(m.snap?.sessions.filter { $0.detail != nil }.count ?? 0)")
3091
+ print("DOCK regular app while the dashboard is open: \(NSApp.activationPolicy() == .regular) | icon set \(NSApp.applicationIconImage != nil) | menu \(NSApp.mainMenu != nil) | reopen handler \(NSApp.delegate is App)")
3092
+ print("STARTED BY " + (m.parentSession.isEmpty ? "none" : m.parentSession.map { c, up in "\(m.snap?.sessions.first { $0.pid == c }?.name ?? "\(c)") <- \(m.snap?.sessions.first { $0.pid == up }?.name ?? "\(up)")" }.sorted().joined(separator: " | ")))
3093
+ print("PHASE " + (m.snap?.sessions ?? []).map { s in "\(s.name ?? s.agent) \(m.phase(s)) [" + m.working(s, max: 3).map { "\($0.name) cpu \(pct1($0.w.cpu * 100)) gpu \(pct1($0.w.gpu * 100)) \(memText($0.w.mem))" }.joined(separator: "; ") + "]" }.joined(separator: " | "))
3094
+ render(DashboardView(model: m, still: true).frame(width: 1480), "\(prefix)-dashboard-dark.png")
3095
+ render(DashboardView(model: m, still: true).frame(width: 1480), "\(prefix)-dashboard-light.png", dark: false)
3096
+ if let first = m.snap?.sessions.first { render(DashboardView(model: m, still: true, lit: first.pid).frame(width: 1480), "\(prefix)-dashboard-hover-dark.png") }
3097
+ print("GPU device \(m.gpu.map { pct1($0 * 100) } ?? "-") | processes on it \(m.gpuUse.count) | sessions on it \(m.gpuBySession.count) | top " + m.gpuUse.prefix(4).map { "\($0.name) \(pct1($0.share * 100)) \($0.session.map { "session \($0)" } ?? "no session")" }.joined(separator: "; "))
3098
+ let tree = m.usage.values.reduce(Load()) { var l = $0; l.cpu += $1.tree.cpu; l.mem += $1.tree.mem; l.n += $1.tree.n; return l }
3099
+ let det = m.usage.values.reduce(Load()) { var l = $0; l.cpu += $1.detached.cpu; l.mem += $1.detached.mem; l.n += $1.detached.n; return l }
3100
+ let oth = m.others.reduce(Load()) { var l = $0; l.cpu += $1.cpu; l.mem += $1.mem; l.n += $1.n; return l }
3101
+ print("CENSUS machine CPU \(pct1((m.sysCpu ?? 0) * 100)) mem \(memText(m.sysMemMb)) | session trees \(pct1(tree.cpu * 100)) \(memText(tree.mem)) (\(tree.n)) | detached \(pct1(det.cpu * 100)) \(memText(det.mem)) (\(det.n)) | left by ended sessions \(pct1(m.leftover.cpu * 100)) \(memText(m.leftover.mem)) (\(m.leftover.n)) | other programs \(pct1(oth.cpu * 100)) \(memText(oth.mem)) (\(oth.n))")
3102
+ print("CENSUS CLI figures for the same sessions: CPU \(pct1((m.snap?.sessions ?? []).reduce(0) { $0 + Model.raw($1) })) mem \(memText((m.snap?.sessions ?? []).reduce(0) { $0 + ($1.rssMb ?? 0) })) | leftover kinds \(m.leftoverItems.count) | other apps \(m.others.count)")
3103
+ print("CPUOF " + (m.snap?.sessions ?? []).map { "\($0.name ?? $0.agent) \(pct1(m.cpuOf($0))) \(memText(m.memOf($0)))" }.joined(separator: " | "))
3104
+ print("JUMP " + (m.snap?.sessions ?? []).map { "\($0.name ?? $0.agent) opens \(owningApp($0.pid)?.localizedName ?? "nothing found")\(exactTab($0) == nil ? ", app only" : ", its own tab")" }.joined(separator: " | ") + " | responsible-process lookup \(RESPONSIBLE == nil ? "missing" : "present")")
3105
+ print("LEFT " + m.leftoverItems.prefix(6).map { "\($0.name) x\($0.n) \(memText($0.mem))" }.joined(separator: " | "))
3106
+ print("OTHER " + m.others.sorted { $0.cpu > $1.cpu }.prefix(5).map { "\($0.name) \(pct1($0.cpu * 100)) \(memText($0.mem))" }.joined(separator: " | "))
3107
+ print("GROUPS " + groupSessions(m.snap?.sessions ?? [], parents: m.parentSession).map { "\($0.name) x\($0.sessions.count)" }.joined(separator: " | ") + " | started by another session \(m.parentSession.count)")
3108
+ if let first = m.snap?.sessions.first { render(DashboardView(model: m, still: true, preselect: first.pid).frame(width: 1480), "\(prefix)-dashboard-open-dark.png") }
3109
+ render(DashboardView(model: m, still: true, cleaning: true).frame(width: 1480), "\(prefix)-dashboard-clean-dark.png")
3110
+ print("DASHBOARD history samples \(m.samples.count) per-session \(m.hist.values.map { $0.count }.sorted())")
3111
+ if let v = main.dash?.contentView { liveShot(v, "\(prefix)-dashboard-live.png") }
3112
+ print("LEFTOVER lines \(m.leftoverItems.count) | never cleaned (apps, virtual machines, databases): \(m.leftoverItems.filter { m.leftoverShared.contains($0.id) }.map { $0.name }.joined(separator: ", "))")
3113
+ if let target = selftestClean {
3114
+ let hit = m.leftoverItems.first { $0.name == target }
3115
+ print("CLEAN target '\(target)': \(hit.map { "\($0.n) process(es)" } ?? "not listed") | protected \(m.leftoverShared.contains(target))")
3116
+ print("CLEAN signals sent: \(m.stopLeftovers([target]))")
3117
+ }
3118
+ main.dash?.close()
3119
+ DispatchQueue.main.asyncAfter(deadline: .now() + (selftestClean == nil ? 0.6 : 6.0)) {
3120
+ if let target = selftestClean { print("CLEAN afterwards: '\(target)' \(m.leftoverItems.contains { $0.name == target } ? "still listed" : "gone") | leftover lines \(m.leftoverItems.count)") }
3121
+ print("DASHBOARD closed, asked for detail \(m.wantDetail) | back to a menu bar app \(NSApp.activationPolicy() == .accessory)"); fflush(stdout); NSApp.terminate(nil)
3122
+ }
3123
+ }
3124
+ }
3125
+ if ttl > 0 { DispatchQueue.main.asyncAfter(deadline: .now() + ttl) { NSApp.terminate(nil) } }
3126
+ // One copy per user. sprag may try to start the app from several sessions at once; the lock decides, and the pid file tells
3127
+ // `sprag bar off` and the next upgrade which process to stop.
3128
+ var lockFd: Int32 = -1
3129
+ if let dir = dataDir, selftest == nil {
3130
+ try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
3131
+ lockFd = open(dir + "/bar-app.lock", O_CREAT | O_RDWR, 0o600)
3132
+ // After an upgrade sprag stops the old copy and starts this one straight away, so the lock may be held for a moment more.
3133
+ var mine = false
3134
+ if lockFd >= 0 { for _ in 0..<12 { if flock(lockFd, LOCK_EX | LOCK_NB) == 0 { mine = true; break }; usleep(250_000) } }
3135
+ if !mine { exit(0) }
3136
+ let info: [String: Any] = ["pid": Int(getpid()), "version": versionTag, "startedAt": Int(Date().timeIntervalSince1970 * 1000)]
3137
+ if let d = try? JSONSerialization.data(withJSONObject: info) { FileManager.default.createFile(atPath: dir + "/bar-app.json", contents: d, attributes: [.posixPermissions: 0o600]) }
3138
+ }
3139
+ ProcessInfo.processInfo.processName = "Sprag Bar"
3140
+ print("READY"); fflush(stdout)
3141
+ app.run()