sprag-cli 3.136.1 → 3.138.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.
- package/mac/SpragBar.swift +130 -16
- package/package.json +1 -1
- package/src/agent-activity.js +44 -2
- package/src/agent-detail.js +41 -0
- package/src/bar-app.js +129 -4
- package/src/commands/bar.js +11 -2
package/mac/SpragBar.swift
CHANGED
|
@@ -36,7 +36,12 @@ struct Session: Decodable, Identifiable {
|
|
|
36
36
|
let cpu: Double?; let rssMb: Double?; let procs: Int?
|
|
37
37
|
let cpuPct: Double?; let model: String?; let modelName: String?; let effort: String?; let context: Ctx?; let usage: SUsage?
|
|
38
38
|
let compactions: Int? // times the conversation was compacted; optional so a snapshot from an older sprag still decodes
|
|
39
|
+
let title: String? // what the session is about (rename, last prompt, topic); optional so a snapshot from an older sprag still decodes
|
|
39
40
|
var id: Int { pid }
|
|
41
|
+
/** What a row calls the session: its title, else Claude Code's own name, which is often the folder plus a number. */
|
|
42
|
+
var label: String { if let t = title, !t.isEmpty { return t }; return name ?? agent }
|
|
43
|
+
/** The tooltip form: the title and the name under it, or one of them when they are the same. */
|
|
44
|
+
var fullName: String { let n = name ?? agent; return label == n ? n : label + "\n" + n }
|
|
40
45
|
}
|
|
41
46
|
struct Totals: Decodable { let sessions: Int; let busy: Int; let subagents: Int; let cpu: Double?; let rssMb: Double?; let procs: Int?; let costUsd: Double? }
|
|
42
47
|
struct Animal: Decodable { let grade: String; let emoji: String }
|
|
@@ -263,14 +268,103 @@ func exactTab(_ s: Session) -> (tool: String, args: [String])? {
|
|
|
263
268
|
let dir = env["ORCA_CLI_BIN_DIR"], dir.hasSuffix(".app/Contents/Resources/bin"), FileManager.default.isExecutableFile(atPath: dir + "/orca") else { return nil }
|
|
264
269
|
return (dir + "/orca", ["terminal", "switch", "--terminal", handle])
|
|
265
270
|
}
|
|
266
|
-
/**
|
|
271
|
+
/** Whether an app has a normal window on the current screen. Minimized and hidden windows are not on screen. Owner and layer are readable without the screen recording permission. */
|
|
272
|
+
func hasWindowOnScreen(_ pid: pid_t) -> Bool {
|
|
273
|
+
guard let list = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] else { return true }
|
|
274
|
+
return list.contains { ($0[kCGWindowOwnerPID as String] as? Int) == Int(pid) && ($0[kCGWindowLayer as String] as? Int) == 0 }
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Go to a session: show its tab where the terminal allows it, then bring the terminal app to the front.
|
|
278
|
+
* activate() only raises windows that are already open, so a terminal whose windows all sit in the Dock came forward with
|
|
279
|
+
* nothing to show. Opening the running app again sends it the same reopen event a Dock click does, which restores a
|
|
280
|
+
* minimized window (and unhides a hidden app) without asking for any permission. It is sent only when nothing of the
|
|
281
|
+
* app is on screen, because some apps open a new window on every reopen.
|
|
282
|
+
*/
|
|
267
283
|
func jump(to s: Session) {
|
|
268
284
|
if let tab = exactTab(s) {
|
|
269
285
|
let p = Process(); p.executableURL = URL(fileURLWithPath: tab.tool); p.arguments = tab.args
|
|
270
286
|
p.standardOutput = FileHandle.nullDevice; p.standardError = FileHandle.nullDevice
|
|
271
287
|
try? p.run()
|
|
272
288
|
}
|
|
273
|
-
owningApp(s.pid)
|
|
289
|
+
guard let app = owningApp(s.pid) else { return }
|
|
290
|
+
if let script = TAB_SCRIPTS[app.bundleIdentifier ?? ""], let tty = ttyPath(Int32(s.pid)) {
|
|
291
|
+
selectTab(script, tty: tty) { found in if !found { bringForward(app) } }
|
|
292
|
+
return
|
|
293
|
+
}
|
|
294
|
+
bringForward(app)
|
|
295
|
+
}
|
|
296
|
+
/** The terminal device a process writes to (`/dev/ttys003`), or nil for one without a terminal. */
|
|
297
|
+
func ttyPath(_ pid: Int32) -> String? {
|
|
298
|
+
var info = proc_bsdinfo()
|
|
299
|
+
let size = Int32(MemoryLayout<proc_bsdinfo>.size)
|
|
300
|
+
guard proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, size) == size, info.e_tdev != UInt32.max, let name = devname(dev_t(bitPattern: info.e_tdev), S_IFCHR) else { return nil }
|
|
301
|
+
return "/dev/" + String(cString: name)
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Terminals that name each tab's tty to AppleScript, with a script that selects the tab on the tty given as its argument,
|
|
305
|
+
* restores and raises its window and prints true, or prints false when no tab has that tty. Running one asks once for the
|
|
306
|
+
* Automation permission; refused, the script fails and the jump falls back to bringing the app forward.
|
|
307
|
+
*/
|
|
308
|
+
let TAB_SCRIPTS: [String: String] = [
|
|
309
|
+
"com.apple.Terminal": """
|
|
310
|
+
on run argv
|
|
311
|
+
tell application id "com.apple.Terminal"
|
|
312
|
+
repeat with w in windows
|
|
313
|
+
repeat with t in tabs of w
|
|
314
|
+
if tty of t is (item 1 of argv) then
|
|
315
|
+
if miniaturized of w then set miniaturized of w to false
|
|
316
|
+
set selected of t to true
|
|
317
|
+
set index of w to 1
|
|
318
|
+
activate
|
|
319
|
+
return true
|
|
320
|
+
end if
|
|
321
|
+
end repeat
|
|
322
|
+
end repeat
|
|
323
|
+
end tell
|
|
324
|
+
return false
|
|
325
|
+
end run
|
|
326
|
+
""",
|
|
327
|
+
"com.googlecode.iterm2": """
|
|
328
|
+
on run argv
|
|
329
|
+
tell application id "com.googlecode.iterm2"
|
|
330
|
+
repeat with w in windows
|
|
331
|
+
repeat with t in tabs of w
|
|
332
|
+
repeat with s in sessions of t
|
|
333
|
+
if tty of s is (item 1 of argv) then
|
|
334
|
+
if miniaturized of w then set miniaturized of w to false
|
|
335
|
+
select w
|
|
336
|
+
tell t to select
|
|
337
|
+
tell s to select
|
|
338
|
+
activate
|
|
339
|
+
return true
|
|
340
|
+
end if
|
|
341
|
+
end repeat
|
|
342
|
+
end repeat
|
|
343
|
+
end repeat
|
|
344
|
+
end tell
|
|
345
|
+
return false
|
|
346
|
+
end run
|
|
347
|
+
""",
|
|
348
|
+
]
|
|
349
|
+
/** Run a tab script off the main thread; `done` gets whether the tab was found, on the main thread. A permission prompt left unanswered gives up after a minute. */
|
|
350
|
+
func selectTab(_ script: String, tty: String, done: @escaping (Bool) -> Void) {
|
|
351
|
+
let p = Process(), out = Pipe()
|
|
352
|
+
p.executableURL = URL(fileURLWithPath: "/usr/bin/osascript"); p.arguments = ["-e", script, tty]
|
|
353
|
+
p.standardOutput = out; p.standardError = FileHandle.nullDevice
|
|
354
|
+
p.terminationHandler = { _ in
|
|
355
|
+
let text = String(decoding: out.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
|
|
356
|
+
DispatchQueue.main.async { done(text == "true") }
|
|
357
|
+
}
|
|
358
|
+
do { try p.run() } catch { done(false); return }
|
|
359
|
+
DispatchQueue.main.asyncAfter(deadline: .now() + 60) { if p.isRunning { p.terminate() } }
|
|
360
|
+
}
|
|
361
|
+
/** Bring a terminal app forward, restoring a minimized window when nothing of it is on screen (see jump). */
|
|
362
|
+
func bringForward(_ app: NSRunningApplication) {
|
|
363
|
+
app.activate(options: [.activateAllWindows])
|
|
364
|
+
if let url = app.bundleURL, app.isHidden || !hasWindowOnScreen(app.processIdentifier) {
|
|
365
|
+
let cfg = NSWorkspace.OpenConfiguration(); cfg.activates = true
|
|
366
|
+
NSWorkspace.shared.openApplication(at: url, configuration: cfg)
|
|
367
|
+
}
|
|
274
368
|
}
|
|
275
369
|
/** The folder a Claude session worked in, read from its transcript (`<config>/projects/<folder>/<id>.jsonl`, whose lines carry `cwd`). */
|
|
276
370
|
func sessionCwd(_ sid: String) -> String? {
|
|
@@ -667,7 +761,7 @@ final class Model: ObservableObject {
|
|
|
667
761
|
for s in sessions {
|
|
668
762
|
let mine = gpuUse.filter { $0.session == s.pid }
|
|
669
763
|
guard !mine.isEmpty else { continue }
|
|
670
|
-
out.append(GpuLine(id: "s\(s.pid)", label: s.
|
|
764
|
+
out.append(GpuLine(id: "s\(s.pid)", label: s.label, note: mine.prefix(2).map { $0.name }.joined(separator: ", "), share: min(1, mine.reduce(0) { $0 + $1.share }), agent: s.agent, pid: s.pid))
|
|
671
765
|
}
|
|
672
766
|
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)) }
|
|
673
767
|
return Array(out.sorted { $0.share > $1.share }.prefix(n))
|
|
@@ -1670,7 +1764,7 @@ struct SessionRow: View {
|
|
|
1670
1764
|
VStack(alignment: .leading, spacing: 4) {
|
|
1671
1765
|
HStack(alignment: .center, spacing: 6) {
|
|
1672
1766
|
Badge(agent: s.agent)
|
|
1673
|
-
Text(s.
|
|
1767
|
+
Text(s.label).font(.system(size: 13, weight: .semibold)).lineLimit(2).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true)
|
|
1674
1768
|
Spacer(minLength: 6)
|
|
1675
1769
|
if let c = s.usage?.costUsd { Text(String(format: "$%.2f", c)).font(.system(size: 12.5, weight: .medium)).monospacedDigit().fixedSize().help("이 세션의 비용, 정가 환산") }
|
|
1676
1770
|
}
|
|
@@ -2265,7 +2359,7 @@ struct SessionView: View {
|
|
|
2265
2359
|
if let s = s {
|
|
2266
2360
|
FitScroll(limit: limit - 70, still: still) {
|
|
2267
2361
|
VStack(alignment: .leading, spacing: 6) {
|
|
2268
|
-
HStack(spacing: 7) { Badge(agent: s.agent); Text(s.
|
|
2362
|
+
HStack(spacing: 7) { Badge(agent: s.agent); Text(s.label).font(.system(size: 15, weight: .semibold)).lineLimit(1).truncationMode(.middle) }
|
|
2269
2363
|
if let c = s.cwd { Text(c).font(.system(size: 10.5, design: .monospaced)).foregroundColor(.secondary).lineLimit(1).truncationMode(.head).textSelection(.enabled) }
|
|
2270
2364
|
HStack(spacing: 6) { Circle().fill(stateColor(s)).frame(width: 7, height: 7); Text(activity(s, now: now)).font(.system(size: 12)) }
|
|
2271
2365
|
Divider().padding(.vertical, 2)
|
|
@@ -2460,7 +2554,7 @@ struct SubTile: View {
|
|
|
2460
2554
|
HStack(spacing: 7) {
|
|
2461
2555
|
Image(systemName: "arrow.turn.down.right").font(.system(size: 10, weight: .semibold)).foregroundColor(pal.text2)
|
|
2462
2556
|
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) }
|
|
2463
|
-
Text(s.
|
|
2557
|
+
Text(s.label).font(.system(size: 12, weight: .medium)).foregroundColor(pal.text).lineLimit(1).truncationMode(.tail)
|
|
2464
2558
|
Spacer(minLength: 4)
|
|
2465
2559
|
Text("\(mark.label) \(sinceText(s.stateSince, now: now))").font(.system(size: 10.5)).foregroundColor(pal.text2).lineLimit(1).fixedSize()
|
|
2466
2560
|
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("컨텍스트") }
|
|
@@ -2503,7 +2597,7 @@ struct SessionTile: View {
|
|
|
2503
2597
|
HStack(spacing: 7) {
|
|
2504
2598
|
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()
|
|
2505
2599
|
if let up = parentName { Image(systemName: "arrow.turn.down.right").font(.system(size: 10.5, weight: .semibold)).foregroundColor(pal.text2).help("\(up) 세션이 띄운 세션") }
|
|
2506
|
-
Text(s.
|
|
2600
|
+
Text(s.label).font(.system(size: 13.5, weight: .semibold)).foregroundColor(pal.text).lineLimit(1).truncationMode(.middle).help(s.fullName)
|
|
2507
2601
|
Spacer(minLength: 6)
|
|
2508
2602
|
}
|
|
2509
2603
|
HStack(spacing: 5) {
|
|
@@ -2838,7 +2932,7 @@ struct DashboardView: View {
|
|
|
2838
2932
|
func inspector(_ s: Session, _ snap: Snapshot, _ pal: Pal) -> some View {
|
|
2839
2933
|
let body = VStack(alignment: .leading, spacing: 6) {
|
|
2840
2934
|
HStack(spacing: 7) {
|
|
2841
|
-
Text(s.
|
|
2935
|
+
Text(s.label).font(.system(size: 15, weight: .semibold)).lineLimit(1).truncationMode(.middle)
|
|
2842
2936
|
Spacer(minLength: 6)
|
|
2843
2937
|
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()) }
|
|
2844
2938
|
.buttonStyle(HoverStyle(radius: 6)).help("이 세션이 열려 있는 터미널 앱을 앞으로 가져옵니다")
|
|
@@ -2954,7 +3048,7 @@ struct DashboardView: View {
|
|
|
2954
3048
|
let sm = model.samples, ses = snap.sessions
|
|
2955
3049
|
let cpu = cpuSplit(snap, pal), mem = memSplit(snap, pal)
|
|
2956
3050
|
func tops(_ pick: (AppLoad) -> Double, _ of: (Session) -> Double, _ part: (Work) -> Double, _ show: (Double) -> String) -> [Top] {
|
|
2957
|
-
var t = ses.map { s in Top(id: "s\(s.pid)", name: s.
|
|
3051
|
+
var t = ses.map { s in Top(id: "s\(s.pid)", name: s.label, value: of(s), color: pal.agent(s.agent), pid: s.pid, program: heaviest(s, total: of(s), part, show), doing: doingNow(s)) }
|
|
2958
3052
|
t += model.leftoverItems.map { Top(id: "l\($0.id)", name: $0.name, value: pick($0), color: pal.left, origin: leftOrigin($0.id)) }
|
|
2959
3053
|
t += model.others.map { Top(id: "o\($0.id)", name: $0.name, value: pick($0), color: pal.neutral, origin: "세션과 무관한 프로그램", originSymbol: "macwindow") }
|
|
2960
3054
|
return Array(t.sorted { $0.value > $1.value }.prefix(5))
|
|
@@ -3063,7 +3157,7 @@ struct DashboardView: View {
|
|
|
3063
3157
|
let gap: CGFloat = 12, minCell: CGFloat = 318
|
|
3064
3158
|
let cols = max(1, Int((width + gap) / (minCell + gap)))
|
|
3065
3159
|
let cell = (width - CGFloat(cols - 1) * gap) / CGFloat(cols)
|
|
3066
|
-
let names = Dictionary(snap.sessions.map { ($0.pid, $0.
|
|
3160
|
+
let names = Dictionary(snap.sessions.map { ($0.pid, $0.label) }, uniquingKeysWith: { a, _ in a })
|
|
3067
3161
|
// A group is as wide as its main sessions need, and at least wide enough to lay its started sessions side by side.
|
|
3068
3162
|
let isSub: (Session, SessionGroup) -> Bool = { s, g in model.parentSession[s.pid].map { up in g.sessions.contains { $0.pid == up } } ?? false }
|
|
3069
3163
|
let spanOf: (SessionGroup) -> Int = { g in
|
|
@@ -3141,7 +3235,7 @@ struct DashboardView: View {
|
|
|
3141
3235
|
let ph = model.phase(s), tint = pal.state(ph), mark = stateMark(s)
|
|
3142
3236
|
let byLoad = ph == .active && s.state != "busy" && s.state != "shell" && s.subagents == 0
|
|
3143
3237
|
let pending = (s.detail?.recent ?? []).last { $0.pending == true }
|
|
3144
|
-
let name = Text(s.
|
|
3238
|
+
let name = Text(s.label).font(.system(size: 12.5, weight: .semibold)).foregroundColor(pal.text)
|
|
3145
3239
|
let row = VStack(alignment: .leading, spacing: 6) {
|
|
3146
3240
|
HStack(alignment: dense ? .top : .center, spacing: 6) {
|
|
3147
3241
|
if ph == .active { LiveDot(color: tint) } else { Image(systemName: mark.symbol).font(.system(size: 11)).foregroundColor(tint).frame(width: 12) }
|
|
@@ -3197,7 +3291,7 @@ struct DashboardView: View {
|
|
|
3197
3291
|
}
|
|
3198
3292
|
/** A session resting at its prompt: one quiet line. */
|
|
3199
3293
|
func idleRow(_ s: Session, _ snap: Snapshot, _ pal: Pal, dense: Bool, pick: @escaping (Session) -> Void) -> some View {
|
|
3200
|
-
let name = Text(s.
|
|
3294
|
+
let name = Text(s.label).font(.system(size: 12)).foregroundColor(pal.text2)
|
|
3201
3295
|
return Pressable(radius: 6, action: { pick(s) }) {
|
|
3202
3296
|
HStack(alignment: dense ? .top : .center, spacing: 6) {
|
|
3203
3297
|
Image(systemName: "pause.circle").font(.system(size: 11)).foregroundColor(pal.text2).frame(width: 12)
|
|
@@ -3435,6 +3529,8 @@ struct PanelView: View {
|
|
|
3435
3529
|
case .warning(let chip): WarningView(w: model.snap?.warnings?.first { $0.chip == chip }, now: model.snap?.at ?? 0, limit: maxHeight, back: { nav.page = .status })
|
|
3436
3530
|
}
|
|
3437
3531
|
}
|
|
3532
|
+
// A page that still comes out taller than the screen loses its bottom, never the header with the back and menu buttons.
|
|
3533
|
+
.frame(maxHeight: still ? nil : maxHeight, alignment: .top)
|
|
3438
3534
|
}
|
|
3439
3535
|
/** How many sessions, and how they stand: working, waiting for a go-ahead, waiting for input. Sessions another one started are counted apart. */
|
|
3440
3536
|
func sessionsTitle(_ snap: Snapshot) -> String {
|
|
@@ -3591,6 +3687,16 @@ final class FloatPanel: NSPanel { override var canBecomeKey: Bool { true } }
|
|
|
3591
3687
|
* species that runs in the menu bar. It is one still frame, redrawn only when the grade changes; a running Dock icon
|
|
3592
3688
|
* would spend CPU and pull the eye away from the dashboard. Drawn on the macOS icon grid (an 824 square in 1024).
|
|
3593
3689
|
*/
|
|
3690
|
+
/**
|
|
3691
|
+
* Give the launcher bundle the CLI writes (~/Applications/Sprag Bar.app, src/bar-app.js installLauncher) the same icon
|
|
3692
|
+
* as the Dock, so Spotlight and Launchpad show the runner instead of a blank app. Only a bundle whose Info.plist names
|
|
3693
|
+
* the launcher's id is touched; a missing one is left for the CLI to write.
|
|
3694
|
+
*/
|
|
3695
|
+
func paintLauncher(_ icon: NSImage) {
|
|
3696
|
+
let path = NSHomeDirectory() + "/Applications/Sprag Bar.app"
|
|
3697
|
+
guard let plist = try? String(contentsOfFile: path + "/Contents/Info.plist", encoding: .utf8), plist.contains("io.sprag.bar-launcher") else { return }
|
|
3698
|
+
NSWorkspace.shared.setIcon(icon, forFile: path, options: [])
|
|
3699
|
+
}
|
|
3594
3700
|
func dockIcon(_ grade: String?) -> NSImage {
|
|
3595
3701
|
let sp = runnerSpecies(grade)
|
|
3596
3702
|
// a frame that reads as that animal at rest in motion: wings up for fliers, mid-leap for the frog, a stride otherwise
|
|
@@ -3773,10 +3879,14 @@ final class App: NSObject {
|
|
|
3773
3879
|
b.toolTip = model.sysCpu != nil ? String(format: "기기 전체 CPU %.0f%%, 그중 AI 세션 %.0f%%. 세션 %d개 실행 중", (model.sysCpu ?? 0) * 100, model.share(nil), s.totals.sessions) : "작업 중인 세션 수 / 실행 중인 세션 수"
|
|
3774
3880
|
}
|
|
3775
3881
|
var dockGrade: String? = nil // the grade the Dock icon was drawn for
|
|
3882
|
+
var launcherGrade: String?? = .none // the grade the launcher's icon was drawn for, .none until the first snapshot
|
|
3776
3883
|
func animate() {
|
|
3777
3884
|
if NSApp.activationPolicy() == .regular, model.snap?.animal?.grade != dockGrade {
|
|
3778
3885
|
dockGrade = model.snap?.animal?.grade; NSApp.applicationIconImage = dockIcon(dockGrade)
|
|
3779
3886
|
}
|
|
3887
|
+
if selftest == nil, let snap = model.snap, launcherGrade != .some(snap.animal?.grade) {
|
|
3888
|
+
launcherGrade = .some(snap.animal?.grade); paintLauncher(dockIcon(snap.animal?.grade))
|
|
3889
|
+
}
|
|
3780
3890
|
// RunCat's rule, on the same thing RunCat measures: the whole machine. A runner that strolls while the machine is
|
|
3781
3891
|
// flat out, because the agent sessions' own share happens to be small, reads as wrong.
|
|
3782
3892
|
let load = min(100, max(0, (model.sysCpu ?? 0) * 100))
|
|
@@ -3794,6 +3904,10 @@ final class App: NSObject {
|
|
|
3794
3904
|
/** Size the window to its content and hang it under the menu bar item, wholly inside the screen. */
|
|
3795
3905
|
func place() {
|
|
3796
3906
|
guard let b = item.button, let bw = b.window, let screen = bw.screen ?? NSScreen.main else { return }
|
|
3907
|
+
// The content's own height limit follows the screen the menu bar item is on. Set once from the main screen at
|
|
3908
|
+
// launch, it let a page grow taller than a shorter screen's window, and the window cut the page off at the top.
|
|
3909
|
+
let cap = screen.visibleFrame.height - 12
|
|
3910
|
+
if abs(hosting.rootView.maxHeight - cap) > 0.5 { var v = hosting.rootView; v.maxHeight = cap; hosting.rootView = v }
|
|
3797
3911
|
hosting.layoutSubtreeIfNeeded()
|
|
3798
3912
|
let vis = screen.visibleFrame, fit = hosting.fittingSize
|
|
3799
3913
|
let w = fit.width, h = min(fit.height, vis.height - 12)
|
|
@@ -4080,8 +4194,8 @@ func dashboardTest(_ prefix: String) {
|
|
|
4080
4194
|
if let icon = NSApp.applicationIconImage { png(icon, "\(prefix)-dock.png") }
|
|
4081
4195
|
print("DOCK icon drawn for grade \(main.dockGrade ?? "none") (species \(runnerSpecies(main.dockGrade).id))")
|
|
4082
4196
|
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)")
|
|
4083
|
-
print("STARTED BY " + (m.parentSession.isEmpty ? "none" : m.parentSession.map { c, up in "\(m.snap?.sessions.first { $0.pid == c }?.
|
|
4084
|
-
print("PHASE " + (m.snap?.sessions ?? []).map { s in "\(s.
|
|
4197
|
+
print("STARTED BY " + (m.parentSession.isEmpty ? "none" : m.parentSession.map { c, up in "\(m.snap?.sessions.first { $0.pid == c }?.label ?? "\(c)") <- \(m.snap?.sessions.first { $0.pid == up }?.label ?? "\(up)")" }.sorted().joined(separator: " | ")))
|
|
4198
|
+
print("PHASE " + (m.snap?.sessions ?? []).map { s in "\(s.label) \(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: " | "))
|
|
4085
4199
|
render(DashboardView(model: m, still: true).frame(width: 1480), "\(prefix)-dashboard-dark.png")
|
|
4086
4200
|
render(DashboardView(model: m, still: true, width: 340).frame(width: 340), "\(prefix)-dashboard-mini-dark.png")
|
|
4087
4201
|
render(DashboardView(model: m, still: true, width: 780).frame(width: 780), "\(prefix)-dashboard-medium-dark.png")
|
|
@@ -4095,8 +4209,8 @@ func dashboardTest(_ prefix: String) {
|
|
|
4095
4209
|
let oth = m.others.reduce(Load()) { var l = $0; l.cpu += $1.cpu; l.mem += $1.mem; l.n += $1.n; return l }
|
|
4096
4210
|
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))")
|
|
4097
4211
|
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)")
|
|
4098
|
-
print("CPUOF " + (m.snap?.sessions ?? []).map { "\($0.
|
|
4099
|
-
print("JUMP " + (m.snap?.sessions ?? []).map { "\($0.
|
|
4212
|
+
print("CPUOF " + (m.snap?.sessions ?? []).map { "\($0.label) \(pct1(m.cpuOf($0))) \(memText(m.memOf($0)))" }.joined(separator: " | "))
|
|
4213
|
+
print("JUMP " + (m.snap?.sessions ?? []).map { "\($0.label) opens \(owningApp($0.pid)?.localizedName ?? "nothing found")\(exactTab($0) == nil ? ", app only" : ", its own tab")" }.joined(separator: " | ") + " | responsible-process lookup \(RESPONSIBLE == nil ? "missing" : "present")")
|
|
4100
4214
|
print("LEFT " + m.leftoverItems.prefix(6).map { "\($0.name) x\($0.n) \(memText($0.mem))" }.joined(separator: " | "))
|
|
4101
4215
|
print("OTHER " + m.others.sorted { $0.cpu > $1.cpu }.prefix(5).map { "\($0.name) \(pct1($0.cpu * 100)) \(memText($0.mem))" }.joined(separator: " | "))
|
|
4102
4216
|
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)")
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sprag-cli",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.138.0",
|
|
4
4
|
"description": "The delegation layer for Claude Code and Codex: each task goes to the model and effort that fits it, down to cheaper models for lookups and up to higher effort when a cheaper run would miss, backed by public replay cases, with a live statusline and team rules for Pro and Enterprise.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/src/agent-activity.js
CHANGED
|
@@ -30,6 +30,11 @@
|
|
|
30
30
|
* - Model, context window use, tokens, cost and the account limits come from
|
|
31
31
|
* agent-usage.js: the transcript tail, the statusline's caches in the user
|
|
32
32
|
* data folder, and the Codex rollout files.
|
|
33
|
+
* - A Claude row's `title` is what tells sessions apart on screen, where `name`
|
|
34
|
+
* is often the folder plus a number: a name given with /rename, else the last
|
|
35
|
+
* prompt or Claude Code's topic title from the transcript tail (agent-detail.js
|
|
36
|
+
* sessionTitleHints). null when there is none; Codex rows are always null.
|
|
37
|
+
* Rows are still sorted by `name`, so a new prompt does not reorder them.
|
|
33
38
|
* - A Claude row's effort level is the one the statusline recorded in the user
|
|
34
39
|
* data folder (session-effort.js); Codex rows read theirs from the rollout.
|
|
35
40
|
* - With `detail`, each row also carries the session's latest typed request, its
|
|
@@ -58,7 +63,7 @@ import { loadCache } from './session-cache.js';
|
|
|
58
63
|
import { codexUserDir } from './agent.js';
|
|
59
64
|
import { userLanguage } from './config.js';
|
|
60
65
|
import { readSessionEffort } from './session-effort.js';
|
|
61
|
-
import { sessionDetail } from './agent-detail.js';
|
|
66
|
+
import { sessionDetail, sessionTitleHints } from './agent-detail.js';
|
|
62
67
|
import { writeStateFile } from './state-file.js';
|
|
63
68
|
import { currentWarnings } from './agent-warnings.js';
|
|
64
69
|
import {
|
|
@@ -246,6 +251,40 @@ function standingFor(st, { lang, org }) {
|
|
|
246
251
|
const defaultCores = () => os.availableParallelism?.() ?? os.cpus().length;
|
|
247
252
|
const dirName = (cwd) => (typeof cwd === 'string' && cwd ? basename(cwd) || null : null);
|
|
248
253
|
|
|
254
|
+
const TITLE_MAX = 80;
|
|
255
|
+
/** A prompt this short (spaces not counted) says little by itself: "ok", "승인완료". */
|
|
256
|
+
const TITLE_MIN_CHARS = 5;
|
|
257
|
+
|
|
258
|
+
function clipTitle(text) {
|
|
259
|
+
const chars = Array.from(text);
|
|
260
|
+
return chars.length > TITLE_MAX ? `${chars.slice(0, TITLE_MAX).join('')}…` : text;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* What tells one session from another on screen. Claude Code names a session
|
|
265
|
+
* after its folder plus a number (`sprag-6b`, nameSource "derived"), which does
|
|
266
|
+
* not. In order: a name the user gave with /rename, the last prompt when it is
|
|
267
|
+
* substantial, Claude Code's own topic title, any last prompt, else null (the
|
|
268
|
+
* caller falls back to `name`). Pure; `hints` is sessionTitleHints()'s result.
|
|
269
|
+
*
|
|
270
|
+
* @param {{ name?: unknown, nameSource?: unknown }} file the session file
|
|
271
|
+
* @param {{ lastPrompt?: string|null, aiTitle?: string|null }} hints
|
|
272
|
+
* @returns {string|null}
|
|
273
|
+
*/
|
|
274
|
+
export function pickTitle(file, hints) {
|
|
275
|
+
const given = typeof file?.name === 'string' ? file.name.trim() : '';
|
|
276
|
+
if (typeof file?.nameSource === 'string' && file.nameSource !== 'derived' && given) return clipTitle(given);
|
|
277
|
+
const raw = typeof hints?.lastPrompt === 'string' ? hints.lastPrompt : '';
|
|
278
|
+
const firstLine = raw.split(/\r?\n/).find((l) => l.trim() !== '') ?? '';
|
|
279
|
+
const prompt = firstLine.replace(/\s+/g, ' ').trim();
|
|
280
|
+
const substantial = prompt !== '' && !prompt.startsWith('/') && !prompt.startsWith('<')
|
|
281
|
+
&& Array.from(prompt.replace(/\s/g, '')).length >= TITLE_MIN_CHARS;
|
|
282
|
+
if (substantial) return clipTitle(prompt);
|
|
283
|
+
const ai = typeof hints?.aiTitle === 'string' ? hints.aiTitle.trim() : '';
|
|
284
|
+
if (ai) return clipTitle(ai);
|
|
285
|
+
return prompt ? clipTitle(prompt) : null;
|
|
286
|
+
}
|
|
287
|
+
|
|
249
288
|
function claudeRow(file, { claudeDir, dataDir, now, table, env, getCache, detail, promptCache }) {
|
|
250
289
|
const cwd = typeof file.cwd === 'string' && file.cwd ? file.cwd : null;
|
|
251
290
|
const project = dirName(cwd);
|
|
@@ -262,11 +301,14 @@ function claudeRow(file, { claudeDir, dataDir, now, table, env, getCache, detail
|
|
|
262
301
|
const usage = claudeSessionDetail({ sessionId: file.sessionId, transcript, dataDir, cache: getCache(), env, now });
|
|
263
302
|
let effort = null;
|
|
264
303
|
try { effort = readSessionEffort(file.sessionId, { dir: dataDir }); } catch { effort = null; }
|
|
304
|
+
let title = null;
|
|
305
|
+
try { title = pickTitle(file, transcript ? sessionTitleHints({ transcript }) : {}); } catch { title = null; }
|
|
265
306
|
const row = {
|
|
266
307
|
agent: 'claude',
|
|
267
308
|
pid: file.pid,
|
|
268
309
|
sessionId: file.sessionId,
|
|
269
310
|
name,
|
|
311
|
+
title,
|
|
270
312
|
project,
|
|
271
313
|
cwd,
|
|
272
314
|
kind: typeof file.kind === 'string' ? file.kind : null,
|
|
@@ -358,7 +400,7 @@ export function collectActivity({
|
|
|
358
400
|
}
|
|
359
401
|
if (nested) continue;
|
|
360
402
|
const row = {
|
|
361
|
-
agent: 'codex', pid: p.pid, sessionId: null, name: 'codex', project: null, cwd: null, kind: null,
|
|
403
|
+
agent: 'codex', pid: p.pid, sessionId: null, name: 'codex', title: null, project: null, cwd: null, kind: null,
|
|
362
404
|
state: null, stateSince: null, tools: [], subagents: 0,
|
|
363
405
|
model: null, modelName: null, effort: null, context: null, usage: null,
|
|
364
406
|
cpu: 0, cpuPct: null, rssMb: 0, procs: 0,
|
package/src/agent-detail.js
CHANGED
|
@@ -208,6 +208,47 @@ function scanBack(fd, lo, hi, chunkBytes) {
|
|
|
208
208
|
return null;
|
|
209
209
|
}
|
|
210
210
|
|
|
211
|
+
/**
|
|
212
|
+
* The two lines Claude Code writes to name a session in its own picker: the last
|
|
213
|
+
* typed prompt (`last-prompt`, rewritten every turn) and a title it makes from the
|
|
214
|
+
* opening topic (`ai-title`, absent in a brand new session). Only the last
|
|
215
|
+
* `tailBytes` are read, and a line is parsed only when it carries one of the two
|
|
216
|
+
* type markers; the newest of each wins. Never throws.
|
|
217
|
+
*
|
|
218
|
+
* @returns {{ lastPrompt: string|null, aiTitle: string|null }}
|
|
219
|
+
*/
|
|
220
|
+
export function sessionTitleHints({ transcript, tailBytes = TRANSCRIPT_TAIL } = {}) {
|
|
221
|
+
const out = { lastPrompt: null, aiTitle: null };
|
|
222
|
+
if (typeof transcript !== 'string' || transcript === '') return out;
|
|
223
|
+
let fd;
|
|
224
|
+
try {
|
|
225
|
+
fd = openSync(transcript, 'r');
|
|
226
|
+
const size = fstatSync(fd).size;
|
|
227
|
+
if (size <= 0) return out;
|
|
228
|
+
const tailStart = Math.max(0, size - tailBytes);
|
|
229
|
+
const lines = readRange(fd, tailStart, size - tailStart).toString('utf8').split('\n');
|
|
230
|
+
if (tailStart > 0) lines.shift();
|
|
231
|
+
for (const line of lines) {
|
|
232
|
+
const isPrompt = line.includes('"type":"last-prompt"');
|
|
233
|
+
const isTitle = !isPrompt && line.includes('"type":"ai-title"');
|
|
234
|
+
if (!isPrompt && !isTitle) continue;
|
|
235
|
+
try {
|
|
236
|
+
const entry = JSON.parse(line);
|
|
237
|
+
if (!entry || typeof entry !== 'object') continue;
|
|
238
|
+
if (isPrompt && entry.type === 'last-prompt' && typeof entry.lastPrompt === 'string') out.lastPrompt = entry.lastPrompt;
|
|
239
|
+
if (isTitle && entry.type === 'ai-title' && typeof entry.aiTitle === 'string') out.aiTitle = entry.aiTitle;
|
|
240
|
+
} catch { /* partial or foreign line */ }
|
|
241
|
+
}
|
|
242
|
+
return out;
|
|
243
|
+
} catch {
|
|
244
|
+
return { lastPrompt: null, aiTitle: null };
|
|
245
|
+
} finally {
|
|
246
|
+
if (fd !== undefined) {
|
|
247
|
+
try { closeSync(fd); } catch { /* nothing to release */ }
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
211
252
|
/**
|
|
212
253
|
* The newest typed request, the newest text reply and the last 12 tool calls of
|
|
213
254
|
* a transcript. Never throws.
|
package/src/bar-app.js
CHANGED
|
@@ -6,6 +6,9 @@
|
|
|
6
6
|
* The first session on a Mac with the Xcode command line tools compiles it
|
|
7
7
|
* once per sprag version into <dataDir>/bar/<version>/sprag-bar and starts it.
|
|
8
8
|
* `sprag bar off` turns the whole thing off, and `sprag bar on` brings it back.
|
|
9
|
+
* Starting the app also writes a launcher, ~/Applications/Sprag Bar.app, a shell
|
|
10
|
+
* script bundle that runs `sprag bar on`, so Spotlight, Launchpad and Finder can
|
|
11
|
+
* bring the app back without a terminal.
|
|
9
12
|
*
|
|
10
13
|
* Every outside effect goes through an injectable dependency (run, spawn, kill,
|
|
11
14
|
* exists, clock, dataDir, version), so the tests start no process and touch no
|
|
@@ -18,6 +21,7 @@ import {
|
|
|
18
21
|
} from 'node:fs';
|
|
19
22
|
import { createRequire } from 'node:module';
|
|
20
23
|
import { createHash } from 'node:crypto';
|
|
24
|
+
import { homedir } from 'node:os';
|
|
21
25
|
import { basename, join } from 'node:path';
|
|
22
26
|
import { fileURLToPath } from 'node:url';
|
|
23
27
|
import { CLI_ENTRY, DETACHED_CHILD_VAR, isDetachedChild, spawnDetachedCli } from './cli-entry.js';
|
|
@@ -40,6 +44,13 @@ const TRANSIENT_ERROR = /was modified during the build/i;
|
|
|
40
44
|
const ERROR_TAIL = 600;
|
|
41
45
|
const BINARY_NAME = 'sprag-bar';
|
|
42
46
|
|
|
47
|
+
export const LAUNCHER_NAME = 'Sprag Bar.app';
|
|
48
|
+
export const LAUNCHER_ID = 'io.sprag.bar-launcher';
|
|
49
|
+
const LAUNCHER_EXECUTABLE = 'sprag-bar-launcher';
|
|
50
|
+
const LSREGISTER = '/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister';
|
|
51
|
+
/** What LaunchServices does not hand to an app it starts, and the app's data and config folders depend on. */
|
|
52
|
+
const LAUNCHER_ENV_KEYS = ['XDG_CONFIG_HOME', 'CLAUDE_CONFIG_DIR', 'CODEX_HOME'];
|
|
53
|
+
|
|
43
54
|
/** The bar is on unless the user ran `sprag bar off`. */
|
|
44
55
|
export function barEnabled(cfg = loadConfig()) {
|
|
45
56
|
return cfg?.bar !== false;
|
|
@@ -71,9 +82,12 @@ export function barBuildId(source = BAR_SOURCE) {
|
|
|
71
82
|
}
|
|
72
83
|
|
|
73
84
|
/** `version` is the build id above; the name is kept because the app's pid file calls it that. */
|
|
74
|
-
export function barPaths({ dataDir = userDataDir(), version = barBuildId() } = {}) {
|
|
85
|
+
export function barPaths({ dataDir = userDataDir(), version = barBuildId(), appsDir, home } = {}) {
|
|
75
86
|
const dir = join(dataDir, 'bar');
|
|
87
|
+
const apps = appsDir ?? join(home ?? homedir(), 'Applications');
|
|
76
88
|
return {
|
|
89
|
+
appsDir: apps,
|
|
90
|
+
launcher: join(apps, LAUNCHER_NAME),
|
|
77
91
|
dataDir,
|
|
78
92
|
dir,
|
|
79
93
|
version,
|
|
@@ -284,9 +298,115 @@ export function barChildEnv(env = process.env) {
|
|
|
284
298
|
return out;
|
|
285
299
|
}
|
|
286
300
|
|
|
301
|
+
const shQuote = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
302
|
+
const xmlEscape = (s) => String(s)
|
|
303
|
+
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* The two files of the launcher bundle. Opening the bundle runs `sprag bar on`.
|
|
307
|
+
* LaunchServices starts it without the user's shell environment, so the folders
|
|
308
|
+
* that decide where sprag keeps its data and finds Claude's settings are written
|
|
309
|
+
* into the script. A launcher without them would turn on a bar that reads other folders.
|
|
310
|
+
*/
|
|
311
|
+
export function launcherFiles({ execPath, cliEntry, env = {}, version }) {
|
|
312
|
+
const exportLines = LAUNCHER_ENV_KEYS
|
|
313
|
+
.filter((key) => typeof env?.[key] === 'string' && env[key] !== '')
|
|
314
|
+
.map((key) => `export ${key}=${shQuote(env[key])}`);
|
|
315
|
+
const script = [
|
|
316
|
+
'#!/bin/sh',
|
|
317
|
+
'# Written by sprag. Opening Sprag Bar runs `sprag bar on`, which turns the menu bar app on and starts it.',
|
|
318
|
+
...exportLines,
|
|
319
|
+
`exec ${shQuote(execPath)} ${shQuote(cliEntry)} bar on`,
|
|
320
|
+
'',
|
|
321
|
+
].join('\n');
|
|
322
|
+
const entries = [
|
|
323
|
+
['CFBundleIdentifier', `<string>${xmlEscape(LAUNCHER_ID)}</string>`],
|
|
324
|
+
['CFBundleName', '<string>Sprag Bar</string>'],
|
|
325
|
+
['CFBundleDisplayName', '<string>Sprag Bar</string>'],
|
|
326
|
+
['CFBundleExecutable', `<string>${LAUNCHER_EXECUTABLE}</string>`],
|
|
327
|
+
['CFBundlePackageType', '<string>APPL</string>'],
|
|
328
|
+
['CFBundleShortVersionString', `<string>${xmlEscape(version)}</string>`],
|
|
329
|
+
['LSUIElement', '<true/>'],
|
|
330
|
+
];
|
|
331
|
+
const plist = [
|
|
332
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
333
|
+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
334
|
+
'<plist version="1.0">',
|
|
335
|
+
'<dict>',
|
|
336
|
+
...entries.flatMap(([key, value]) => [` <key>${key}</key>`, ` ${value}`]),
|
|
337
|
+
'</dict>',
|
|
338
|
+
'</plist>',
|
|
339
|
+
'',
|
|
340
|
+
].join('\n');
|
|
341
|
+
return { plist, script };
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function launcherFilePaths(paths) {
|
|
345
|
+
return {
|
|
346
|
+
plist: join(paths.launcher, 'Contents', 'Info.plist'),
|
|
347
|
+
script: join(paths.launcher, 'Contents', 'MacOS', LAUNCHER_EXECUTABLE),
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** The text of a file, or null when it cannot be read. */
|
|
352
|
+
function readText(file) {
|
|
353
|
+
try { return readFileSync(file, 'utf8'); } catch { return null; }
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Write ~/Applications/Sprag Bar.app so Spotlight, Launchpad and Finder can start the app again.
|
|
358
|
+
* Never throws. Returns 'created', 'updated', 'unchanged', 'foreign' (a bundle or file of that name
|
|
359
|
+
* that is not ours is left alone), 'not-mac' or 'error'.
|
|
360
|
+
*/
|
|
361
|
+
export function installLauncher(deps = {}) {
|
|
362
|
+
try {
|
|
363
|
+
if ((deps.platform ?? process.platform) !== 'darwin') return 'not-mac';
|
|
364
|
+
const paths = barPaths(deps);
|
|
365
|
+
const files = launcherFilePaths(paths);
|
|
366
|
+
if (existsSync(paths.launcher) && !statSync(paths.launcher).isDirectory()) return 'foreign';
|
|
367
|
+
const oldPlist = readText(files.plist);
|
|
368
|
+
if (oldPlist !== null && !oldPlist.includes(LAUNCHER_ID)) return 'foreign';
|
|
369
|
+
const want = launcherFiles({
|
|
370
|
+
execPath: deps.execPath ?? process.execPath,
|
|
371
|
+
cliEntry: deps.cliEntry ?? CLI_ENTRY,
|
|
372
|
+
env: deps.env ?? process.env,
|
|
373
|
+
version: PKG_VERSION,
|
|
374
|
+
});
|
|
375
|
+
// Windows keeps no execute bits, so there the check would call every launcher stale (only the tests write one there).
|
|
376
|
+
let executable = false;
|
|
377
|
+
try { executable = process.platform === 'win32' || (statSync(files.script).mode & 0o111) !== 0; } catch { /* a missing script is rewritten */ }
|
|
378
|
+
if (oldPlist === want.plist && readText(files.script) === want.script && executable) return 'unchanged';
|
|
379
|
+
mkdirSync(join(paths.launcher, 'Contents', 'MacOS'), { recursive: true });
|
|
380
|
+
writeFileSync(files.plist, want.plist);
|
|
381
|
+
writeFileSync(files.script, want.script);
|
|
382
|
+
chmodSync(files.script, 0o755);
|
|
383
|
+
if (oldPlist !== null) return 'updated';
|
|
384
|
+
// A new bundle is registered once so Spotlight and Launchpad list it without waiting for their own scan.
|
|
385
|
+
try { runOf(deps)(LSREGISTER, ['-f', paths.launcher]); } catch { /* the bundle works without it */ }
|
|
386
|
+
return 'created';
|
|
387
|
+
} catch {
|
|
388
|
+
return 'error';
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** Delete the launcher, only when its Info.plist names our bundle id. True when it was deleted. Never throws. */
|
|
393
|
+
export function removeLauncher(deps = {}) {
|
|
394
|
+
try {
|
|
395
|
+
const paths = barPaths(deps);
|
|
396
|
+
const plist = readText(launcherFilePaths(paths).plist);
|
|
397
|
+
if (plist === null || !plist.includes(LAUNCHER_ID)) return false;
|
|
398
|
+
rmSync(paths.launcher, { recursive: true, force: true });
|
|
399
|
+
return true;
|
|
400
|
+
} catch {
|
|
401
|
+
return false;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
287
405
|
/** Start the compiled app detached from this process. The caller has checked the binary exists. */
|
|
288
406
|
export function launchBar(deps = {}) {
|
|
289
407
|
const paths = barPaths(deps);
|
|
408
|
+
// The launcher is a convenience: a failure to write it never keeps the app from starting.
|
|
409
|
+
try { installLauncher(deps); } catch { /* the app starts regardless */ }
|
|
290
410
|
const spawn = deps.spawn ?? childProcess.spawn;
|
|
291
411
|
const child = spawn(paths.binary, [
|
|
292
412
|
'--node', deps.execPath ?? process.execPath,
|
|
@@ -335,12 +455,16 @@ export function ensureBar({ platform = process.platform, env = process.env, cfg,
|
|
|
335
455
|
if (isDetachedChild(env)) return 'child';
|
|
336
456
|
if (envVar('NO_BAR', env) === '1') return 'off';
|
|
337
457
|
if (!barEnabled(cfg)) return 'off';
|
|
338
|
-
const d = { ...deps, env };
|
|
458
|
+
const d = { ...deps, env, platform };
|
|
339
459
|
const paths = barPaths(d);
|
|
340
460
|
let restart = false;
|
|
341
461
|
const running = barRunning(d);
|
|
342
462
|
if (running) {
|
|
343
|
-
if (running.version === paths.version)
|
|
463
|
+
if (running.version === paths.version) {
|
|
464
|
+
// An app that stays up across upgrades would otherwise never get the launcher, or a launcher naming a new node.
|
|
465
|
+
installLauncher(d);
|
|
466
|
+
return 'running';
|
|
467
|
+
}
|
|
344
468
|
stopBar(d);
|
|
345
469
|
restart = true;
|
|
346
470
|
}
|
|
@@ -363,10 +487,11 @@ export function ensureBar({ platform = process.platform, env = process.env, cfg,
|
|
|
363
487
|
}
|
|
364
488
|
}
|
|
365
489
|
|
|
366
|
-
/** Uninstall: stop the app and delete everything this module wrote under the data directory. */
|
|
490
|
+
/** Uninstall: stop the app and delete everything this module wrote under the data directory, and the launcher. */
|
|
367
491
|
export function removeBarFiles(deps = {}) {
|
|
368
492
|
const paths = barPaths(deps);
|
|
369
493
|
try { stopBar(deps); } catch { /* the files go regardless */ }
|
|
494
|
+
removeLauncher(deps);
|
|
370
495
|
for (const target of [paths.dir, paths.pidFile, paths.buildState, paths.buildLock]) {
|
|
371
496
|
try { rmSync(target, { recursive: true, force: true }); } catch { /* best effort */ }
|
|
372
497
|
}
|
package/src/commands/bar.js
CHANGED
|
@@ -145,7 +145,7 @@ export function renderText(snapshot) {
|
|
|
145
145
|
for (const g of limitGroups(snapshot)) head += ` · ${g.name} ${g.words.join(' ')}`;
|
|
146
146
|
const cells = sessions.map((r) => ({
|
|
147
147
|
dot: dot(r.state),
|
|
148
|
-
name: fit(r.name, NAME_WIDTH),
|
|
148
|
+
name: fit(r.title ?? r.name, NAME_WIDTH),
|
|
149
149
|
agent: agentText(r),
|
|
150
150
|
state: stateText(r, snapshot.at),
|
|
151
151
|
activity: fit(activityLabel(r), ACTIVITY_WIDTH),
|
|
@@ -182,7 +182,7 @@ export function renderSwiftBar(snapshot) {
|
|
|
182
182
|
out.push('No agent sessions running');
|
|
183
183
|
} else {
|
|
184
184
|
for (const r of sessions) {
|
|
185
|
-
const parts = [r.name, agentText(r), stateText(r, snapshot.at)];
|
|
185
|
+
const parts = [r.title ?? r.name, agentText(r), stateText(r, snapshot.at)];
|
|
186
186
|
const label = activityLabel(r);
|
|
187
187
|
if (label) parts.push(label);
|
|
188
188
|
for (const extra of [ctxText(r), costText(r)]) if (extra) parts.push(extra);
|
|
@@ -244,6 +244,7 @@ async function runSubcommand(sub, { hasFlag, deps }) {
|
|
|
244
244
|
if (sub === 'off') {
|
|
245
245
|
bar.setBarEnabled(false);
|
|
246
246
|
bar.stopBar(barDeps);
|
|
247
|
+
bar.removeLauncher(barDeps);
|
|
247
248
|
say('✓ The menu bar app is off and will not be started again. `sprag bar on` brings it back.',
|
|
248
249
|
'✓ 메뉴 막대 앱을 껐고 다시 시작하지 않습니다. 다시 켜려면 `sprag bar on` 을 실행하십시오.');
|
|
249
250
|
return;
|
|
@@ -255,6 +256,7 @@ async function runSubcommand(sub, { hasFlag, deps }) {
|
|
|
255
256
|
const paths = bar.barPaths(barDeps);
|
|
256
257
|
const running = bar.barRunning(barDeps);
|
|
257
258
|
if (running && running.version === paths.version) {
|
|
259
|
+
bar.installLauncher({ ...barDeps, platform });
|
|
258
260
|
say(`✓ The menu bar app is already running (pid ${running.pid}, build ${running.version}).`,
|
|
259
261
|
`✓ 메뉴 막대 앱이 이미 실행 중입니다 (pid ${running.pid}, 빌드 ${running.version}).`);
|
|
260
262
|
return;
|
|
@@ -279,6 +281,8 @@ async function runSubcommand(sub, { hasFlag, deps }) {
|
|
|
279
281
|
}
|
|
280
282
|
bar.launchBar(barDeps);
|
|
281
283
|
say('✓ The menu bar app is in the menu bar.', '✓ 메뉴 막대에 앱을 띄웠습니다.');
|
|
284
|
+
say('Open "Sprag Bar" from Spotlight or Launchpad to start it again later.',
|
|
285
|
+
'나중에 다시 켤 때는 Spotlight나 Launchpad에서 Sprag Bar를 여십시오.');
|
|
282
286
|
return;
|
|
283
287
|
}
|
|
284
288
|
|
|
@@ -326,6 +330,11 @@ async function runSubcommand(sub, { hasFlag, deps }) {
|
|
|
326
330
|
} else {
|
|
327
331
|
say('Swift toolchain: not needed, the app only works on macOS', 'Swift 도구: 필요 없음, 앱은 macOS에서만 동작합니다');
|
|
328
332
|
}
|
|
333
|
+
if (exists(paths.launcher)) {
|
|
334
|
+
say(`Launcher app: yes (${paths.launcher})`, `응용 프로그램 실행기: 있음 (${paths.launcher})`);
|
|
335
|
+
} else {
|
|
336
|
+
say('Launcher app: no', '응용 프로그램 실행기: 없음');
|
|
337
|
+
}
|
|
329
338
|
const state = bar.readBuildState(barDeps);
|
|
330
339
|
if (state?.error) {
|
|
331
340
|
say(`Last build error (${state.version ?? 'unknown build'}):\n${indent(state.error)}`,
|