sprag-cli 3.136.1 → 3.137.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.
@@ -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,30 @@ 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
- /** Go to a session: show its tab where the terminal allows it, then bring the terminal app to the front. */
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)?.activate(options: [.activateAllWindows])
289
+ guard let app = owningApp(s.pid) else { return }
290
+ app.activate(options: [.activateAllWindows])
291
+ if let url = app.bundleURL, app.isHidden || !hasWindowOnScreen(app.processIdentifier) {
292
+ let cfg = NSWorkspace.OpenConfiguration(); cfg.activates = true
293
+ NSWorkspace.shared.openApplication(at: url, configuration: cfg)
294
+ }
274
295
  }
275
296
  /** The folder a Claude session worked in, read from its transcript (`<config>/projects/<folder>/<id>.jsonl`, whose lines carry `cwd`). */
276
297
  func sessionCwd(_ sid: String) -> String? {
@@ -667,7 +688,7 @@ final class Model: ObservableObject {
667
688
  for s in sessions {
668
689
  let mine = gpuUse.filter { $0.session == s.pid }
669
690
  guard !mine.isEmpty else { continue }
670
- 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))
691
+ 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
692
  }
672
693
  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
694
  return Array(out.sorted { $0.share > $1.share }.prefix(n))
@@ -1670,7 +1691,7 @@ struct SessionRow: View {
1670
1691
  VStack(alignment: .leading, spacing: 4) {
1671
1692
  HStack(alignment: .center, spacing: 6) {
1672
1693
  Badge(agent: s.agent)
1673
- Text(s.name ?? s.agent).font(.system(size: 13, weight: .semibold)).lineLimit(2).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true)
1694
+ Text(s.label).font(.system(size: 13, weight: .semibold)).lineLimit(2).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true)
1674
1695
  Spacer(minLength: 6)
1675
1696
  if let c = s.usage?.costUsd { Text(String(format: "$%.2f", c)).font(.system(size: 12.5, weight: .medium)).monospacedDigit().fixedSize().help("이 세션의 비용, 정가 환산") }
1676
1697
  }
@@ -2265,7 +2286,7 @@ struct SessionView: View {
2265
2286
  if let s = s {
2266
2287
  FitScroll(limit: limit - 70, still: still) {
2267
2288
  VStack(alignment: .leading, spacing: 6) {
2268
- HStack(spacing: 7) { Badge(agent: s.agent); Text(s.name ?? s.agent).font(.system(size: 15, weight: .semibold)).lineLimit(1).truncationMode(.middle) }
2289
+ HStack(spacing: 7) { Badge(agent: s.agent); Text(s.label).font(.system(size: 15, weight: .semibold)).lineLimit(1).truncationMode(.middle) }
2269
2290
  if let c = s.cwd { Text(c).font(.system(size: 10.5, design: .monospaced)).foregroundColor(.secondary).lineLimit(1).truncationMode(.head).textSelection(.enabled) }
2270
2291
  HStack(spacing: 6) { Circle().fill(stateColor(s)).frame(width: 7, height: 7); Text(activity(s, now: now)).font(.system(size: 12)) }
2271
2292
  Divider().padding(.vertical, 2)
@@ -2460,7 +2481,7 @@ struct SubTile: View {
2460
2481
  HStack(spacing: 7) {
2461
2482
  Image(systemName: "arrow.turn.down.right").font(.system(size: 10, weight: .semibold)).foregroundColor(pal.text2)
2462
2483
  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.name ?? s.agent).font(.system(size: 12, weight: .medium)).foregroundColor(pal.text).lineLimit(1).truncationMode(.head)
2484
+ Text(s.label).font(.system(size: 12, weight: .medium)).foregroundColor(pal.text).lineLimit(1).truncationMode(.tail)
2464
2485
  Spacer(minLength: 4)
2465
2486
  Text("\(mark.label) \(sinceText(s.stateSince, now: now))").font(.system(size: 10.5)).foregroundColor(pal.text2).lineLimit(1).fixedSize()
2466
2487
  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 +2524,7 @@ struct SessionTile: View {
2503
2524
  HStack(spacing: 7) {
2504
2525
  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
2526
  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.name ?? s.agent).font(.system(size: 13.5, weight: .semibold)).foregroundColor(pal.text).lineLimit(1).truncationMode(.middle).help(s.name ?? s.agent)
2527
+ Text(s.label).font(.system(size: 13.5, weight: .semibold)).foregroundColor(pal.text).lineLimit(1).truncationMode(.middle).help(s.fullName)
2507
2528
  Spacer(minLength: 6)
2508
2529
  }
2509
2530
  HStack(spacing: 5) {
@@ -2838,7 +2859,7 @@ struct DashboardView: View {
2838
2859
  func inspector(_ s: Session, _ snap: Snapshot, _ pal: Pal) -> some View {
2839
2860
  let body = VStack(alignment: .leading, spacing: 6) {
2840
2861
  HStack(spacing: 7) {
2841
- Text(s.name ?? s.agent).font(.system(size: 15, weight: .semibold)).lineLimit(1).truncationMode(.middle)
2862
+ Text(s.label).font(.system(size: 15, weight: .semibold)).lineLimit(1).truncationMode(.middle)
2842
2863
  Spacer(minLength: 6)
2843
2864
  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
2865
  .buttonStyle(HoverStyle(radius: 6)).help("이 세션이 열려 있는 터미널 앱을 앞으로 가져옵니다")
@@ -2954,7 +2975,7 @@ struct DashboardView: View {
2954
2975
  let sm = model.samples, ses = snap.sessions
2955
2976
  let cpu = cpuSplit(snap, pal), mem = memSplit(snap, pal)
2956
2977
  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.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)) }
2978
+ 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
2979
  t += model.leftoverItems.map { Top(id: "l\($0.id)", name: $0.name, value: pick($0), color: pal.left, origin: leftOrigin($0.id)) }
2959
2980
  t += model.others.map { Top(id: "o\($0.id)", name: $0.name, value: pick($0), color: pal.neutral, origin: "세션과 무관한 프로그램", originSymbol: "macwindow") }
2960
2981
  return Array(t.sorted { $0.value > $1.value }.prefix(5))
@@ -3063,7 +3084,7 @@ struct DashboardView: View {
3063
3084
  let gap: CGFloat = 12, minCell: CGFloat = 318
3064
3085
  let cols = max(1, Int((width + gap) / (minCell + gap)))
3065
3086
  let cell = (width - CGFloat(cols - 1) * gap) / CGFloat(cols)
3066
- let names = Dictionary(snap.sessions.map { ($0.pid, $0.name ?? $0.agent) }, uniquingKeysWith: { a, _ in a })
3087
+ let names = Dictionary(snap.sessions.map { ($0.pid, $0.label) }, uniquingKeysWith: { a, _ in a })
3067
3088
  // A group is as wide as its main sessions need, and at least wide enough to lay its started sessions side by side.
3068
3089
  let isSub: (Session, SessionGroup) -> Bool = { s, g in model.parentSession[s.pid].map { up in g.sessions.contains { $0.pid == up } } ?? false }
3069
3090
  let spanOf: (SessionGroup) -> Int = { g in
@@ -3141,7 +3162,7 @@ struct DashboardView: View {
3141
3162
  let ph = model.phase(s), tint = pal.state(ph), mark = stateMark(s)
3142
3163
  let byLoad = ph == .active && s.state != "busy" && s.state != "shell" && s.subagents == 0
3143
3164
  let pending = (s.detail?.recent ?? []).last { $0.pending == true }
3144
- let name = Text(s.name ?? s.agent).font(.system(size: 12.5, weight: .semibold)).foregroundColor(pal.text)
3165
+ let name = Text(s.label).font(.system(size: 12.5, weight: .semibold)).foregroundColor(pal.text)
3145
3166
  let row = VStack(alignment: .leading, spacing: 6) {
3146
3167
  HStack(alignment: dense ? .top : .center, spacing: 6) {
3147
3168
  if ph == .active { LiveDot(color: tint) } else { Image(systemName: mark.symbol).font(.system(size: 11)).foregroundColor(tint).frame(width: 12) }
@@ -3197,7 +3218,7 @@ struct DashboardView: View {
3197
3218
  }
3198
3219
  /** A session resting at its prompt: one quiet line. */
3199
3220
  func idleRow(_ s: Session, _ snap: Snapshot, _ pal: Pal, dense: Bool, pick: @escaping (Session) -> Void) -> some View {
3200
- let name = Text(s.name ?? s.agent).font(.system(size: 12)).foregroundColor(pal.text2)
3221
+ let name = Text(s.label).font(.system(size: 12)).foregroundColor(pal.text2)
3201
3222
  return Pressable(radius: 6, action: { pick(s) }) {
3202
3223
  HStack(alignment: dense ? .top : .center, spacing: 6) {
3203
3224
  Image(systemName: "pause.circle").font(.system(size: 11)).foregroundColor(pal.text2).frame(width: 12)
@@ -3591,6 +3612,16 @@ final class FloatPanel: NSPanel { override var canBecomeKey: Bool { true } }
3591
3612
  * species that runs in the menu bar. It is one still frame, redrawn only when the grade changes; a running Dock icon
3592
3613
  * would spend CPU and pull the eye away from the dashboard. Drawn on the macOS icon grid (an 824 square in 1024).
3593
3614
  */
3615
+ /**
3616
+ * Give the launcher bundle the CLI writes (~/Applications/Sprag Bar.app, src/bar-app.js installLauncher) the same icon
3617
+ * as the Dock, so Spotlight and Launchpad show the runner instead of a blank app. Only a bundle whose Info.plist names
3618
+ * the launcher's id is touched; a missing one is left for the CLI to write.
3619
+ */
3620
+ func paintLauncher(_ icon: NSImage) {
3621
+ let path = NSHomeDirectory() + "/Applications/Sprag Bar.app"
3622
+ guard let plist = try? String(contentsOfFile: path + "/Contents/Info.plist", encoding: .utf8), plist.contains("io.sprag.bar-launcher") else { return }
3623
+ NSWorkspace.shared.setIcon(icon, forFile: path, options: [])
3624
+ }
3594
3625
  func dockIcon(_ grade: String?) -> NSImage {
3595
3626
  let sp = runnerSpecies(grade)
3596
3627
  // 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 +3804,14 @@ final class App: NSObject {
3773
3804
  b.toolTip = model.sysCpu != nil ? String(format: "기기 전체 CPU %.0f%%, 그중 AI 세션 %.0f%%. 세션 %d개 실행 중", (model.sysCpu ?? 0) * 100, model.share(nil), s.totals.sessions) : "작업 중인 세션 수 / 실행 중인 세션 수"
3774
3805
  }
3775
3806
  var dockGrade: String? = nil // the grade the Dock icon was drawn for
3807
+ var launcherGrade: String?? = .none // the grade the launcher's icon was drawn for, .none until the first snapshot
3776
3808
  func animate() {
3777
3809
  if NSApp.activationPolicy() == .regular, model.snap?.animal?.grade != dockGrade {
3778
3810
  dockGrade = model.snap?.animal?.grade; NSApp.applicationIconImage = dockIcon(dockGrade)
3779
3811
  }
3812
+ if selftest == nil, let snap = model.snap, launcherGrade != .some(snap.animal?.grade) {
3813
+ launcherGrade = .some(snap.animal?.grade); paintLauncher(dockIcon(snap.animal?.grade))
3814
+ }
3780
3815
  // RunCat's rule, on the same thing RunCat measures: the whole machine. A runner that strolls while the machine is
3781
3816
  // flat out, because the agent sessions' own share happens to be small, reads as wrong.
3782
3817
  let load = min(100, max(0, (model.sysCpu ?? 0) * 100))
@@ -4080,8 +4115,8 @@ func dashboardTest(_ prefix: String) {
4080
4115
  if let icon = NSApp.applicationIconImage { png(icon, "\(prefix)-dock.png") }
4081
4116
  print("DOCK icon drawn for grade \(main.dockGrade ?? "none") (species \(runnerSpecies(main.dockGrade).id))")
4082
4117
  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 }?.name ?? "\(c)") <- \(m.snap?.sessions.first { $0.pid == up }?.name ?? "\(up)")" }.sorted().joined(separator: " | ")))
4084
- 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: " | "))
4118
+ 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: " | ")))
4119
+ 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
4120
  render(DashboardView(model: m, still: true).frame(width: 1480), "\(prefix)-dashboard-dark.png")
4086
4121
  render(DashboardView(model: m, still: true, width: 340).frame(width: 340), "\(prefix)-dashboard-mini-dark.png")
4087
4122
  render(DashboardView(model: m, still: true, width: 780).frame(width: 780), "\(prefix)-dashboard-medium-dark.png")
@@ -4095,8 +4130,8 @@ func dashboardTest(_ prefix: String) {
4095
4130
  let oth = m.others.reduce(Load()) { var l = $0; l.cpu += $1.cpu; l.mem += $1.mem; l.n += $1.n; return l }
4096
4131
  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
4132
  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.name ?? $0.agent) \(pct1(m.cpuOf($0))) \(memText(m.memOf($0)))" }.joined(separator: " | "))
4099
- 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")")
4133
+ print("CPUOF " + (m.snap?.sessions ?? []).map { "\($0.label) \(pct1(m.cpuOf($0))) \(memText(m.memOf($0)))" }.joined(separator: " | "))
4134
+ 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
4135
  print("LEFT " + m.leftoverItems.prefix(6).map { "\($0.name) x\($0.n) \(memText($0.mem))" }.joined(separator: " | "))
4101
4136
  print("OTHER " + m.others.sorted { $0.cpu > $1.cpu }.prefix(5).map { "\($0.name) \(pct1($0.cpu * 100)) \(memText($0.mem))" }.joined(separator: " | "))
4102
4137
  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.136.1",
3
+ "version": "3.137.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": {
@@ -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,
@@ -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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;');
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) return 'running';
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
  }
@@ -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)}`,