sprag-cli 3.135.0 → 3.136.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.
@@ -2,7 +2,8 @@
2
2
  //
3
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
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.
5
+ // rules. The dashboard window has three sizes: wide shows a band of machine figures, every session's tile, what is running now
6
+ // and the trends; middle the band and the tiles; narrow only the session list. The window's width picks the size.
6
7
  //
7
8
  // Session data comes from `sprag bar --json` (one child at a time, never overlapping). Machine totals, each process's CPU
8
9
  // time and memory footprint, and GPU time per process come from the kernel and the I/O registry. A setting is changed by
@@ -2576,12 +2577,51 @@ struct SessionTile: View {
2576
2577
  .contentShape(Rectangle())
2577
2578
  }
2578
2579
  }
2579
- /** 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. */
2580
+ /** The dashboard's three layouts. The window's width alone picks one, so dragging the edge and pressing a preset agree. */
2581
+ enum DashSize: String, CaseIterable { case mini, medium, large
2582
+ static func of(_ width: CGFloat) -> DashSize { width < 620 ? .mini : width < 1100 ? .medium : .large }
2583
+ var label: String { self == .mini ? "작게" : self == .medium ? "중간" : "크게" }
2584
+ var tip: String { self == .mini ? "세션 목록만 봅니다 (⌘1)" : self == .medium ? "세션 타일을 봅니다 (⌘2)" : "세션 타일과 지금 도는 것, 추이를 봅니다 (⌘3)" }
2585
+ }
2586
+ /**
2587
+ * The height of the dashboard's transparent title bar. The window's view ignores the safe area SwiftUI keeps for that bar
2588
+ * and every layout leaves this much itself, so a colour can run up behind the bar while the first row starts right under
2589
+ * it. Keeping the safe area as well doubled the gap, which the narrow window cannot afford. The right column and the
2590
+ * picked session's overlay start 10 points lower, level with the band: a scroll view that begins right at the bar is
2591
+ * composited by the system in a way the self-test's capture cannot read, and the whole column came out blank there.
2592
+ */
2593
+ let TITLE_BAR: CGFloat = 28
2594
+ /** What the title bar controls show: the layout the window is in, and whether it floats over other windows. */
2595
+ final class DashUI: ObservableObject { @Published var size: DashSize = .large; @Published var pinned = false }
2596
+ /** The three size buttons and the pin, in the title bar next to the traffic lights. Drawn like `Segments`, small enough for the standard title bar. */
2597
+ struct DashControls: View {
2598
+ @ObservedObject var ui: DashUI
2599
+ let pick: (DashSize) -> Void; let pin: () -> Void
2600
+ var body: some View {
2601
+ HStack(spacing: 6) {
2602
+ HStack(spacing: 1) {
2603
+ ForEach(DashSize.allCases, id: \.self) { s in
2604
+ let on = ui.size == s
2605
+ Button(action: { if !on { pick(s) } }) {
2606
+ Text(s.label).font(.system(size: 11, weight: on ? .semibold : .regular)).lineLimit(1).fixedSize().padding(.horizontal, 7).frame(height: 18)
2607
+ .background(RoundedRectangle(cornerRadius: 4).fill(on ? Color.primary.opacity(0.24) : Color.clear)).contentShape(Rectangle())
2608
+ }.buttonStyle(HoverStyle(radius: 4, off: on)).help(s.tip)
2609
+ }
2610
+ }.padding(2).background(RoundedRectangle(cornerRadius: 6).fill(Color.primary.opacity(0.09)))
2611
+ Button(action: pin) {
2612
+ Image(systemName: ui.pinned ? "pin.fill" : "pin").font(.system(size: 11)).foregroundColor(ui.pinned ? Color.accentColor : Color.secondary).frame(width: 22, height: 22).contentShape(Rectangle())
2613
+ }.buttonStyle(HoverStyle(radius: 5)).help(ui.pinned ? "다른 창 위에 고정했습니다. 누르면 풉니다" : "다른 창 위에 고정합니다")
2614
+ }.padding(.horizontal, 8).frame(height: 24)
2615
+ }
2616
+ }
2617
+ /** Every session on one screen, in a window of its own, in three sizes: wide shows tiles, what is running and the trends, middle the tiles, narrow only the session list. */
2580
2618
  struct DashboardView: View {
2581
2619
  @ObservedObject var model: Model
2582
2620
  var still = false
2583
2621
  var stillWidth: CGFloat = 1480
2584
2622
  var lit: Int? = nil // draw this session's tile as if the pointer were on it, for a capture
2623
+ var forcedDetail: Bool? = nil // a capture says whether the machine detail is open; the window remembers it
2624
+ @AppStorage("dashMachineDetail") private var detail = false
2585
2625
  @State private var selected: Int?
2586
2626
  @State private var hoverPid: Int? // the session whose row in a largest-users list is under the pointer
2587
2627
  @State private var busyLeft: Set<String> = [] // leftover lines with an open connection: left unticked, something may be using them
@@ -2589,17 +2629,35 @@ struct DashboardView: View {
2589
2629
  @State private var picked: Set<String> = []
2590
2630
  @State private var cleanNote = ""
2591
2631
  @Environment(\.colorScheme) private var scheme
2592
- 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) }
2632
+ private var showDetail: Bool { still ? (forcedDetail ?? false) : detail }
2633
+ init(model: Model, still: Bool = false, preselect: Int? = nil, width: CGFloat = 1480, lit: Int? = nil, cleaning: Bool = false, detail: Bool? = nil) { self.model = model; self.still = still; self.stillWidth = width; self.lit = lit; self.forcedDetail = detail; 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) }
2593
2634
  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) } }
2594
2635
  func chip(_ symbol: String, _ color: Color, _ text: String, _ pal: Pal) -> some View {
2595
2636
  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()
2596
2637
  }
2597
- func smallTile<V: View>(_ label: String, _ pal: Pal, @ViewBuilder _ content: () -> V) -> some View {
2598
- VStack(alignment: .leading, spacing: 5) { Text(label).font(.system(size: 11)).foregroundColor(pal.text2).lineLimit(1); content() }
2599
- .padding(12).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading).background(RoundedRectangle(cornerRadius: 10).fill(pal.tile))
2600
- }
2601
- /** The GPU split the same way as CPU and memory: who is on it, by name, and what is left over. */
2602
- func gpuCard(_ snap: Snapshot, _ pal: Pal) -> some View {
2638
+ /** Who uses the machine's CPU: the whole figure, and its parts by owner. The band and the detail tiles both read this. */
2639
+ func cpuSplit(_ snap: Snapshot, _ pal: Pal) -> (total: Double, parts: [Part]) {
2640
+ let cl = snap.sessions.filter { $0.agent != "codex" }, cx = snap.sessions.filter { $0.agent == "codex" }
2641
+ let cpuCl = cl.reduce(0) { $0 + model.cpuOf($1) }, cpuCx = cx.reduce(0) { $0 + model.cpuOf($1) }, cpuLeft = model.leftover.cpu * 100
2642
+ let all = max((model.sysCpu ?? 0) * 100, cpuCl + cpuCx + cpuLeft)
2643
+ var parts = [Part(id: "Claude 세션", value: cpuCl, color: pal.claude)]
2644
+ if !cx.isEmpty { parts.append(Part(id: "Codex 세션", value: cpuCx, color: pal.codex)) }
2645
+ parts.append(Part(id: "끝난 세션이 남긴 것", value: cpuLeft, color: pal.left))
2646
+ parts.append(Part(id: "그 밖", value: max(0, all - cpuCl - cpuCx - cpuLeft), color: pal.neutral))
2647
+ return (all, parts)
2648
+ }
2649
+ /** The same for memory, in MB. */
2650
+ func memSplit(_ snap: Snapshot, _ pal: Pal) -> (total: Double, parts: [Part]) {
2651
+ let cl = snap.sessions.filter { $0.agent != "codex" }, cx = snap.sessions.filter { $0.agent == "codex" }
2652
+ let memCl = cl.reduce(0) { $0 + model.memOf($1) }, memCx = cx.reduce(0) { $0 + model.memOf($1) }, memLeft = model.leftover.mem
2653
+ var parts = [Part(id: "Claude 세션", value: memCl, color: pal.claude)]
2654
+ if !cx.isEmpty { parts.append(Part(id: "Codex 세션", value: memCx, color: pal.codex)) }
2655
+ parts.append(Part(id: "끝난 세션이 남긴 것", value: memLeft, color: pal.left))
2656
+ parts.append(Part(id: "다른 프로그램", value: model.others.reduce(0) { $0 + $1.mem }, color: pal.neutral))
2657
+ return (model.sysMemMb ?? 0, parts)
2658
+ }
2659
+ /** The GPU split the same way as CPU and memory: who is on it, and what is left over. */
2660
+ func gpuSplit(_ snap: Snapshot, _ pal: Pal) -> (total: Double, parts: [Part]) {
2603
2661
  let g = (model.gpu ?? 0) * 100
2604
2662
  let hasCodex = snap.sessions.contains { $0.agent == "codex" }
2605
2663
  let cl = min(100, snap.sessions.filter { $0.agent != "codex" }.reduce(0) { $0 + (model.gpuBySession[$1.pid] ?? 0) } * 100)
@@ -2609,6 +2667,21 @@ struct DashboardView: View {
2609
2667
  if hasCodex { parts.append(Part(id: "Codex 세션", value: cx, color: pal.codex)) }
2610
2668
  parts.append(Part(id: "끝난 세션이 남긴 것", value: left, color: pal.left))
2611
2669
  parts.append(Part(id: "그 밖", value: max(0, g - cl - cx - left), color: pal.neutral))
2670
+ return (g, parts)
2671
+ }
2672
+ /** The thin bar split by owner, the rest in the well colour: the detail tiles draw it 8 points high, the band 6. */
2673
+ func splitBar(_ parts: [Part], scale: Double, height: CGFloat, _ pal: Pal) -> some View {
2674
+ let full = max(scale, parts.reduce(0) { $0 + $1.value }, 0.000001)
2675
+ return GeometryReader { g in
2676
+ HStack(spacing: 2) {
2677
+ 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))) } }
2678
+ Rectangle().fill(pal.well).frame(maxWidth: .infinity)
2679
+ }.clipShape(Capsule())
2680
+ }.frame(height: height)
2681
+ }
2682
+ /** The GPU detail tile, shown under the band when the detail is open. */
2683
+ func gpuCard(_ snap: Snapshot, _ pal: Pal) -> some View {
2684
+ let sp = gpuSplit(snap, pal)
2612
2685
  let top: [Top] = model.gpuLines(snap.sessions, max: 5).map { l in
2613
2686
  let s = l.pid.flatMap { p in snap.sessions.first { $0.pid == p } }
2614
2687
  return Top(id: l.id, name: l.label, value: l.share * 100,
@@ -2616,78 +2689,121 @@ struct DashboardView: View {
2616
2689
  pid: s?.pid, program: s == nil || l.note.isEmpty ? nil : l.note, doing: s.flatMap { doingNow($0) },
2617
2690
  origin: s != nil ? nil : l.agent == "left" ? "끝난 세션이 남긴 것" : "세션과 무관한 프로그램", originSymbol: l.agent == "left" ? "moon.zzz.fill" : "macwindow")
2618
2691
  }
2619
- return machineTile(title: "GPU", total: pct1(g), sub: "기기 전체", parts: parts, scale: 100, fmt: { pct1($0) }, top: top, series: [],
2692
+ return machineTile(title: "GPU", total: pct1(sp.total), sub: "기기 전체", parts: sp.parts, scale: 100, fmt: { pct1($0) }, top: top, series: [],
2620
2693
  tip: "전체 값은 GPU 장치의 사용률이고 이름별 값은 각 프로그램이 GPU를 쓴 시간의 비율입니다. 재는 방식이 달라 합이 조금 어긋날 수 있습니다", pal: pal)
2621
2694
  }
2622
- func kpis(_ snap: Snapshot, _ pal: Pal, width: CGFloat) -> some View {
2623
- let sm = model.samples, span = spanText(sm.first?.at, sm.last?.at)
2624
- let costs = sm.map { $0.cost }, costUp = (costs.last ?? 0) - (costs.first ?? 0)
2695
+ struct Counts { var active = 0, mains = 0, user = 0, idle = 0, subs = 0 }
2696
+ /** How many main sessions work, wait for the user or rest, and how many sessions they started. Every place that says it reads this one count. */
2697
+ func counts(_ snap: Snapshot) -> Counts {
2625
2698
  let mainOnes = snap.sessions.filter { model.parentSession[$0.pid] == nil }
2626
2699
  let phases = mainOnes.map { model.phase($0) }
2627
- let nUser = phases.filter { $0 == .needsUser }.count, nIdle = phases.filter { $0 == .idle }.count, nSubs = snap.sessions.count - mainOnes.count
2628
- let wins = snap.usage?.claude?.windows ?? []
2629
- let working = smallTile("작업 중인 세션", pal) {
2630
- HStack(alignment: .firstTextBaseline, spacing: 5) {
2631
- Text("\(phases.filter { $0 == .active }.count)").font(.system(size: 40, weight: .semibold)).foregroundColor(pal.text)
2632
- Text("/ \(mainOnes.count)").font(.system(size: 16, weight: .medium)).foregroundColor(pal.text2)
2633
- }
2634
- VStack(alignment: .leading, spacing: 2) {
2635
- if nUser > 0 { chip("hand.raised.fill", pal.warning, "확인 대기 \(nUser)", pal) }
2636
- if nIdle > 0 { chip("pause.circle", pal.text2, "입력 대기 \(nIdle)", pal) }
2637
- if nSubs > 0 { chip("arrow.turn.down.right", pal.text2, "띄운 세션 \(nSubs)", pal) }
2638
- }
2639
- }
2640
- let cost = smallTile("세션 비용, 정가 환산", pal) {
2641
- Text(snap.totals.costUsd.map { String(format: "$%.2f", $0) } ?? "-").font(.system(size: 22, weight: .semibold)).monospacedDigit().foregroundColor(pal.text).lineLimit(1).fixedSize()
2642
- Text("실행 중인 세션 \(snap.sessions.count)개 합계").font(.system(size: 10.5)).foregroundColor(pal.text2).lineLimit(1)
2643
- if costUp > 0.005 { Text(String(format: "%@ 동안 +$%.2f", span, costUp)).font(.system(size: 10.5)).monospacedDigit().foregroundColor(pal.text2).lineLimit(1) }
2644
- }.help("구독 청구액이 아니라 쓴 토큰을 정가로 환산한 값입니다")
2645
- let limits = smallTile("Claude 한도", pal) {
2646
- if wins.isEmpty { Text("받은 값이 없습니다").font(.system(size: 11)).foregroundColor(pal.text2) }
2647
- ForEach(wins, id: \.key) { w in
2648
- let sv = severity(w.usedPct, pal.claude, pal)
2649
- VStack(alignment: .leading, spacing: 3) {
2650
- HStack(spacing: 5) {
2651
- Text(windowName(w)).font(.system(size: 11.5, weight: .medium)).foregroundColor(pal.text)
2652
- if let sym = sv.symbol { Image(systemName: sym).font(.system(size: 10)).foregroundColor(sv.color) }
2653
- Spacer(minLength: 4)
2654
- Text("\(Int(w.usedPct.rounded()))%").font(.system(size: 15, weight: .semibold)).monospacedDigit().foregroundColor(pal.text).fixedSize()
2655
- }
2656
- Meter(value: w.usedPct / 100, fill: sv.color)
2657
- Text(resetText(w.resetsAt, now: snap.at)).font(.system(size: 10.5)).foregroundColor(pal.text2).lineLimit(1).minimumScaleFactor(0.85)
2658
- }
2700
+ return Counts(active: phases.filter { $0 == .active }.count, mains: mainOnes.count, user: phases.filter { $0 == .needsUser }.count, idle: phases.filter { $0 == .idle }.count, subs: snap.sessions.count - mainOnes.count)
2701
+ }
2702
+ /** One tile of the band: 58 pt high on the same plate as every tile. `grow` lets it take the width the others leave. */
2703
+ func bandTile<V: View>(_ pal: Pal, width: CGFloat? = nil, grow: Bool = false, @ViewBuilder _ content: () -> V) -> some View {
2704
+ VStack(alignment: .leading, spacing: 3) { content() }
2705
+ .padding(.horizontal, 10).padding(.vertical, 8)
2706
+ .frame(width: width, height: 58, alignment: .leading)
2707
+ .frame(maxWidth: grow ? CGFloat.infinity : nil, alignment: .leading)
2708
+ .background(RoundedRectangle(cornerRadius: 10).fill(pal.tile))
2709
+ }
2710
+ func bandLabel(_ text: String, _ pal: Pal) -> some View { Text(text).font(.system(size: 10.5)).foregroundColor(pal.text2).fixedSize() }
2711
+ func sessionsTile(_ snap: Snapshot, _ pal: Pal) -> some View {
2712
+ let n = counts(snap)
2713
+ return bandTile(pal, grow: true) {
2714
+ bandLabel("작업 중인 세션", pal)
2715
+ HStack(spacing: 7) {
2716
+ if n.active > 0 { LiveDot(color: pal.good) }
2717
+ Text("\(n.active)").font(.system(size: 18, weight: .semibold)).monospacedDigit().foregroundColor(pal.text).fixedSize()
2718
+ Text("/ \(n.mains)").font(.system(size: 12)).foregroundColor(pal.text2).fixedSize()
2719
+ if n.user > 0 { chip("hand.raised.fill", pal.warning, "확인 대기 \(n.user)", pal) }
2720
+ if n.idle > 0 { chip("pause.circle", pal.text2, "입력 대기 \(n.idle)", pal) }
2721
+ if n.subs > 0 { chip("arrow.turn.down.right", pal.text2, "띄운 세션 \(n.subs)", pal) }
2659
2722
  }
2660
2723
  }
2661
- let rank = smallTile("이달의 랭킹", pal) {
2662
- if let st = snap.standing {
2663
- HStack(spacing: 8) {
2664
- Text(st.emoji).font(.system(size: 28)).fixedSize()
2665
- VStack(alignment: .leading, spacing: 0) {
2666
- 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) } }
2667
- Text(st.rank != nil && st.ranked != nil ? "\(Int(st.ranked!))명 중 \(Int(st.rank!))위" : "집계 전").font(.system(size: 11.5)).foregroundColor(pal.text2).lineLimit(1)
2668
- }
2669
- }
2670
- if let p = st.scorePct {
2671
- Meter(value: p / 100, fill: pal.neutral, tick: st.next?.floorPct.map { $0 / 100 }, tickColor: pal.text)
2672
- Text("점수 백분위 \(Int(p))%" + (st.next.map { ", 다음 \($0.emoji) \($0.floorPct.map { "\(Int($0))%" } ?? "")" } ?? "")).font(.system(size: 10.5)).foregroundColor(pal.text2).lineLimit(1)
2673
- }
2674
- } else { Text("팀에 참여하면 나옵니다").font(.system(size: 11)).foregroundColor(pal.text2) }
2724
+ }
2725
+ /** CPU, memory or GPU as a figure and the split bar; the line each part says is in the tooltip. */
2726
+ func resourceTile(_ title: String, _ value: String, _ parts: [Part], scale: Double, fmt: (Double) -> String, fixed: Bool, _ pal: Pal) -> some View {
2727
+ let tip = (["누르면 나눠 쓰는 몫과 많이 쓰는 곳을 펼칩니다"] + parts.map { "\($0.id) \(fmt($0.value))" }).joined(separator: "\n")
2728
+ return bandTile(pal, width: fixed ? 118 : nil, grow: !fixed) {
2729
+ HStack(spacing: 4) {
2730
+ Text(title).font(.system(size: 10.5)).foregroundColor(pal.text2).fixedSize()
2731
+ Spacer(minLength: 4)
2732
+ Text(value).font(.system(size: 13, weight: .semibold)).monospacedDigit().foregroundColor(pal.text).fixedSize()
2733
+ }
2734
+ splitBar(parts, scale: scale, height: 6, pal).padding(.top, 3)
2735
+ }.help(tip)
2736
+ }
2737
+ /** The three machine tiles are one button: pressing any of them opens or closes the detail above the sessions. */
2738
+ func resources(_ snap: Snapshot, _ pal: Pal, fixed: Bool) -> some View {
2739
+ let cpu = cpuSplit(snap, pal), mem = memSplit(snap, pal), gpu = gpuSplit(snap, pal)
2740
+ return Pressable(radius: 10, action: { detail.toggle() }) {
2741
+ HStack(spacing: 6) {
2742
+ resourceTile("CPU", pct1(cpu.total), cpu.parts, scale: 100, fmt: { pct1($0) }, fixed: fixed, pal)
2743
+ resourceTile("메모리", memText(mem.total), mem.parts, scale: RAM_MB, fmt: { memText($0) }, fixed: fixed, pal)
2744
+ if model.gpu != nil { resourceTile("GPU", pct1(gpu.total), gpu.parts, scale: 100, fmt: { pct1($0) }, fixed: fixed, pal) }
2745
+ Image(systemName: showDetail ? "chevron.up" : "chevron.down").font(.system(size: 9)).foregroundColor(pal.text2).frame(width: 12)
2746
+ }
2675
2747
  }
2676
- return Group {
2677
- if width >= 980 {
2678
- HStack(alignment: .top, spacing: 10) {
2679
- if model.gpu != nil { gpuCard(snap, pal) }
2680
- working.frame(width: 132); cost.frame(width: 156); limits.frame(width: 170); rank.frame(width: 170)
2681
- }.fixedSize(horizontal: false, vertical: true)
2682
- } else {
2683
- VStack(spacing: 10) {
2684
- if model.gpu != nil { gpuCard(snap, pal) }
2685
- HStack(alignment: .top, spacing: 10) { working; cost }.fixedSize(horizontal: false, vertical: true)
2686
- HStack(alignment: .top, spacing: 10) { limits; rank }.fixedSize(horizontal: false, vertical: true)
2748
+ }
2749
+ func limitsTile(_ snap: Snapshot, _ pal: Pal) -> some View {
2750
+ let wins = snap.usage?.claude?.windows ?? []
2751
+ return bandTile(pal) {
2752
+ bandLabel("Claude 한도", pal)
2753
+ HStack(alignment: .top, spacing: 12) {
2754
+ ForEach(wins, id: \.key) { w in
2755
+ let sv = severity(w.usedPct, pal.claude, pal)
2756
+ VStack(alignment: .leading, spacing: 3) {
2757
+ HStack(spacing: 4) {
2758
+ Text(windowName(w)).font(.system(size: 11.5, weight: .medium)).foregroundColor(pal.text).fixedSize()
2759
+ if let sym = sv.symbol { Image(systemName: sym).font(.system(size: 10)).foregroundColor(sv.color) }
2760
+ Spacer(minLength: 4)
2761
+ Text("\(Int(w.usedPct.rounded()))%").font(.system(size: 13, weight: .semibold)).monospacedDigit().foregroundColor(pal.text).fixedSize()
2762
+ }
2763
+ Meter(value: w.usedPct / 100, fill: sv.color, height: 5)
2764
+ }.frame(minWidth: 84, alignment: .leading).help(resetText(w.resetsAt, now: snap.at))
2687
2765
  }
2688
2766
  }
2689
2767
  }
2690
2768
  }
2769
+ func costTile(_ snap: Snapshot, _ pal: Pal) -> some View {
2770
+ let sm = model.samples, span = spanText(sm.first?.at, sm.last?.at)
2771
+ let costs = sm.map { $0.cost }, costUp = (costs.last ?? 0) - (costs.first ?? 0)
2772
+ var tip = "실행 중인 세션 \(snap.sessions.count)개 합계입니다. 구독 청구액이 아니라 쓴 토큰을 정가로 환산한 값입니다"
2773
+ if costUp > 0.005 { tip += "\n" + String(format: "%@ 동안 +$%.2f", span, costUp) }
2774
+ return bandTile(pal) {
2775
+ bandLabel("세션 비용, 정가 환산", pal)
2776
+ Text(snap.totals.costUsd.map { String(format: "$%.2f", $0) } ?? "-").font(.system(size: 15, weight: .semibold)).monospacedDigit().foregroundColor(pal.text).fixedSize()
2777
+ }.help(tip)
2778
+ }
2779
+ func rankTile(_ st: Standing, _ pal: Pal) -> some View {
2780
+ var tip = ""
2781
+ if let p = st.scorePct { tip = "점수 백분위 \(Int(p))%" + (st.next.map { ", 다음 \($0.emoji) \($0.floorPct.map { "\(Int($0))%" } ?? "")" } ?? "") }
2782
+ return bandTile(pal) {
2783
+ bandLabel("이달의 랭킹", pal)
2784
+ HStack(spacing: 6) {
2785
+ Text(st.emoji).font(.system(size: 15)).fixedSize()
2786
+ Text(st.name).font(.system(size: 12.5, weight: .semibold)).foregroundColor(pal.text).fixedSize()
2787
+ if st.crown == true { Image(systemName: "crown.fill").font(.system(size: 9.5)).foregroundColor(pal.warning) }
2788
+ Text(st.rank != nil && st.ranked != nil ? "\(Int(st.ranked!))명 중 \(Int(st.rank!))위" : "집계 전").font(.system(size: 11.5)).foregroundColor(pal.text2).fixedSize()
2789
+ }
2790
+ }.help(tip)
2791
+ }
2792
+ /**
2793
+ * One thin band instead of the big machine and summary tiles: what the sessions are doing, the machine as three small
2794
+ * bars, the account limits, the cost and the ranking. The first row that fits the width wins, and the last one wraps.
2795
+ */
2796
+ func band(_ snap: Snapshot, _ pal: Pal) -> some View {
2797
+ let sessions = sessionsTile(snap, pal), cost = costTile(snap, pal)
2798
+ let hasLimits = !(snap.usage?.claude?.windows ?? []).isEmpty
2799
+ return ViewThatFits(in: .horizontal) {
2800
+ HStack(spacing: 8) { sessions; resources(snap, pal, fixed: true); if hasLimits { limitsTile(snap, pal) }; cost; if let st = snap.standing { rankTile(st, pal) } }
2801
+ HStack(spacing: 8) { sessions; resources(snap, pal, fixed: true); if hasLimits { limitsTile(snap, pal) }; cost }
2802
+ HStack(spacing: 8) { sessions; resources(snap, pal, fixed: true); if hasLimits { limitsTile(snap, pal) } }
2803
+ HStack(spacing: 8) { sessions; resources(snap, pal, fixed: true) }
2804
+ VStack(spacing: 8) { sessions; resources(snap, pal, fixed: false) }
2805
+ }
2806
+ }
2691
2807
  /** Trends at a size and with the labels that let them be read: the machine against the sessions, for CPU, memory and GPU. */
2692
2808
  func trends(_ pal: Pal) -> some View {
2693
2809
  let sm = model.samples, span = spanText(sm.first?.at, sm.last?.at)
@@ -2779,7 +2895,6 @@ struct DashboardView: View {
2779
2895
  }
2780
2896
  /** 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. */
2781
2897
  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 {
2782
- let full = max(scale, parts.reduce(0) { $0 + $1.value }, 0.000001)
2783
2898
  let topMax = max(top.map { $0.value }.max() ?? 0, 0.000001)
2784
2899
  // The figure, bar and legend take a fixed narrow column, so every remaining point of width goes to the names of the largest users.
2785
2900
  return HStack(alignment: .top, spacing: 14) {
@@ -2789,12 +2904,7 @@ struct DashboardView: View {
2789
2904
  Text(total).font(.system(size: 26, weight: .semibold)).foregroundColor(pal.text).lineLimit(1).fixedSize()
2790
2905
  Text(sub).font(.system(size: 11)).foregroundColor(pal.text2).lineLimit(1)
2791
2906
  }
2792
- GeometryReader { g in
2793
- HStack(spacing: 2) {
2794
- 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))) } }
2795
- Rectangle().fill(pal.well).frame(maxWidth: .infinity)
2796
- }.clipShape(Capsule())
2797
- }.frame(height: 8)
2907
+ splitBar(parts, scale: scale, height: 8, pal)
2798
2908
  VStack(alignment: .leading, spacing: 3) {
2799
2909
  ForEach(parts) { p in
2800
2910
  HStack(spacing: 5) {
@@ -2835,25 +2945,17 @@ struct DashboardView: View {
2835
2945
  }
2836
2946
  func machine(_ snap: Snapshot, _ pal: Pal, width: CGFloat) -> some View {
2837
2947
  let sm = model.samples, ses = snap.sessions
2838
- let cl = ses.filter { $0.agent != "codex" }, cx = ses.filter { $0.agent == "codex" }
2839
- let cpuCl = cl.reduce(0) { $0 + model.cpuOf($1) }, cpuCx = cx.reduce(0) { $0 + model.cpuOf($1) }, cpuLeft = model.leftover.cpu * 100
2840
- let cpuAll = max((model.sysCpu ?? 0) * 100, cpuCl + cpuCx + cpuLeft)
2841
- let memCl = cl.reduce(0) { $0 + model.memOf($1) }, memCx = cx.reduce(0) { $0 + model.memOf($1) }, memLeft = model.leftover.mem
2842
- let memAll = model.sysMemMb ?? 0
2843
- var cpuParts = [Part(id: "Claude 세션", value: cpuCl, color: pal.claude)], memParts = [Part(id: "Claude 세션", value: memCl, color: pal.claude)]
2844
- if !cx.isEmpty { cpuParts.append(Part(id: "Codex 세션", value: cpuCx, color: pal.codex)); memParts.append(Part(id: "Codex 세션", value: memCx, color: pal.codex)) }
2845
- cpuParts.append(Part(id: "끝난 세션이 남긴 것", value: cpuLeft, color: pal.left)); memParts.append(Part(id: "끝난 세션이 남긴 것", value: memLeft, color: pal.left))
2846
- 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))
2948
+ let cpu = cpuSplit(snap, pal), mem = memSplit(snap, pal)
2847
2949
  func tops(_ pick: (AppLoad) -> Double, _ of: (Session) -> Double, _ part: (Work) -> Double, _ show: (Double) -> String) -> [Top] {
2848
2950
  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)) }
2849
2951
  t += model.leftoverItems.map { Top(id: "l\($0.id)", name: $0.name, value: pick($0), color: pal.left, origin: leftOrigin($0.id)) }
2850
2952
  t += model.others.map { Top(id: "o\($0.id)", name: $0.name, value: pick($0), color: pal.neutral, origin: "세션과 무관한 프로그램", originSymbol: "macwindow") }
2851
2953
  return Array(t.sorted { $0.value > $1.value }.prefix(5))
2852
2954
  }
2853
- 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) }),
2955
+ let a = machineTile(title: "CPU", total: pct1(cpu.total), sub: "기기 전체", parts: cpu.parts, scale: 100, fmt: { pct1($0) }, top: tops({ $0.cpu * 100 }, { model.cpuOf($0) }, { $0.cpu * 100 }, { pct1($0) }),
2854
2956
  series: [(sm.map { $0.sysCpu * 100 }, pal.neutral), (sm.map { ($0.claudeCpu + $0.codexCpu) * 100 }, pal.claude)],
2855
2957
  tip: "세션 값에는 세션이 따로 떼어 띄운 프로세스도 들어갑니다. 회색 선은 기기 전체, 색 선은 실행 중인 세션입니다", pal: pal)
2856
- 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) }),
2958
+ let b = machineTile(title: "메모리", total: memText(mem.total), sub: "/ \(Int((RAM_MB / 1024).rounded())) GB 사용", parts: mem.parts, scale: RAM_MB, fmt: { memText($0) }, top: tops({ $0.mem }, { model.memOf($0) }, { $0.mem }, { memText($0) }),
2857
2959
  series: [(sm.map { $0.sysMem * 100 }, pal.neutral), (sm.map { ($0.claudeMem + $0.codexMem) * 100 }, pal.claude)],
2858
2960
  tip: "프로그램별 값은 압축된 메모리와 GPU 메모리까지 센 점유량입니다. 그래서 합이 실제 사용량보다 클 수 있습니다", pal: pal)
2859
2961
  return Group { if width >= 900 { HStack(alignment: .top, spacing: 10) { a; b } } else { VStack(spacing: 10) { a; b } } }
@@ -3013,115 +3115,246 @@ struct DashboardView: View {
3013
3115
  if w.mem >= 512 { IconStat(symbol: "memorychip", value: memText(w.mem), tip: "메모리", pal: pal) }
3014
3116
  }
3015
3117
  }
3016
- /** 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. */
3017
- func nowColumn(_ snap: Snapshot, _ pal: Pal) -> some View {
3118
+ func warnText(_ w: Warn) -> String { w.chip.replacingOccurrences(of: "⚠ ", with: "").replacingOccurrences(of: "🚨 ", with: "") }
3119
+ func warnIcon(_ w: Warn, _ pal: Pal) -> some View {
3120
+ Image(systemName: w.level == "critical" ? "exclamationmark.octagon.fill" : "exclamationmark.triangle.fill").font(.system(size: 11)).foregroundColor(w.level == "critical" ? pal.critical : pal.warning)
3121
+ }
3122
+ /** The statusline's warnings as capsules in one row, under the band. */
3123
+ func warnChips(_ ws: [Warn], _ pal: Pal) -> some View {
3124
+ HStack(spacing: 8) {
3125
+ ForEach(ws) { w in
3126
+ HStack(spacing: 6) { warnIcon(w, pal); Text(warnText(w)).font(.system(size: 12, weight: .medium)).foregroundColor(pal.text) }
3127
+ .padding(.horizontal, 9).padding(.vertical, 5).background(Capsule().fill(pal.tile)).help(w.advice?.first?.tip ?? w.advice?.first?.title ?? "")
3128
+ }
3129
+ Spacer(minLength: 0)
3130
+ }
3131
+ }
3132
+ /** One session that is working or waiting for the user. `dense` says in one line what it is doing, where the wide layout lists its programs. */
3133
+ func liveRow(_ s: Session, _ snap: Snapshot, _ pal: Pal, subs: [Session], dense: Bool, pick: @escaping (Session) -> Void) -> some View {
3134
+ let ph = model.phase(s), tint = pal.state(ph), mark = stateMark(s)
3135
+ let byLoad = ph == .active && s.state != "busy" && s.state != "shell" && s.subagents == 0
3136
+ let pending = (s.detail?.recent ?? []).last { $0.pending == true }
3137
+ let name = Text(s.name ?? s.agent).font(.system(size: 12.5, weight: .semibold)).foregroundColor(pal.text)
3138
+ let row = VStack(alignment: .leading, spacing: 6) {
3139
+ HStack(alignment: dense ? .top : .center, spacing: 6) {
3140
+ if ph == .active { LiveDot(color: tint) } else { Image(systemName: mark.symbol).font(.system(size: 11)).foregroundColor(tint).frame(width: 12) }
3141
+ // The narrow layout never cuts a name: it takes a second line first.
3142
+ if dense { name.lineLimit(2).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true) } else { name.lineLimit(1).truncationMode(.middle) }
3143
+ Spacer(minLength: 4)
3144
+ Text(byLoad ? "프로그램 실행 중" : "\(mark.label) \(sinceText(s.stateSince, now: snap.at))").font(.system(size: 11)).foregroundColor(pal.text2).lineLimit(1).fixedSize()
3145
+ }
3146
+ if dense { doingLine(s, pending, pal) } else {
3147
+ if let p = pending {
3148
+ HStack(alignment: .top, spacing: 6) {
3149
+ Image(systemName: toolSymbol(p.tool)).font(.system(size: 10)).foregroundColor(pal.text2).frame(width: 12, height: 14)
3150
+ Text((p.target ?? "").isEmpty ? toolName(p.tool) : (p.target ?? "")).font(.system(size: 11.5)).foregroundColor(pal.text).lineLimit(2).fixedSize(horizontal: false, vertical: true)
3151
+ }
3152
+ }
3153
+ ForEach(Array(model.working(s, max: 3).enumerated()), id: \.offset) { _, it in
3154
+ VStack(alignment: .leading, spacing: 2) {
3155
+ HStack(spacing: 6) {
3156
+ Image(systemName: "gearshape.2.fill").font(.system(size: 9.5)).foregroundColor(pal.text2).frame(width: 12)
3157
+ Text(it.name).font(.system(size: 11.5, weight: .medium)).foregroundColor(pal.text).lineLimit(1).truncationMode(.middle).help(it.name)
3158
+ }
3159
+ stats(it.w, pal).padding(.leading, 18)
3160
+ }
3161
+ }
3162
+ }
3163
+ if !subs.isEmpty {
3164
+ HStack(spacing: 6) {
3165
+ Image(systemName: "arrow.turn.down.right").font(.system(size: 9.5, weight: .semibold)).foregroundColor(pal.text2).frame(width: 12)
3166
+ Text("띄운 세션 \(subs.count)개").font(.system(size: 11.5)).foregroundColor(pal.text)
3167
+ Spacer(minLength: 4)
3168
+ Text("작업 중 \(subs.filter { model.phase($0) == .active }.count)").font(.system(size: 11, weight: .medium)).monospacedDigit().foregroundColor(pal.text)
3169
+ }
3170
+ }
3171
+ }.padding(10).frame(maxWidth: .infinity, alignment: .leading).background(RoundedRectangle(cornerRadius: 8).fill(pal.well.opacity(0.55)))
3172
+ return Pressable(radius: 8, action: { pick(s) }) { row }.help(dense ? "누르면 이 세션이 열려 있는 터미널로 갑니다" : "")
3173
+ }
3174
+ /** What a working session does right now, in one line: the tool call in flight, else its heaviest program, else that it is writing. Its context fill sits at the end. */
3175
+ @ViewBuilder func doingLine(_ s: Session, _ pending: ToolCall?, _ pal: Pal) -> some View {
3176
+ let top = model.working(s, max: 1).first
3177
+ let what: (symbol: String, text: String)? = pending.map { p in (toolSymbol(p.tool), (p.target ?? "").isEmpty ? toolName(p.tool) : (p.target ?? "")) }
3178
+ ?? top.map { ("gearshape.2.fill", $0.name) } ?? (s.state == "busy" ? ("ellipsis.bubble.fill", "응답을 쓰는 중") : nil)
3179
+ let ctx = s.context?.pct
3180
+ if what != nil || ctx != nil {
3181
+ HStack(alignment: .top, spacing: 6) {
3182
+ if let w = what {
3183
+ Image(systemName: w.symbol).font(.system(size: 10)).foregroundColor(pal.text2).frame(width: 12, height: 14)
3184
+ Text(w.text).font(.system(size: 11.5)).foregroundColor(pal.text).lineLimit(2).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true)
3185
+ }
3186
+ Spacer(minLength: 4)
3187
+ if let p = ctx { Text("컨텍스트 \(Int(p))%").font(.system(size: 10.5)).monospacedDigit().foregroundColor(severity(p, pal.text2, pal, warnAt: 80, critAt: 95).color).lineLimit(1).fixedSize() }
3188
+ }
3189
+ }
3190
+ }
3191
+ /** A session resting at its prompt: one quiet line. */
3192
+ func idleRow(_ s: Session, _ snap: Snapshot, _ pal: Pal, dense: Bool, pick: @escaping (Session) -> Void) -> some View {
3193
+ let name = Text(s.name ?? s.agent).font(.system(size: 12)).foregroundColor(pal.text2)
3194
+ return Pressable(radius: 6, action: { pick(s) }) {
3195
+ HStack(alignment: dense ? .top : .center, spacing: 6) {
3196
+ Image(systemName: "pause.circle").font(.system(size: 11)).foregroundColor(pal.text2).frame(width: 12)
3197
+ if dense { name.lineLimit(2).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true) } else { name.lineLimit(1).truncationMode(.middle) }
3198
+ Spacer(minLength: 4)
3199
+ Text(sinceText(s.stateSince, now: snap.at)).font(.system(size: 10.5)).foregroundColor(pal.text2).fixedSize()
3200
+ }.padding(.vertical, 5).padding(.horizontal, 10).frame(maxWidth: .infinity, alignment: .leading)
3201
+ }.help(dense ? "누르면 이 세션이 열려 있는 터미널로 갑니다" : "")
3202
+ }
3203
+ /**
3204
+ * Who is working or waiting for the user, then who rests at the prompt, as rows that can be pressed. It fills the width
3205
+ * it is given: the right column gives it 372 points, the narrow layout the whole window.
3206
+ */
3207
+ func nowList(_ snap: Snapshot, _ pal: Pal, dense: Bool, pick: @escaping (Session) -> Void) -> some View {
3018
3208
  let everyone = model.ordered(snap.sessions)
3019
3209
  let all = everyone.filter { model.parentSession[$0.pid] == nil }
3020
3210
  let subsOf: (Session) -> [Session] = { up in everyone.filter { model.parentSession[$0.pid] == up.pid } }
3021
3211
  let busy: (Session) -> Bool = { s in model.phase(s) != .idle || subsOf(s).contains { model.phase($0) != .idle } }
3022
3212
  let live = all.filter { busy($0) }, idle = all.filter { !busy($0) }
3023
- let body = VStack(alignment: .leading, spacing: 10) {
3024
- Text("지금 도는 것").font(.system(size: 15, weight: .semibold)).foregroundColor(pal.text)
3213
+ return VStack(alignment: .leading, spacing: 10) {
3025
3214
  if live.isEmpty { Text("작업 중인 세션이 없습니다").font(.system(size: 12)).foregroundColor(pal.text2) }
3026
- ForEach(live) { s in
3027
- let ph = model.phase(s), tint = pal.state(ph), mark = stateMark(s)
3028
- let byLoad = ph == .active && s.state != "busy" && s.state != "shell" && s.subagents == 0
3029
- let pending = (s.detail?.recent ?? []).last { $0.pending == true }
3030
- Pressable(radius: 8, action: { selected = s.pid }) {
3031
- VStack(alignment: .leading, spacing: 6) {
3032
- HStack(spacing: 6) {
3033
- if ph == .active { LiveDot(color: tint) } else { Image(systemName: mark.symbol).font(.system(size: 11)).foregroundColor(tint).frame(width: 12) }
3034
- Text(s.name ?? s.agent).font(.system(size: 12.5, weight: .semibold)).foregroundColor(pal.text).lineLimit(1).truncationMode(.middle)
3035
- Spacer(minLength: 4)
3036
- Text(byLoad ? "프로그램 실행 중" : "\(mark.label) \(sinceText(s.stateSince, now: snap.at))").font(.system(size: 11)).foregroundColor(pal.text2).lineLimit(1).fixedSize()
3037
- }
3038
- if let p = pending {
3039
- HStack(alignment: .top, spacing: 6) {
3040
- Image(systemName: toolSymbol(p.tool)).font(.system(size: 10)).foregroundColor(pal.text2).frame(width: 12, height: 14)
3041
- Text((p.target ?? "").isEmpty ? toolName(p.tool) : (p.target ?? "")).font(.system(size: 11.5)).foregroundColor(pal.text).lineLimit(2).fixedSize(horizontal: false, vertical: true)
3042
- }
3043
- }
3044
- ForEach(Array(model.working(s, max: 3).enumerated()), id: \.offset) { _, it in
3045
- VStack(alignment: .leading, spacing: 2) {
3046
- HStack(spacing: 6) {
3047
- Image(systemName: "gearshape.2.fill").font(.system(size: 9.5)).foregroundColor(pal.text2).frame(width: 12)
3048
- Text(it.name).font(.system(size: 11.5, weight: .medium)).foregroundColor(pal.text).lineLimit(1).truncationMode(.middle).help(it.name)
3049
- }
3050
- stats(it.w, pal).padding(.leading, 18)
3051
- }
3052
- }
3053
- let subs = subsOf(s)
3054
- if !subs.isEmpty {
3055
- HStack(spacing: 6) {
3056
- Image(systemName: "arrow.turn.down.right").font(.system(size: 9.5, weight: .semibold)).foregroundColor(pal.text2).frame(width: 12)
3057
- Text("띄운 세션 \(subs.count)개").font(.system(size: 11.5)).foregroundColor(pal.text)
3058
- Spacer(minLength: 4)
3059
- Text("작업 중 \(subs.filter { model.phase($0) == .active }.count)").font(.system(size: 11, weight: .medium)).monospacedDigit().foregroundColor(pal.text)
3060
- }
3061
- }
3062
- }.padding(10).frame(maxWidth: .infinity, alignment: .leading).background(RoundedRectangle(cornerRadius: 8).fill(pal.well.opacity(0.55)))
3063
- }
3064
- }
3215
+ ForEach(live) { s in liveRow(s, snap, pal, subs: subsOf(s), dense: dense, pick: pick) }
3065
3216
  if !idle.isEmpty {
3066
3217
  Text("입력 대기").font(.system(size: 11)).foregroundColor(pal.text2).padding(.top, 4)
3067
- ForEach(idle) { s in
3068
- Pressable(radius: 6, action: { selected = s.pid }) {
3069
- HStack(spacing: 6) {
3070
- Image(systemName: "pause.circle").font(.system(size: 11)).foregroundColor(pal.text2).frame(width: 12)
3071
- Text(s.name ?? s.agent).font(.system(size: 12)).foregroundColor(pal.text2).lineLimit(1).truncationMode(.middle)
3072
- Spacer(minLength: 4)
3073
- Text(sinceText(s.stateSince, now: snap.at)).font(.system(size: 10.5)).foregroundColor(pal.text2)
3074
- }.padding(.vertical, 5).padding(.horizontal, 10).frame(maxWidth: .infinity, alignment: .leading)
3075
- }
3076
- }
3218
+ ForEach(idle) { s in idleRow(s, snap, pal, dense: dense, pick: pick) }
3077
3219
  }
3078
3220
  if model.leftover.n > 0 {
3079
3221
  HStack(spacing: 6) {
3080
3222
  Image(systemName: "moon.zzz.fill").font(.system(size: 11)).foregroundColor(pal.left).frame(width: 12)
3081
3223
  Text("끝난 세션이 남긴 프로세스 \(model.leftover.n)개").font(.system(size: 11.5)).foregroundColor(pal.text)
3082
3224
  Spacer(minLength: 4)
3083
- Text("\(pct1(model.leftover.cpu * 100)), \(memText(model.leftover.mem))").font(.system(size: 11, weight: .medium)).monospacedDigit().foregroundColor(pal.text)
3225
+ Text("\(pct1(model.leftover.cpu * 100)), \(memText(model.leftover.mem))").font(.system(size: 11, weight: .medium)).monospacedDigit().foregroundColor(pal.text).fixedSize()
3084
3226
  }.padding(.top, 6).padding(.horizontal, 10)
3085
3227
  }
3228
+ }.frame(maxWidth: .infinity, alignment: .topLeading)
3229
+ }
3230
+ /** 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. */
3231
+ func nowColumn(_ snap: Snapshot, _ pal: Pal) -> some View {
3232
+ let body = VStack(alignment: .leading, spacing: 10) {
3233
+ Text("지금 도는 것").font(.system(size: 15, weight: .semibold)).foregroundColor(pal.text)
3234
+ nowList(snap, pal, dense: false, pick: { selected = $0.pid })
3086
3235
  Divider().padding(.vertical, 4)
3087
3236
  trends(pal)
3088
3237
  }.padding(14).frame(width: 372, alignment: .topLeading)
3089
3238
  return Group { if still { body } else { ScrollView { body } } }
3090
3239
  }
3091
- func content(_ width: CGFloat) -> some View {
3092
- let pal = Pal(dark: scheme == .dark)
3240
+ /** What scrolls under the band: the machine detail when it is open, then the project groups. */
3241
+ func scrollRegion(_ snap: Snapshot, _ pal: Pal, inner: CGFloat) -> some View {
3242
+ let body = VStack(alignment: .leading, spacing: 12) {
3243
+ if showDetail {
3244
+ machine(snap, pal, width: inner)
3245
+ if model.gpu != nil { gpuCard(snap, pal) }
3246
+ }
3247
+ if snap.sessions.isEmpty { Text("실행 중인 세션이 없습니다").font(.system(size: 13)).foregroundColor(pal.text2).padding(.top, 20).frame(maxWidth: .infinity) } else { groupsView(snap, pal, width: inner) }
3248
+ }
3249
+ return Group { if still { body } else { ScrollView { body } } }
3250
+ }
3251
+ /** The band, the warnings and the scroll region. The band and the warnings stay put while the rest scrolls. */
3252
+ func leftColumn(_ pal: Pal, inner: CGFloat) -> some View {
3253
+ VStack(alignment: .leading, spacing: 12) {
3254
+ if let snap = model.snap {
3255
+ band(snap, pal)
3256
+ if let ws = snap.warnings, !ws.isEmpty { warnChips(ws, pal) }
3257
+ if snap.sessions.isEmpty && !showDetail { Text("실행 중인 세션이 없습니다").font(.system(size: 13)).foregroundColor(pal.text2).frame(maxWidth: .infinity, maxHeight: .infinity) }
3258
+ else { scrollRegion(snap, pal, inner: inner) }
3259
+ } else {
3260
+ Text(model.failure ?? "불러오는 중입니다").font(.system(size: 13)).foregroundColor(pal.text2).frame(maxWidth: .infinity, maxHeight: .infinity)
3261
+ }
3262
+ }.padding(.horizontal, 18).padding(.bottom, 18).padding(.top, still ? 12 : TITLE_BAR + 10).frame(maxWidth: .infinity, maxHeight: still ? nil : .infinity, alignment: .topLeading)
3263
+ }
3264
+ /** Wide: the left column and a 372 point column on the right that holds what is running now, or the picked session. */
3265
+ func largeLayout(_ pal: Pal, width: CGFloat) -> some View {
3093
3266
  let open = selected.flatMap { pid in model.snap?.sessions.first { $0.pid == pid } }
3094
- let inner = max(318, width - 372 - 36)
3095
3267
  return HStack(alignment: .top, spacing: 0) {
3096
- VStack(alignment: .leading, spacing: 12) {
3097
- if let snap = model.snap {
3098
- machine(snap, pal, width: inner)
3099
- kpis(snap, pal, width: inner)
3100
- if let ws = snap.warnings, !ws.isEmpty {
3101
- HStack(spacing: 8) {
3102
- ForEach(ws) { w in
3103
- HStack(spacing: 6) {
3104
- Image(systemName: w.level == "critical" ? "exclamationmark.octagon.fill" : "exclamationmark.triangle.fill").font(.system(size: 11)).foregroundColor(w.level == "critical" ? pal.critical : pal.warning)
3105
- Text(w.chip.replacingOccurrences(of: "⚠ ", with: "").replacingOccurrences(of: "🚨 ", with: "")).font(.system(size: 12, weight: .medium)).foregroundColor(pal.text)
3106
- }.padding(.horizontal, 9).padding(.vertical, 5).background(Capsule().fill(pal.tile)).help(w.advice?.first?.tip ?? w.advice?.first?.title ?? "")
3107
- }
3108
- Spacer(minLength: 0)
3268
+ leftColumn(pal, inner: max(318, width - 372 - 36))
3269
+ if let snap = model.snap {
3270
+ Group { if let s = open { inspector(s, snap, pal) } else { nowColumn(snap, pal) } }.padding(.top, still ? 0 : TITLE_BAR + 10).frame(width: 372, alignment: .top)
3271
+ }
3272
+ }.background(alignment: .topTrailing) { Rectangle().fill(pal.tile).frame(width: 372) }
3273
+ }
3274
+ /** Middle: no right column. A picked session's detail lies over the trailing edge, so nothing under it moves when it opens or closes. */
3275
+ func mediumLayout(_ pal: Pal, width: CGFloat) -> some View {
3276
+ let open = selected.flatMap { pid in model.snap?.sessions.first { $0.pid == pid } }
3277
+ return ZStack(alignment: .topTrailing) {
3278
+ leftColumn(pal, inner: width - 36)
3279
+ if let s = open, let snap = model.snap {
3280
+ inspector(s, snap, pal).padding(.top, still ? 0 : TITLE_BAR + 10).frame(width: 372).frame(maxHeight: still ? nil : .infinity, alignment: .top)
3281
+ .background(pal.tile).shadow(color: Color.black.opacity(pal.dark ? 0.5 : 0.2), radius: 10, x: -4, y: 0)
3282
+ }
3283
+ }
3284
+ }
3285
+ func metric(_ label: String, _ value: String, _ pal: Pal, color: Color? = nil) -> some View {
3286
+ HStack(spacing: 3) {
3287
+ Text(label).font(.system(size: 10.5)).foregroundColor(pal.text2)
3288
+ Text(value).font(.system(size: 11, weight: .medium)).monospacedDigit().foregroundColor(color ?? pal.text)
3289
+ }.lineLimit(1).fixedSize()
3290
+ }
3291
+ /** The machine figures and the account limits on one line, the limits dropped one by one when the width runs out. */
3292
+ func metricsLine(_ snap: Snapshot, _ pal: Pal, limits: Int) -> some View {
3293
+ let wins = Array((snap.usage?.claude?.windows ?? []).prefix(limits))
3294
+ return HStack(spacing: 10) {
3295
+ metric("CPU", pct1(cpuSplit(snap, pal).total), pal)
3296
+ metric("메모리", memText(memSplit(snap, pal).total), pal)
3297
+ if model.gpu != nil { metric("GPU", pct1(gpuSplit(snap, pal).total), pal) }
3298
+ ForEach(wins, id: \.key) { w in metric("\(windowName(w)) 한도", "\(Int(w.usedPct.rounded()))%", pal, color: severity(w.usedPct, pal.text, pal).color) }
3299
+ Spacer(minLength: 0)
3300
+ }
3301
+ }
3302
+ func miniHeader(_ snap: Snapshot, _ pal: Pal) -> some View {
3303
+ let n = counts(snap)
3304
+ return VStack(alignment: .leading, spacing: 5) {
3305
+ HStack(spacing: 6) {
3306
+ if n.active > 0 { LiveDot(color: pal.good) }
3307
+ Text("작업 중 \(n.active)").font(.system(size: 15, weight: .semibold)).foregroundColor(pal.text).fixedSize()
3308
+ Text("/ \(n.mains)").font(.system(size: 12)).foregroundColor(pal.text2).fixedSize()
3309
+ Spacer(minLength: 6)
3310
+ if n.user > 0 { chip("hand.raised.fill", pal.warning, "확인 대기 \(n.user)", pal) }
3311
+ if n.idle > 0 { chip("pause.circle", pal.text2, "입력 대기 \(n.idle)", pal) }
3312
+ }
3313
+ ViewThatFits(in: .horizontal) {
3314
+ metricsLine(snap, pal, limits: 4)
3315
+ metricsLine(snap, pal, limits: 1)
3316
+ metricsLine(snap, pal, limits: 0)
3317
+ }
3318
+ }.padding(.horizontal, 12).padding(.top, still ? 10 : TITLE_BAR + 6).padding(.bottom, 8)
3319
+ }
3320
+ /** Narrow: one column of sessions on the tile colour, a header with the counts and the machine, and every session as a row. */
3321
+ func miniLayout(_ pal: Pal) -> some View {
3322
+ VStack(alignment: .leading, spacing: 0) {
3323
+ if let snap = model.snap {
3324
+ miniHeader(snap, pal)
3325
+ if let ws = snap.warnings, !ws.isEmpty {
3326
+ VStack(alignment: .leading, spacing: 4) {
3327
+ ForEach(ws) { w in
3328
+ HStack(alignment: .top, spacing: 6) {
3329
+ warnIcon(w, pal).frame(height: 15)
3330
+ Text(warnText(w)).font(.system(size: 12, weight: .medium)).foregroundColor(pal.text).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true)
3331
+ Spacer(minLength: 0)
3332
+ }.help(w.advice?.first?.tip ?? w.advice?.first?.title ?? "")
3109
3333
  }
3110
- }
3111
- if snap.sessions.isEmpty { Text("실행 중인 세션이 없습니다").font(.system(size: 13)).foregroundColor(pal.text2).frame(maxWidth: .infinity, maxHeight: .infinity) }
3112
- else if still { groupsView(snap, pal, width: inner) } else { ScrollView { groupsView(snap, pal, width: inner) } }
3113
- } else {
3114
- Text(model.failure ?? "불러오는 중입니다").font(.system(size: 13)).foregroundColor(pal.text2).frame(maxWidth: .infinity, maxHeight: .infinity)
3334
+ }.padding(.horizontal, 12).padding(.bottom, 8)
3115
3335
  }
3116
- }.padding(.horizontal, 18).padding(.bottom, 18).padding(.top, 38).frame(maxWidth: .infinity, maxHeight: still ? nil : .infinity, alignment: .topLeading)
3117
- if let snap = model.snap {
3118
- Group { if let s = open { inspector(s, snap, pal) } else { nowColumn(snap, pal) } }.padding(.top, still ? 0 : 28).frame(width: 372, alignment: .top)
3336
+ Divider()
3337
+ let list = nowList(snap, pal, dense: true, pick: { jump(to: $0) }).padding(10)
3338
+ if still { list } else { ScrollView { list } }
3339
+ } else {
3340
+ Text(model.failure ?? "불러오는 중입니다").font(.system(size: 13)).foregroundColor(pal.text2).padding(.top, still ? 10 : TITLE_BAR + 6).padding(.horizontal, 12).frame(maxWidth: .infinity, maxHeight: .infinity)
3341
+ }
3342
+ }.frame(maxWidth: .infinity, maxHeight: still ? nil : .infinity, alignment: .topLeading).background(pal.tile)
3343
+ }
3344
+ func content(_ width: CGFloat) -> some View {
3345
+ let pal = Pal(dark: scheme == .dark)
3346
+ let mode = DashSize.of(width)
3347
+ return Group {
3348
+ switch mode {
3349
+ case .large: largeLayout(pal, width: width)
3350
+ case .medium: mediumLayout(pal, width: width)
3351
+ case .mini: miniLayout(pal)
3119
3352
  }
3120
- }.frame(minWidth: 1060, maxWidth: .infinity, minHeight: 420, maxHeight: still ? nil : .infinity, alignment: .topLeading)
3121
- .background(alignment: .topTrailing) { Rectangle().fill(pal.tile).frame(width: 372) }.background(pal.surface)
3353
+ }.frame(minWidth: mode == .large ? 1100 : mode == .medium ? 620 : 300, maxWidth: .infinity, minHeight: 200, maxHeight: still ? nil : .infinity, alignment: .topLeading)
3354
+ .background(pal.surface)
3122
3355
  }
3123
3356
  var body: some View {
3124
- if still { content(stillWidth) } else { GeometryReader { g in content(g.size.width) } }
3357
+ if still { content(stillWidth) } else { GeometryReader { g in content(g.size.width) }.ignoresSafeArea() }
3125
3358
  }
3126
3359
  }
3127
3360
  /** The animal is a rank, so the rank is said beside it: which species, where in the company, and what comes next. */
@@ -3376,7 +3609,7 @@ func dockIcon(_ grade: String?) -> NSImage {
3376
3609
  }
3377
3610
  }
3378
3611
  /** The few menu commands a window needs once the app is a regular one: close, minimise, quit. */
3379
- func dashboardMenu() -> NSMenu {
3612
+ func dashboardMenu(_ app: App) -> NSMenu {
3380
3613
  let bar = NSMenu()
3381
3614
  let appItem = NSMenuItem(), appMenu = NSMenu()
3382
3615
  appMenu.addItem(NSMenuItem(title: "Sprag 끝내기", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))
@@ -3384,9 +3617,20 @@ func dashboardMenu() -> NSMenu {
3384
3617
  let winItem = NSMenuItem(), winMenu = NSMenu(title: "윈도우")
3385
3618
  winMenu.addItem(NSMenuItem(title: "닫기", action: #selector(NSWindow.performClose(_:)), keyEquivalent: "w"))
3386
3619
  winMenu.addItem(NSMenuItem(title: "최소화", action: #selector(NSWindow.performMiniaturize(_:)), keyEquivalent: "m"))
3620
+ winMenu.addItem(.separator())
3621
+ for (title, key, action) in [("작게", "1", #selector(App.dashMini)), ("중간", "2", #selector(App.dashMedium)), ("크게", "3", #selector(App.dashLarge)), ("항상 위에 두기", "", #selector(App.dashPinMenu))] {
3622
+ let it = NSMenuItem(title: title, action: action, keyEquivalent: key); it.target = app; winMenu.addItem(it)
3623
+ }
3387
3624
  winItem.submenu = winMenu; bar.addItem(winItem)
3388
3625
  return bar
3389
3626
  }
3627
+ extension App: NSMenuItemValidation {
3628
+ /** The checkmark of "항상 위에 두기" follows the pin, whichever of the two controls changed it. */
3629
+ func validateMenuItem(_ item: NSMenuItem) -> Bool {
3630
+ if item.action == #selector(App.dashPinMenu) { item.state = dashUI.pinned ? .on : .off }
3631
+ return true
3632
+ }
3633
+ }
3390
3634
  extension App: NSApplicationDelegate {
3391
3635
  /** A click on the Dock icon: show the dashboard again, wherever it went. */
3392
3636
  func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { showDashboard(); return false }
@@ -3403,6 +3647,7 @@ final class App: NSObject {
3403
3647
  var frame = 0
3404
3648
  var outside: Any?, keys: Any?
3405
3649
  var dash: NSWindow?
3650
+ let dashUI = DashUI()
3406
3651
  var isOpen: Bool { panel.isVisible }
3407
3652
  var dashOpen: Bool { dash?.isVisible == true }
3408
3653
  /** Each session's work is asked for only while something that shows it is on screen. */
@@ -3417,22 +3662,60 @@ final class App: NSObject {
3417
3662
  if dash == nil {
3418
3663
  let room = NSScreen.main?.visibleFrame.size ?? NSSize(width: 1480, height: 900)
3419
3664
  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)
3420
- w.title = "Sprag 대시보드"; w.isReleasedWhenClosed = false; w.titlebarAppearsTransparent = true; w.minSize = NSSize(width: 1060, height: 560)
3665
+ w.title = "Sprag 대시보드"; w.isReleasedWhenClosed = false; w.titlebarAppearsTransparent = true; w.minSize = NSSize(width: 300, height: 200)
3421
3666
  // A plain surface, not a see-through material: the chart colours were checked against this one.
3422
3667
  w.contentView = NSHostingView(rootView: DashboardView(model: model)); w.center()
3668
+ // The last size and place come back next time. The self-test keeps the default frame and leaves the user's saved one alone.
3669
+ if selftest == nil { w.setFrameUsingName("SpragDashboard"); w.setFrameAutosaveName("SpragDashboard"); dashUI.pinned = UserDefaults.standard.bool(forKey: "dashPinned") }
3670
+ w.level = dashUI.pinned ? .floating : .normal
3671
+ let controls = NSHostingView(rootView: DashControls(ui: dashUI, pick: { [weak self] in self?.setDashSize($0) }, pin: { [weak self] in self?.toggleDashPin() }))
3672
+ controls.frame.size = NSSize(width: controls.fittingSize.width, height: 28)
3673
+ let accessory = NSTitlebarAccessoryViewController(); accessory.view = controls; accessory.layoutAttribute = .right
3674
+ w.addTitlebarAccessoryViewController(accessory)
3675
+ NotificationCenter.default.addObserver(forName: NSWindow.didResizeNotification, object: w, queue: .main) { [weak self] _ in self?.syncDashSize() }
3423
3676
  NotificationCenter.default.addObserver(forName: NSWindow.willCloseNotification, object: w, queue: .main) { [weak self] _ in DispatchQueue.main.async { self?.syncDetail(); NSApp.setActivationPolicy(.accessory) } }
3424
3677
  dash = w
3678
+ syncDashSize()
3425
3679
  }
3426
3680
  // A menu bar app has no Dock icon, so a dashboard that slipped behind other windows could only be found through the
3427
3681
  // 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.
3428
3682
  NSApp.setActivationPolicy(.regular)
3429
3683
  dockGrade = model.snap?.animal?.grade; NSApp.applicationIconImage = dockIcon(dockGrade)
3430
- if NSApp.mainMenu == nil { NSApp.mainMenu = dashboardMenu() }
3684
+ if NSApp.mainMenu == nil { NSApp.mainMenu = dashboardMenu(self) }
3431
3685
  NSApp.activate(ignoringOtherApps: true)
3432
3686
  if dash?.isMiniaturized == true { dash?.deminiaturize(nil) }
3433
3687
  dash?.makeKeyAndOrderFront(nil)
3434
3688
  syncDetail()
3435
3689
  }
3690
+ /** The control and the title follow the window's real width, so a dragged edge and a pressed preset end up the same. */
3691
+ func syncDashSize() {
3692
+ guard let w = dash, let v = w.contentView else { return }
3693
+ let s = DashSize.of(v.bounds.width)
3694
+ if dashUI.size != s { dashUI.size = s }
3695
+ let title: NSWindow.TitleVisibility = s == .mini ? .hidden : .visible // the narrow title bar belongs to the controls
3696
+ if w.titleVisibility != title { w.titleVisibility = title }
3697
+ }
3698
+ /** Resize the window to one of the three layouts. The top edge stays, the side nearer the screen edge stays, and the result is kept on screen. */
3699
+ func setDashSize(_ s: DashSize, animate: Bool = true) {
3700
+ guard let w = dash else { return }
3701
+ let vis = (w.screen ?? NSScreen.main)?.visibleFrame ?? NSRect(x: 0, y: 0, width: 1480, height: 900)
3702
+ let size: NSSize = s == .mini ? NSSize(width: 340, height: 480) : s == .medium ? NSSize(width: 780, height: 680) : NSSize(width: min(1480, vis.width - 40), height: min(900, vis.height - 60))
3703
+ let now = w.frame
3704
+ var f = NSRect(x: now.midX > vis.midX ? now.maxX - size.width : now.minX, y: now.maxY - size.height, width: size.width, height: size.height)
3705
+ f.size.width = min(f.width, vis.width); f.size.height = min(f.height, vis.height)
3706
+ f.origin.x = max(vis.minX, min(f.origin.x, vis.maxX - f.width)); f.origin.y = max(vis.minY, min(f.origin.y, vis.maxY - f.height))
3707
+ w.setFrame(f, display: true, animate: animate)
3708
+ }
3709
+ /** Keep the dashboard above other windows, and remember that for the next start. */
3710
+ @objc func toggleDashPin() {
3711
+ dashUI.pinned.toggle()
3712
+ dash?.level = dashUI.pinned ? .floating : .normal
3713
+ if selftest == nil { UserDefaults.standard.set(dashUI.pinned, forKey: "dashPinned") }
3714
+ }
3715
+ @objc func dashMini() { setDashSize(.mini) }
3716
+ @objc func dashMedium() { setDashSize(.medium) }
3717
+ @objc func dashLarge() { setDashSize(.large) }
3718
+ @objc func dashPinMenu() { toggleDashPin() }
3436
3719
  func start() {
3437
3720
  panel = FloatPanel(contentRect: NSRect(x: 0, y: 0, width: 408, height: 300), styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: true)
3438
3721
  panel.isOpaque = false; panel.backgroundColor = .clear; panel.hasShadow = true; panel.level = .popUpMenu
@@ -3757,6 +4040,31 @@ func sessionTest(_ prefix: String) {
3757
4040
  fflush(stdout); dashboardTest(prefix)
3758
4041
  }
3759
4042
  }
4043
+ /**
4044
+ * Put the real window through its three sizes, as a press on the title bar would: after each one the layout the width picks
4045
+ * and the control have to agree with the size asked for, the frame has to be on the screen, and the content is captured.
4046
+ * Then the pin: the window must float after one press, and goes back to normal after the second.
4047
+ */
4048
+ func dashSizeTest(_ prefix: String, done: @escaping () -> Void) {
4049
+ var todo = DashSize.allCases
4050
+ func next() {
4051
+ guard !todo.isEmpty else {
4052
+ main.toggleDashPin(); print("DASHPIN floating after toggle: \(main.dash?.level == .floating)"); main.toggleDashPin()
4053
+ fflush(stdout); done(); return
4054
+ }
4055
+ let s = todo.removeFirst()
4056
+ main.setDashSize(s, animate: false)
4057
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
4058
+ if let w = main.dash, let v = w.contentView {
4059
+ let vis = (w.screen ?? NSScreen.main)?.visibleFrame ?? .zero
4060
+ print("DASHSIZE \(s.rawValue) window \(Int(w.frame.width))x\(Int(w.frame.height)) | layout \(DashSize.of(v.bounds.width).rawValue) | control \(main.dashUI.size.rawValue) | inside screen \(vis.contains(w.frame))")
4061
+ liveShot(v, "\(prefix)-dashboard-live-\(s.rawValue).png")
4062
+ }
4063
+ next()
4064
+ }
4065
+ }
4066
+ next()
4067
+ }
3760
4068
  func dashboardTest(_ prefix: String) {
3761
4069
  main.showDashboard()
3762
4070
  DispatchQueue.main.asyncAfter(deadline: .now() + 4.0) {
@@ -3768,6 +4076,10 @@ func dashboardTest(_ prefix: String) {
3768
4076
  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: " | ")))
3769
4077
  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: " | "))
3770
4078
  render(DashboardView(model: m, still: true).frame(width: 1480), "\(prefix)-dashboard-dark.png")
4079
+ render(DashboardView(model: m, still: true, width: 340).frame(width: 340), "\(prefix)-dashboard-mini-dark.png")
4080
+ render(DashboardView(model: m, still: true, width: 780).frame(width: 780), "\(prefix)-dashboard-medium-dark.png")
4081
+ if let first = m.snap?.sessions.first { render(DashboardView(model: m, still: true, preselect: first.pid, width: 780).frame(width: 780), "\(prefix)-dashboard-medium-open-dark.png") }
4082
+ render(DashboardView(model: m, still: true, detail: true).frame(width: 1480), "\(prefix)-dashboard-detail-dark.png")
3771
4083
  render(DashboardView(model: m, still: true).frame(width: 1480), "\(prefix)-dashboard-light.png", dark: false)
3772
4084
  if let first = m.snap?.sessions.first { render(DashboardView(model: m, still: true, lit: first.pid).frame(width: 1480), "\(prefix)-dashboard-hover-dark.png") }
3773
4085
  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: "; "))
@@ -3785,18 +4097,20 @@ func dashboardTest(_ prefix: String) {
3785
4097
  render(DashboardView(model: m, still: true, cleaning: true).frame(width: 1480), "\(prefix)-dashboard-clean-dark.png")
3786
4098
  print("DASHBOARD history samples \(m.samples.count) per-session \(m.hist.values.map { $0.count }.sorted())")
3787
4099
  if let v = main.dash?.contentView { liveShot(v, "\(prefix)-dashboard-live.png") }
3788
- 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: ", "))")
3789
- // which session each line would reopen, and the folder that session worked in (the id itself is not printed)
3790
- print("LEFTOVER sessions " + m.leftoverItems.map { it in "\(it.name)=" + (m.leftoverSession[it.id].map { sessionCwd($0).map { ($0 as NSString).lastPathComponent } ?? "no transcript" } ?? "none") }.joined(separator: ", "))
3791
- if let target = selftestClean {
3792
- let hit = m.leftoverItems.first { $0.name == target }
3793
- print("CLEAN target '\(target)': \(hit.map { "\($0.n) process(es)" } ?? "not listed") | protected \(m.leftoverShared.contains(target))")
3794
- print("CLEAN signals sent: \(m.stopLeftovers([target]))")
3795
- }
3796
- main.dash?.close()
3797
- DispatchQueue.main.asyncAfter(deadline: .now() + (selftestClean == nil ? 0.6 : 6.0)) {
3798
- if let target = selftestClean { print("CLEAN afterwards: '\(target)' \(m.leftoverItems.contains { $0.name == target } ? "still listed" : "gone") | leftover lines \(m.leftoverItems.count)") }
3799
- print("DASHBOARD closed, asked for detail \(m.wantDetail) | back to a menu bar app \(NSApp.activationPolicy() == .accessory)"); fflush(stdout); NSApp.terminate(nil)
4100
+ dashSizeTest(prefix) {
4101
+ 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: ", "))")
4102
+ // which session each line would reopen, and the folder that session worked in (the id itself is not printed)
4103
+ print("LEFTOVER sessions " + m.leftoverItems.map { it in "\(it.name)=" + (m.leftoverSession[it.id].map { sessionCwd($0).map { ($0 as NSString).lastPathComponent } ?? "no transcript" } ?? "none") }.joined(separator: ", "))
4104
+ if let target = selftestClean {
4105
+ let hit = m.leftoverItems.first { $0.name == target }
4106
+ print("CLEAN target '\(target)': \(hit.map { "\($0.n) process(es)" } ?? "not listed") | protected \(m.leftoverShared.contains(target))")
4107
+ print("CLEAN signals sent: \(m.stopLeftovers([target]))")
4108
+ }
4109
+ main.dash?.close()
4110
+ DispatchQueue.main.asyncAfter(deadline: .now() + (selftestClean == nil ? 0.6 : 6.0)) {
4111
+ if let target = selftestClean { print("CLEAN afterwards: '\(target)' \(m.leftoverItems.contains { $0.name == target } ? "still listed" : "gone") | leftover lines \(m.leftoverItems.count)") }
4112
+ print("DASHBOARD closed, asked for detail \(m.wantDetail) | back to a menu bar app \(NSApp.activationPolicy() == .accessory)"); fflush(stdout); NSApp.terminate(nil)
4113
+ }
3800
4114
  }
3801
4115
  }
3802
4116
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.135.0",
3
+ "version": "3.136.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/bar-app.js CHANGED
@@ -14,7 +14,7 @@
14
14
 
15
15
  import * as childProcess from 'node:child_process';
16
16
  import {
17
- chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync,
17
+ chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync,
18
18
  } from 'node:fs';
19
19
  import { createRequire } from 'node:module';
20
20
  import { createHash } from 'node:crypto';
@@ -35,6 +35,8 @@ export const LOCK_STALE_MS = 10 * 60 * 1000;
35
35
  /** A failed build of this source is not retried at session start for this long. */
36
36
  export const BUILD_RETRY_MS = 24 * 60 * 60 * 1000;
37
37
  const BUILD_TIMEOUT_MS = 5 * 60 * 1000;
38
+ /** Compile errors that a second try fixes. A build that failed this way is not held back for a day. */
39
+ const TRANSIENT_ERROR = /was modified during the build/i;
38
40
  const ERROR_TAIL = 600;
39
41
  const BINARY_NAME = 'sprag-bar';
40
42
 
@@ -213,16 +215,35 @@ export function buildBar(deps = {}) {
213
215
  const folder = join(paths.dir, paths.version);
214
216
  mkdirSync(folder, { recursive: true, mode: 0o700 });
215
217
  const tmp = `${paths.binary}.tmp-${process.pid}`;
216
- // The compiler inside the toolchain cannot find the SDK when run by its full path ("unable to load standard
217
- // library"). /usr/bin/swiftc is the system's front door to the same compiler and sets the SDK up. Running it is
218
- // safe here: findSwiftc has just confirmed developer tools are installed, so it cannot pop the install dialog.
219
- const compiler = existsOf(deps)('/usr/bin/swiftc') ? '/usr/bin/swiftc' : swiftc;
220
- const r = runOf(deps)(compiler, ['-O', '-swift-version', '5', deps.source ?? BAR_SOURCE, '-o', tmp], {
221
- timeout: BUILD_TIMEOUT_MS, stdio: 'pipe', windowsHide: true, maxBuffer: 16 * 1024 * 1024,
222
- });
218
+ // swiftc reads a copy of the source. `npm install -g` of the same version rewrites the package's
219
+ // SpragBar.swift with the same bytes and a new mtime, and swiftc fails a build whose input changed while it
220
+ // ran ("was modified during the build"). The copy sits in its own folder so it keeps its file name.
221
+ const srcDir = join(folder, `src-${process.pid}`);
222
+ const srcCopy = join(srcDir, basename(BAR_SOURCE));
223
223
  let error = null;
224
- if (r.error) error = r.error.code === 'ETIMEDOUT' ? 'timeout after 5 minutes' : String(r.error.message ?? r.error);
225
- else if (r.status !== 0) error = String(r.stderr ?? '').trim().slice(-ERROR_TAIL) || `swiftc exited with status ${r.status}`;
224
+ let transient = false;
225
+ try {
226
+ rmSync(srcDir, { recursive: true, force: true });
227
+ mkdirSync(srcDir, { recursive: true, mode: 0o700 });
228
+ copyFileSync(deps.source ?? BAR_SOURCE, srcCopy);
229
+ } catch (e) {
230
+ // The package folder can be missing for a moment while npm swaps it, so the next session tries again.
231
+ error = `could not copy the source: ${String(e?.message ?? e)}`;
232
+ transient = true;
233
+ }
234
+ if (!error) {
235
+ // The compiler inside the toolchain cannot find the SDK when run by its full path ("unable to load standard
236
+ // library"). /usr/bin/swiftc is the system's front door to the same compiler and sets the SDK up. Running it is
237
+ // safe here: findSwiftc has just confirmed developer tools are installed, so it cannot pop the install dialog.
238
+ const compiler = existsOf(deps)('/usr/bin/swiftc') ? '/usr/bin/swiftc' : swiftc;
239
+ const r = runOf(deps)(compiler, ['-O', '-swift-version', '5', srcCopy, '-o', tmp], {
240
+ timeout: BUILD_TIMEOUT_MS, stdio: 'pipe', windowsHide: true, maxBuffer: 16 * 1024 * 1024,
241
+ });
242
+ if (r.error) error = r.error.code === 'ETIMEDOUT' ? 'timeout after 5 minutes' : String(r.error.message ?? r.error);
243
+ else if (r.status !== 0) error = String(r.stderr ?? '').trim().slice(-ERROR_TAIL) || `swiftc exited with status ${r.status}`;
244
+ if (error && TRANSIENT_ERROR.test(error)) transient = true;
245
+ }
246
+ try { rmSync(srcDir, { recursive: true, force: true }); } catch { /* a stray copy is only disk space */ }
226
247
  if (!error) {
227
248
  try {
228
249
  renameSync(tmp, paths.binary);
@@ -236,9 +257,9 @@ export function buildBar(deps = {}) {
236
257
  error = error.slice(-ERROR_TAIL);
237
258
  }
238
259
  const ms = clock() - started;
239
- writeBuildState(paths, { version: paths.version, ok: !error, at: clock(), ms, error });
260
+ writeBuildState(paths, { version: paths.version, ok: !error, at: clock(), ms, error, ...(transient ? { transient: true } : {}) });
240
261
  if (!error) pruneOtherVersions(paths);
241
- return { ok: !error, ms, error };
262
+ return { ok: !error, ms, error, ...(transient ? { transient: true } : {}) };
242
263
  } finally {
243
264
  try { rmSync(paths.buildLock, { force: true }); } catch { /* a stale lock expires by itself */ }
244
265
  }
@@ -278,6 +299,31 @@ export function launchBar(deps = {}) {
278
299
  child.unref();
279
300
  }
280
301
 
302
+ /**
303
+ * Whether the recorded build state keeps session start from compiling this build.
304
+ * A compile that failed is not retried for a day. A missing toolchain is looked for again every time: the check
305
+ * costs one short command, and installing the tools should bring the app at the next session. A transient failure
306
+ * (the source changed or vanished while a reinstall of the package rewrote it) is tried again at the next session.
307
+ */
308
+ function buildHeldBack(state, version, now) {
309
+ return Boolean(state && state.version === version && state.ok === false && state.error !== 'no-toolchain'
310
+ && state.transient !== true && Number.isFinite(state.at) && now - state.at < BUILD_RETRY_MS);
311
+ }
312
+
313
+ /**
314
+ * The line a session start prints when a failed compile holds the app back, or null when nothing does.
315
+ * Without it the only place the failure shows is `sprag bar status`, which nobody opens while the app is missing.
316
+ */
317
+ export function barBuildBlockedNotice({ lang = 'en', now = Date.now(), ...deps } = {}) {
318
+ const paths = barPaths(deps);
319
+ const state = readBuildState(deps);
320
+ if (!buildHeldBack(state, paths.version, now)) return null;
321
+ const hours = Math.max(1, Math.ceil((state.at + BUILD_RETRY_MS - now) / 3_600_000));
322
+ return lang === 'ko'
323
+ ? `✇ [sprag] Sprag Bar 컴파일이 실패해서 앞으로 ${hours}시간 동안 세션을 시작해도 다시 컴파일하지 않습니다. 지금 다시 하려면 \`sprag bar build --then-launch\` 를 실행하십시오. 오류는 \`sprag bar status\` 에 나옵니다. 사용자에게 이 내용을 한 줄로 알리십시오.`
324
+ : `✇ [sprag] The Sprag Bar compile failed, so sessions will not compile it again for the next ${hours}h. Run \`sprag bar build --then-launch\` to try now; \`sprag bar status\` shows the error. Tell the user this in one line.`;
325
+ }
326
+
281
327
  /**
282
328
  * Session start: make sure the app is running, building it first when needed.
283
329
  * Returns why it did what it did and never throws. 'started', 'restarted' and
@@ -303,10 +349,7 @@ export function ensureBar({ platform = process.platform, env = process.env, cfg,
303
349
  return restart ? 'restarted' : 'started';
304
350
  }
305
351
  const state = readBuildState(d);
306
- // A compile that failed is not retried for a day. A missing toolchain is looked for again every time:
307
- // the check costs one short command, and installing the tools should bring the app at the next session.
308
- if (state && state.version === paths.version && state.ok === false && state.error !== 'no-toolchain'
309
- && Number.isFinite(state.at) && now - state.at < BUILD_RETRY_MS) return 'build-failed';
352
+ if (buildHeldBack(state, paths.version, now)) return 'build-failed';
310
353
  const age = lockAge(paths, now);
311
354
  if (age !== null && age < LOCK_STALE_MS) return 'building';
312
355
  if (!findSwiftc(d)) {
@@ -53,9 +53,14 @@ function readPackageVersion() {
53
53
  * Called after the hook has printed everything, and it can neither throw nor
54
54
  * delay the hook past a few file reads: the compile runs in a detached child.
55
55
  */
56
- async function startBarApp() {
56
+ async function startBarApp(lang) {
57
57
  try {
58
- (await import('../bar-app.js')).ensureBar();
58
+ const bar = await import('../bar-app.js');
59
+ // A failed compile holds the app back for a day; say so, or the user only sees an empty menu bar.
60
+ if (bar.ensureBar() === 'build-failed') {
61
+ const notice = bar.barBuildBlockedNotice({ lang });
62
+ if (notice) console.log(notice);
63
+ }
59
64
  } catch (e) { debug('route-scan:bar-app', e); }
60
65
  }
61
66
 
@@ -488,7 +493,7 @@ export async function run({ args, hasFlag, numArg }) {
488
493
  if (doc2mdBlock) console.log(doc2mdBlock);
489
494
  if (koreanBlock) console.log(koreanBlock);
490
495
  if (cohesionBlock) console.log(cohesionBlock);
491
- await startBarApp();
496
+ await startBarApp(lang);
492
497
  return; // nothing else to inject
493
498
  }
494
499
  if (secretsBlock) console.log(secretsBlock);
@@ -578,7 +583,7 @@ export async function run({ args, hasFlag, numArg }) {
578
583
  ...reviewRules.map((r) => `health|${r.signature}|${r.scope}`),
579
584
  ]);
580
585
  } catch (e) { debug('route-scan:seed-briefed', e); /* worst case is one duplicate brief */ }
581
- await startBarApp();
586
+ await startBarApp(lang);
582
587
  return;
583
588
  }
584
589