// agents menu — the agents deck and the overall limits as ONE menu bar item.
//
//   bar:         [critter] 80% 5h · 73% 7d      (badge on the critter when an agent needs you / errored)
//                — or, when a backup tool is ticked in the dock (codex / cursor / copilot …): that tool's usage
//                  (e.g. "codex 41% 5h · 12% 7d"), the same tick pattern as the Claude / antigrav account pills
//   left click:  popover with the deck (the hub's web UI: tiles, limits, vitals, audit)
//   right click: native details menu (limits, weekly split, every agent with its usage and a submenu to focus /
//                continue on another account / hand over to another tool, then measured tool usage)
//
// Data: http://127.0.0.1:4040/api/limits and /v1/state (the Pi-5-Monitor hub), plus /api/models, /api/handover/targets,
// /v1/accounts and /api/local-usage when the menu opens. Only real readings are shown; "—" means there is none (never a
// made-up number). Moving a job (continue / hand over) is never done from here: those items open the deck's own dialog for
// that agent, which previews the brief and asks for a second click.
import AppKit
import WebKit

let hubBase = "http://127.0.0.1:4040"
let limitsURL = URL(string: hubBase + "/api/limits")!
let stateURL = URL(string: hubBase + "/v1/state")!
let statusURL = URL(string: hubBase + "/api/status")!
let modelsURL = URL(string: hubBase + "/api/models")!
let targetsURL = URL(string: hubBase + "/api/handover/targets")!
let accountsURL = URL(string: hubBase + "/v1/accounts")!
let systemMetricsURL = URL(string: hubBase + "/api/system-metrics")!
let dockerModeURL = URL(string: hubBase + "/api/docker-mode")!
let localUsageURL = URL(string: hubBase + "/api/local-usage")!
let handURL = URL(string: hubBase + "/api/agents/hand")!   // agy / gemini / codex sessions started by hand in a terminal
let refreshURL = URL(string: hubBase + "/api/limits/refresh")!
let autoContinueURL = URL(string: hubBase + "/api/auto-continue")!
let broadcastURL = URL(string: hubBase + "/api/agents/broadcast")!
let deckURL = URL(string: hubBase + "/?panel&embed")!
let dashboardURL = URL(string: "http://localhost:4040/")!
let piVitalsURL = URL(string: "http://localhost:4040/?slide=2")!
let macVitalsURL = URL(string: "http://localhost:4040/?slide=2")!
let piSetupGuideURL = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("pi-setup/README_PI.md")

let accent = NSColor(srgbRed: 1.0, green: 0.30, blue: 0.0, alpha: 1.0)   // the deck's orange (#FF4D00)
let ink = NSColor(srgbRed: 0.04, green: 0.04, blue: 0.04, alpha: 1.0)
let palette: [NSColor] = [accent, NSColor(srgbRed: 0.37, green: 0.77, blue: 0.84, alpha: 1),
                          NSColor(srgbRed: 0.66, green: 0.33, blue: 0.97, alpha: 1),
                          NSColor(srgbRed: 0.91, green: 0.89, blue: 0.86, alpha: 1)]
let menuWidth: CGFloat = 320
let seedPosition: CGFloat = 320   // points from the right screen edge (safely to the right of the notch)

// Set AGENTS_MENU_DEBUG=1 (run the binary by hand) to log menu/click events to stderr.
/// Posted by a second copy of the app to the running one: "show your window" (then the second copy quits).
let showWindowNote = Notification.Name("local.pi5monitor.menu.showWindow")
let debugLog = ProcessInfo.processInfo.environment["AGENTS_MENU_DEBUG"] != nil
var tShow = Date()   // when the popover was last asked to open: the debug log counts from here
func dlog(_ s: @autoclosure () -> String) { if debugLog { FileHandle.standardError.write(Data(("[menu +\(Int(Date().timeIntervalSince(tShow) * 1000))ms] " + s() + "\n").utf8)) } }
func tlog(_ s: String) { FileHandle.standardError.write(Data((s + "\n").utf8)) }
var selfTesting = false   // keeps the popover from auto-closing while the self-test drives it
var persistFocus = true   // the self-test turns this off so it never touches the user's saved selection

// MARK: - data

struct Win {
    var label = "", state = "unknown"
    var percent: Int?
    var resetIn: String?, severity: String?
    var resetsAt: Date?
    var of: Int?, total: Int?
    var resetAccount: String?, resetAccountLabel: String?   // overall windows: the most-used account, whose reset this is

    init(_ d: [String: Any]? = nil) {
        label = (d?["label"] as? String) ?? ""
        percent = d?["percent"] as? Int
        state = (d?["state"] as? String) ?? "unknown"
        resetIn = d?["resetIn"] as? String
        severity = d?["severity"] as? String
        resetsAt = (d?["resetsAt"] as? String).flatMap(isoDate)
        of = d?["of"] as? Int
        total = d?["total"] as? Int
        resetAccount = d?["resetAccount"] as? String
        resetAccountLabel = d?["resetAccountLabel"] as? String
    }

    var pct: String {
        guard let p = percent else { return "—" }
        return (state == "stale" ? "~" : "") + "\(p)%"
    }
    /// The same window worded as % used.
    var left: String {
        guard let p = percent else { return "—" }
        return (state == "stale" ? "~" : "") + "\(p)% used"
    }
    /// Claude's own severity wins; otherwise colour by how full the window is.
    var tint: NSColor {
        switch severity {
        case "normal"?: return NSColor.labelColor
        case "warning"?: return accent
        case nil: return (percent ?? 0) >= 90 ? NSColor.systemRed : ((percent ?? 0) >= 75 ? accent : NSColor.labelColor)
        default: return NSColor.systemRed
        }
    }
    var detail: String {
        if state == "none" { return "no accounts ticked" }
        if state == "reset" { return "window reset · no new reading yet" }
        if percent == nil {
            if label == "5h" && (of ?? 0) == 0 && (total ?? 0) > 0 { return "no 5h limit (weekly only)" }
            return "no reading"
        }
        let r = resetIn.map { "resets in \($0)" + ((of ?? 0) > 1 ? resetAccountLabel.map { " (\($0))" } ?? "" : "") } ?? "resets —"
        if let p = percent, p >= 100 { return "limit reached · " + r }
        if let out = runOutIn() { return "out in \(out) · " + r }
        return r
    }

    /// Window duration in seconds based on label ("5h", "7d", "30d", etc.)
    var windowDuration: TimeInterval {
        let l = label.lowercased()
        if l.contains("5h") { return 5 * 3600 }
        if l.contains("7d") { return 7 * 86400 }
        if l.contains("30d") { return 30 * 86400 }
        if l.contains("24h") || l.contains("1d") { return 86400 }
        if let m = l.range(of: "^([0-9]+)h", options: .regularExpression), let h = Double(l[m].dropLast()) { return h * 3600 }
        if let m = l.range(of: "^([0-9]+)d", options: .regularExpression), let d = Double(l[m].dropLast()) { return d * 86400 }
        return 5 * 3600
    }

    /// Estimated seconds from `now` until 100% quota is reached at current burn rate.
    /// Suppresses noisy early-window extrapolations (tiny elapsed time or < 5% quantized usage).
    func secondsToRunOut(now: Date = Date()) -> TimeInterval? {
        guard let p = percent, p > 0, let at = resetsAt else { return nil }
        if p >= 100 { return 0 }
        guard p >= 5 else { return nil }
        let resetSecs = at.timeIntervalSince(now)
        guard resetSecs > 0 else { return nil }
        let elapsed = windowDuration - resetSecs
        let minElapsed = min(1800, windowDuration * 0.05)
        guard elapsed >= minElapsed else { return nil }
        let remaining = 100.0 - Double(p)
        return elapsed * remaining / Double(p)
    }

    /// Whether quota is predicted to run out BEFORE the window resets.
    func runsOutBeforeReset(now: Date = Date()) -> Bool {
        guard let p = percent else { return false }
        if p >= 100 { return true }
        guard let s = secondsToRunOut(now: now), let at = resetsAt else { return false }
        return s < at.timeIntervalSince(now)
    }

    /// Formatted time until running out, e.g. "2h 22m" (or nil if it won't run out before reset).
    func runOutIn(now: Date = Date()) -> String? {
        guard let p = percent else { return nil }
        if p >= 100 { return "now" }
        guard runsOutBeforeReset(now: now), let s = secondsToRunOut(now: now) else { return nil }
        return formatIn(s)
    }
}

struct Acct {
    var id = "", label = "", note = "", unit = "used"   // unit: how the account's own app words it ("used" / "left")
    var sameAs = ""       // an antigrav login that returned the other login's figures (one Google login behind both launchers): it has none of its own
    var short = Win(), week = Win()
    var color = NSColor.secondaryLabelColor
    var expired = false   // the CLI said "Please run /login" (the limits JSON's health.state)
}

struct Share { var name: String; var percent: Int }

/// THE overall rule (plan item 8) — identical in collectors/overall.js, the page's overallFocus and the iOS Usage.overall;
/// spec: tests/overall-vectors.json (`agents menu --overall-vectors <file>` runs it headless). Highest usage (lowest remaining
/// headroom) among the accounts with a reading; the reset is THAT most-used account's (ties: the earlier reset), and that account is named.
func overallRule(_ sel: [Acct], pick: (Acct) -> Win, label: String, now: Date = Date()) -> Win {
    let known = sel.filter { pick($0).percent != nil }
    var w = Win(); w.label = label; w.of = known.count; w.total = sel.count
    if sel.isEmpty { w.state = "none"; return w }   // nothing ticked: no number at all
    guard !known.isEmpty else { return w }
    let top = known.compactMap { pick($0).percent }.max() ?? 0
    w.percent = top
    w.state = known.contains { pick($0).state == "stale" } ? "stale" : "live"
    let rank = { (v: String) -> Int in v == "normal" ? 0 : (v == "warning" ? 1 : 2) }
    w.severity = known.compactMap { pick($0).severity }.max { rank($0) < rank($1) }
    let decider = known.filter { pick($0).percent == top }
        .min { (pick($0).resetsAt ?? .distantFuture) < (pick($1).resetsAt ?? .distantFuture) }!   // first of equals, like the JS reduce
    w.resetAccount = decider.id
    w.resetAccountLabel = decider.label.isEmpty ? decider.id : decider.label
    if let at = pick(decider).resetsAt { w.resetsAt = at; w.resetIn = formatIn(at.timeIntervalSince(now)) }
    return w
}

struct Counts {
    var running = 0, waiting = 0, idle = 0, error = 0
    var total: Int { running + waiting + idle + error }
}

/// The extra terminal agents the hub runs in shell tiles titled "<id> · …" (collectors/cli_tools.js EXTRA_TILES).
let extraTiles = ["copilot", "kimi", "groq", "hermes", "nvidia", "cerebras", "local"]   // as the deck's EXTRA_TILES ("local model · …" tiles too)

/// One agent of the deck, as the details menu lists it (built from /v1/state).
struct AgentInfo {
    struct UsageStats {
        var tokens: Int = 0
        var costUsd: Double = 0.0
    }
    var id = "", title = "", folder = "", cwd = "", branch = "", tool = "", status = "", account = "", activity = "", error = ""
    var slot = 0
    var ctxPercent: Int?
    var costUsd = 0.0
    var external = false
    var model = ""
    var provider = ""
    var totalTokens = 0
    var lifeUsage = UsageStats()
    var weekUsage = UsageStats()
    var dayUsage = UsageStats()
    var hourUsage = UsageStats()

    init(_ d: [String: Any]) {
        id = d["id"] as? String ?? ""
        folder = d["folder"] as? String ?? ""
        cwd = d["cwd"] as? String ?? ""
        title = (d["title"] as? String).flatMap { $0.isEmpty ? nil : $0 } ?? (folder.isEmpty ? id : folder)
        branch = d["branch"] as? String ?? ""
        tool = d["tool"] as? String ?? ""
        status = d["status"] as? String ?? ""
        account = (d["account"] as? [String: Any])?["name"] as? String ?? ""
        activity = (d["activity"] as? [String: Any])?["tool"] as? String ?? ""
        error = (d["error"] as? [String: Any])?["message"] as? String ?? ""
        slot = d["slot"] as? Int ?? 0
        if let c = d["context"] as? [String: Any], let used = c["used"] as? Int, let win = c["window"] as? Int, win > 0 {
            ctxPercent = Int((Double(used) / Double(win) * 100).rounded())
        }
        costUsd = (d["costUsd"] as? NSNumber)?.doubleValue ?? 0
        external = d["external"] as? Bool ?? false
        model = d["model"] as? String ?? ""
        provider = d["tool"] as? String ?? ""
        if let tok = d["tokens"] as? [String: Any] {
            let inn = (tok["input"] as? NSNumber)?.intValue ?? 0
            let out = (tok["output"] as? NSNumber)?.intValue ?? 0
            let cr = (tok["cacheRead"] as? NSNumber)?.intValue ?? 0
            let cw = (tok["cacheWrite"] as? NSNumber)?.intValue ?? 0
            totalTokens = inn + out + cr + cw
        }
        if let u = d["usage"] as? [String: Any] {
            if let p = u["provider"] as? String, !p.isEmpty { provider = p }
            if let m = u["model"] as? String, !m.isEmpty { model = m }
            func parseUsage(_ key: String) -> UsageStats {
                guard let sub = u[key] as? [String: Any] else { return UsageStats() }
                return UsageStats(
                    tokens: (sub["tokens"] as? NSNumber)?.intValue ?? 0,
                    costUsd: (sub["costUsd"] as? NSNumber)?.doubleValue ?? 0.0
                )
            }
            lifeUsage = parseUsage("lifetime")
            weekUsage = parseUsage("weekly")
            dayUsage = parseUsage("daily")
            hourUsage = parseUsage("hourly")
        } else {
            let t = totalTokens
            lifeUsage = UsageStats(tokens: t, costUsd: costUsd)
            weekUsage = UsageStats(tokens: t, costUsd: costUsd)
            dayUsage = UsageStats(tokens: t, costUsd: costUsd)
            hourUsage = UsageStats(tokens: 0, costUsd: 0.0)
        }
    }
    /// An antigrav / cursor / kiro / opencode tile is a shell agent running that program, told apart by its title (the deck's isAgyAgent / tileOf).
    private func titled(_ word: String) -> Bool { tool == "shell" && title.range(of: "^\(word)\\b", options: [.regularExpression, .caseInsensitive]) != nil }
    /// "antigrav · …", "antigrav-work · …", and "agy-work · …" (an agy started by hand and put on the deck is titled by its profile).
    var isAntigrav: Bool { titled("antigrav") || titled("agy") }
    var isCursor: Bool { titled("cursor") }
    /// cursor / kiro / opencode / copilot, kimi … (extraTiles): the shell-tile tools that have a row of their own in /api/models.
    var tileTool: String? { isCursor ? "cursor" : (["kiro", "opencode"] + extraTiles).first { titled($0) } }
    /// A codex / gemini started by hand and put on the deck ("+ add", deckN): a stand-in shell tile titled "codex · …" / "gemini · …"
    /// (the deck runs its own codex and gemini natively, so only a stand-in is titled so). Named as that tool, nothing more.
    var standIn: String? { ["codex", "gemini"].first { titled($0) } }
    var kind: String { isAntigrav ? "antigrav" : (tileTool ?? standIn ?? tool) }
    /// The launcher an antigrav tile runs under: "antigrav-work · …" is work, "antigrav-free · …" is free; a plain "antigrav · …" tile is the bare agy, which is the personal one.
    var agyProfile: String {
        if title.range(of: "^(?:antigrav|agy)-work\\b", options: [.regularExpression, .caseInsensitive]) != nil { return "work" }
        if title.range(of: "^(?:antigrav|agy)-free\\b", options: [.regularExpression, .caseInsensitive]) != nil { return "free" }
        return "personal"
    }
    /// The title without the "<tool> · " its row's tag already says ("agy-work · Fix it" -> "Fix it" beside "antigrav work"); as is when that is all it says.
    var cleanTitle: String {
        guard tool == "shell", isAntigrav || tileTool != nil || standIn != nil else { return title }
        let rest = title.replacingOccurrences(of: "^(?:antigrav|agy)(?:-work|-personal|-free)?\\s*·\\s*|^(?:codex|gemini|cursor|kiro|opencode|copilot|kimi|groq|hermes|nvidia|cerebras|local(?:\\s+model)?)\\s*·\\s*",
                                              with: "", options: [.regularExpression, .caseInsensitive]).trimmingCharacters(in: .whitespaces)
        return rest.isEmpty ? title : rest
    }
    /// The key of the deck's hand-over dialog for this agent's own tool ("agy-work" / "agy-personal" for antigrav): it is not offered as a target.
    var handoverKey: String { isAntigrav ? "agy-\(agyProfile)" : (tileTool ?? tool) }
    var live: Bool { status != "exited" }
    var needsYou: Bool { status == "waiting" || status == "error" }
    /// A plain shell has no conversation to continue or hand over.
    var movable: Bool { tool != "shell" || isAntigrav || tileTool != nil }
}

/// A coding tool as /api/models reports it (collectors/cli_tools.js): installed, logged in (yes / no only), and percentage usage when available.
struct ToolInfo {
    var id = "", label = "", plan = "", login = "", reached = "", sameAs = "", from = "", group = ""
    var installed = false, keyless = false, active = false
    var offline = false                           // the local model while Docker Model Runner is not answering (it has no login)
    var loggedIn: Bool?
    var windows: [Win] = []
    var profiles: [(label: String, windows: [Win])] = []
    var agentsTotal = 0
    var credits: (used: Double, limit: Double)?   // kiro
    var spent: [String] = []                      // antigrav's other model groups whose weekly limit is spent

    init(_ d: [String: Any]) {
        id = d["id"] as? String ?? ""
        label = d["label"] as? String ?? id
        installed = d["installed"] as? Bool ?? false
        keyless = d["keyless"] as? Bool ?? false
        offline = d["offline"] as? Bool ?? false
        active = d["active"] as? Bool ?? false
        sameAs = d["sameAs"] as? String ?? ""
        loggedIn = d["loggedIn"] as? Bool
        login = d["login"] as? String ?? ""
        agentsTotal = (d["agents"] as? [String: Any])?["total"] as? Int ?? 0
        if let u = d["usage"] as? [String: Any] {
            plan = u["plan"] as? String ?? ""
            reached = u["reached"] as? String ?? ""
            from = u["from"] as? String ?? ""
            group = u["group"] as? String ?? ""
            let ws = u["windows"] as? [[String: Any]] ?? []
            windows = ws.map { Win($0) }
            profiles = (u["profiles"] as? [[String: Any]] ?? []).map { profile in
                (profile["label"] as? String ?? profile["id"] as? String ?? "",
                 (profile["windows"] as? [[String: Any]] ?? []).map { Win($0) })
            }
            if let w = ws.first, w["unit"] as? String == "credits", let used = (w["used"] as? NSNumber)?.doubleValue, let lim = (w["limit"] as? NSNumber)?.doubleValue { credits = (used, lim) }
            spent = (u["others"] as? [[String: Any]] ?? []).filter { ($0["week"] as? Int ?? 0) >= 100 }.compactMap { $0["group"] as? String }
        }
    }
}

/// What a menu item acts on: an agent, and (for continue / hand over) the target login or tool.
final class Act: NSObject {
    let id: String, target: String
    init(_ id: String, _ target: String = "") { self.id = id; self.target = target }
}

func clip(_ s: String, _ n: Int) -> String { s.count > n ? String(s.prefix(n - 1)) + "…" : s }
func measuredWindows(_ windows: [Win]) -> [Win] { windows.filter { $0.percent != nil } }

func hexColor(_ s: String?) -> NSColor? {
    guard let s = s, s.hasPrefix("#"), s.count == 7, let v = UInt32(s.dropFirst(), radix: 16) else { return nil }
    return NSColor(srgbRed: CGFloat((v >> 16) & 255) / 255, green: CGFloat((v >> 8) & 255) / 255,
                   blue: CGFloat(v & 255) / 255, alpha: 1)
}

// Formatters are costly to build; this runs on every poll, so make them once.
let isoFrac: ISO8601DateFormatter = { let f = ISO8601DateFormatter(); f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]; return f }()
let isoPlain = ISO8601DateFormatter()
func isoDate(_ s: String) -> Date? { isoFrac.date(from: s) ?? isoPlain.date(from: s) }

/// "2h 12m" / "3d 18h" — same format the hub uses (collectors/limits_collector.js formatIn).
func formatIn(_ secs: TimeInterval) -> String? {
    guard secs > 0 else { return nil }
    let mins = Int(secs / 60), d = mins / 1440, h = (mins % 1440) / 60, m = mins % 60
    return d > 0 ? "\(d)d \(h)h" : (h > 0 ? "\(h)h \(m)m" : "\(m)m")
}

func ago(_ iso: String?) -> String? {
    guard let iso = iso, let t = isoDate(iso) else { return nil }
    let s = Int(Date().timeIntervalSince(t))
    if s < 60 { return "just now" }
    if s < 3600 { return "\(s / 60)m ago" }
    return "\(s / 3600)h \((s % 3600) / 60)m ago"
}

/// Format a number with k/m suffixes: "1.2k", "47.7k", "3m".
func fmtN(_ n: Int) -> String {
    if n >= 1_000_000 { return String(format: "%.1fM", Double(n) / 1_000_000) }
    if n >= 1_000 { return String(format: "%.1fk", Double(n) / 1_000) }
    return String(n)
}

// MARK: - icon

/// The deck's pixel critter (same shape as the web favicon), drawn slightly smaller (15x12 pt) so it fits crisp in crowded menu bars.
func critter(badge: NSColor?) -> NSImage {
    let img = NSImage(size: NSSize(width: 15, height: 12), flipped: true) { _ in
        guard let ctx = NSGraphicsContext.current?.cgContext else { return false }
        ctx.saveGState()
        let s: CGFloat = 0.8
        ctx.scaleBy(x: s, y: s)
        let ox: CGFloat = 0.5, oy: CGFloat = 2.0
        func r(_ x: CGFloat, _ y: CGFloat, _ w: CGFloat, _ h: CGFloat, _ c: NSColor) {
            c.setFill(); NSRect(x: ox + x, y: oy + y, width: w, height: h).fill()
        }
        r(2, 0, 10, 1, accent); r(1, 1, 12, 1, accent); r(0, 2, 14, 2, accent)
        r(1, 4, 12, 2, accent); r(2, 6, 10, 1, accent)
        for x in [2, 4, 9, 11] as [CGFloat] { r(x, 7, 1, 2, accent) }
        r(4, 2, 1, 2, ink); r(9, 2, 1, 2, ink)
        if let b = badge {
            let dot = NSRect(x: 11.0, y: 1.0, width: 4.8, height: 4.8)
            NSColor.black.withAlphaComponent(0.55).setFill(); NSBezierPath(ovalIn: dot.insetBy(dx: -0.7, dy: -0.7)).fill()
            b.setFill(); NSBezierPath(ovalIn: dot).fill()
        }
        ctx.restoreGState()
        return true
    }
    img.isTemplate = false
    return img
}

/// An agent's critter for its menu row (15 Nov: "redo the sprites so they fit with the agent deck original designs, keep the agents
/// different coloured"): the original agents-deck critter (Codex: the onigiri), in its tool's colour as on the deck (dashboard.css
/// --tool-*), faded while it rests. Drawn once per tool and state.
let kinColours: [String: Int] = ["claude": 0xC98B6B, "codex": 0x4FB3A6, "cursor": 0xA9B6CC, "gemini": 0x6F8FD8, "kiro": 0xD4A94A,
                                 "opencode": 0x8DBF7A, "antigrav": 0xA855F7, "copilot": 0x8B9CF0, "kimi": 0xE07A8F, "groq": 0xF0703C, "hermes": 0xD95FC8,
                                 "nvidia": 0x76B900, "cerebras": 0xE5B33B, "local": 0x2496ED]
private var kinImages: [String: NSImage] = [:]
func kinCritter(_ kind: String, faded: Bool = false) -> NSImage {
    let key = "\(kind)|\(faded)"
    if let img = kinImages[key] { return img }
    let hexv = kinColours[kind]
    let base = hexv.map { NSColor(srgbRed: CGFloat(($0 >> 16) & 0xFF) / 255, green: CGFloat(($0 >> 8) & 0xFF) / 255, blue: CGFloat($0 & 0xFF) / 255, alpha: 1) } ?? NSColor.secondaryLabelColor
    let body = faded ? base.withAlphaComponent(0.45) : base
    let onigiri = kind == "codex"
    let img = NSImage(size: NSSize(width: 16, height: 12), flipped: true) { _ in
        let oy: CGFloat = onigiri ? 3.4 : 2.2
        func r(_ x: CGFloat, _ y: CGFloat, _ w: CGFloat, _ h: CGFloat, _ c: NSColor) { c.setFill(); NSRect(x: 1 + x, y: oy + y, width: w, height: h).fill() }
        let eye = NSColor(white: 0.06, alpha: faded ? 0.5 : 0.9)
        if onigiri {   // dashboard.js BOT_BODY, row by row, then the nori and two feet
            for (y, x0, x1) in [(-3, 6, 8), (-2, 5, 9), (-1, 4, 10), (0, 3, 11), (1, 2, 12), (2, 2, 12), (3, 1, 13), (4, 1, 13), (5, 0, 14), (6, 1, 13)] as [(CGFloat, CGFloat, CGFloat)] {
                r(x0, y, x1 - x0, 1, body)
            }
            r(4, 5.4, 6, 1.6, eye.withAlphaComponent(faded ? 0.3 : 0.55))
            r(3.5, 7, 2, 1.4, body); r(8.5, 7, 2, 1.4, body)
            r(4, 2, 1, 2, eye); r(9, 2, 1, 2, eye)
        } else {       // dashboard.js BODY: the 12 x 6 block, 1 x 2 arms, four legs
            r(1, 0, 12, 6, body); r(0, 2, 1, 2, body); r(13, 2, 1, 2, body)
            for x in [2, 4, 9, 11] as [CGFloat] { r(x, 6, 1, 1.6, body) }
            r(4, 1.5, 1, 2, eye); r(9, 1.5, 1, 2, eye)
        }
        return true
    }
    img.isTemplate = false
    kinImages[key] = img
    return img
}

/// The app icon (Dock, Finder, the app switcher): the same critter, big, on the deck's near-black tile.
func appIcon(_ side: CGFloat = 512) -> NSImage {
    NSImage(size: NSSize(width: side, height: side), flipped: true) { _ in
        let u = side / 1024   // drawn on a 1024 grid
        let tile = NSRect(x: 100 * u, y: 100 * u, width: 824 * u, height: 824 * u)
        NSColor(srgbRed: 0.07, green: 0.07, blue: 0.07, alpha: 1).setFill()
        NSBezierPath(roundedRect: tile, xRadius: 185 * u, yRadius: 185 * u).fill()
        let px = 44 * u, ox = 512 * u - 7 * px, oy = 512 * u - 4.5 * px   // the critter is 14 x 9 cells
        func r(_ x: CGFloat, _ y: CGFloat, _ w: CGFloat, _ h: CGFloat, _ c: NSColor) {
            c.setFill(); NSRect(x: ox + x * px, y: oy + y * px, width: w * px, height: h * px).fill()
        }
        r(2, 0, 10, 1, accent); r(1, 1, 12, 1, accent); r(0, 2, 14, 2, accent)
        r(1, 4, 12, 2, accent); r(2, 6, 10, 1, accent)
        for x in [2, 4, 9, 11] as [CGFloat] { r(x, 7, 1, 2, accent) }
        r(4, 2, 1, 2, ink); r(9, 2, 1, 2, ink)
        return true
    }
}

/// An agy / gemini / codex … session started by hand in a terminal (GET /api/agents/hand): the daemon doesn't know it, so it can
/// only be shown and its window raised, never moved.
struct HandSession {
    var pid = 0, tool = "", folder = "", cwd = ""
    init(_ d: [String: Any]) {
        pid = d["pid"] as? Int ?? 0
        tool = d["tool"] as? String ?? ""
        folder = d["folder"] as? String ?? ""
        cwd = d["cwd"] as? String ?? ""
    }
    /// The same session as a deck agent would look, so the usage lines are worded the same (antigrav's account, codex's windows …).
    var asAgent: AgentInfo {
        let shellTool = (["antigrav", "cursor", "kiro", "opencode"] + extraTiles).contains(tool)
        return AgentInfo(["id": "", "tool": shellTool ? "shell" : tool, "title": shellTool ? "\(tool) · \(folder)" : folder, "folder": folder, "cwd": cwd, "status": "idle"])
    }
}

/// One folder cluster from /api/agents/broadcast (multi-agent / multi-company group sharing a folder).
struct BroadcastCluster {
    var cwd = "", folder = ""
    var cwds: [String] = []
    var agentCount = 0, reachableCount = 0
    var companies: [String] = []
    var isMultiCompany = false
    init(_ d: [String: Any]) {
        cwd = d["cwd"] as? String ?? ""
        folder = d["folder"] as? String ?? ""
        cwds = d["cwds"] as? [String] ?? (cwd.isEmpty ? [] : [cwd])
        agentCount = (d["agentCount"] as? NSNumber)?.intValue ?? 0
        reachableCount = (d["reachableCount"] as? NSNumber)?.intValue ?? 0
        companies = d["companies"] as? [String] ?? []
        isMultiCompany = d["isMultiCompany"] as? Bool ?? false
    }
    func matches(_ dir: String) -> Bool {
        let norm = (dir as NSString).standardizingPath
        guard !norm.isEmpty else { return false }
        if (cwd as NSString).standardizingPath == norm { return true }
        return cwds.contains { ($0 as NSString).standardizingPath == norm }
    }
}

// MARK: - dynamic menu (lazy submenu loading for instant menubar and hidden agents responsiveness)

/// An NSMenu that populates its items lazily on demand when displayed or inspected.
/// Prevents expensive synchronous view/menu construction when opening menus with many items or submenus.
final class DynamicMenu: NSMenu, NSMenuDelegate {
    private var populate: ((NSMenu) -> Void)?
    private var isPopulated = false

    init(title: String = "", populate: @escaping (NSMenu) -> Void) {
        self.populate = populate
        super.init(title: title)
        self.autoenablesItems = false
        self.delegate = self
    }

    required init(coder: NSCoder) { fatalError() }

    func ensurePopulated() {
        if !isPopulated {
            isPopulated = true
            let block = populate
            populate = nil
            block?(self)
        }
    }

    override var items: [NSMenuItem] {
        get {
            if selfTesting { ensurePopulated() }
            return super.items
        }
        set {
            super.items = newValue
        }
    }

    override var numberOfItems: Int {
        if selfTesting { ensurePopulated() }
        if isPopulated {
            return super.numberOfItems
        }
        return 1
    }

    func menuNeedsUpdate(_ menu: NSMenu) {
        ensurePopulated()
    }

    func menuWillOpen(_ menu: NSMenu) {
        ensurePopulated()
    }
}

// MARK: - menu rows (drawn views, so the bars/spacing are exact and every row shares one font)

class Row: NSView {
    override var isFlipped: Bool { true }
    init(height: CGFloat) {
        super.init(frame: NSRect(x: 0, y: 0, width: menuWidth, height: height))
        autoresizingMask = [.width]
    }
    required init?(coder: NSCoder) { fatalError() }

    @discardableResult
    func text(_ s: String, x: CGFloat, y: CGFloat, font: NSFont, color: NSColor, right: Bool = false) -> CGFloat {
        let a: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: color]
        let w = (s as NSString).size(withAttributes: a).width
        (s as NSString).draw(at: NSPoint(x: right ? x - w : x, y: y), withAttributes: a)
        return w
    }
    func bar(x: CGFloat, y: CGFloat, w: CGFloat, fraction: CGFloat?, color: NSColor, dim: Bool) {
        let track = NSRect(x: x, y: y, width: w, height: 6)
        NSColor.labelColor.withAlphaComponent(0.14).setFill()
        NSBezierPath(roundedRect: track, xRadius: 3, yRadius: 3).fill()
        guard let f = fraction else { return }
        var fill = track; fill.size.width = max(6, w * min(1, max(0, f)))
        color.withAlphaComponent(dim ? 0.55 : 1).setFill()
        NSBezierPath(roundedRect: fill, xRadius: 3, yRadius: 3).fill()
    }
}

let body = NSFont.systemFont(ofSize: 12.5, weight: .regular)
let bodyBold = NSFont.systemFont(ofSize: 12.5, weight: .semibold)
let digits = NSFont.monospacedDigitSystemFont(ofSize: 12.5, weight: .semibold)
let small = NSFont.systemFont(ofSize: 11, weight: .regular)
let caps = NSFont.systemFont(ofSize: 10.5, weight: .semibold)

/// Account line as a standard menu item (AppKit doesn't deliver clicks to custom-view rows): a coloured ●,
/// then tab-aligned "85% 5h   71% 7d". The menu's own checkmark (item state) shows which accounts are focused;
/// `on` is false for an account that isn't counted because a focus is set on others (dimmed).
/// Primary text keeps the menu's own colour (an explicit dynamic colour renders grey in menus).
func accountTitle(_ a: Acct, on: Bool) -> NSAttributedString {
    let ps = NSMutableParagraphStyle()
    ps.tabStops = [NSTextTab(textAlignment: .left, location: 132), NSTextTab(textAlignment: .left, location: 206)]
    let s = NSMutableAttributedString()
    func add(_ t: String, _ f: NSFont, _ c: NSColor?) {
        var at: [NSAttributedString.Key: Any] = [.font: f, .paragraphStyle: ps]
        if let c = c { at[.foregroundColor] = on ? c : c.withAlphaComponent(0.4) }
        s.append(NSAttributedString(string: t, attributes: at))
    }
    add("● ", body, a.color)
    add(a.label, body, on ? nil : NSColor.white)
    for w in [a.short, a.week] {
        add("\t", body, nil)
        add(w.pct, digits, w.percent == nil ? NSColor.secondaryLabelColor : (w.tint == .labelColor ? nil : w.tint))
        add(" " + w.label, small, NSColor.secondaryLabelColor)
    }
    return s
}

final class HeaderRow: Row {
    var updated: String?
    var online = true
    var busy = false
    var title = "OVERALL LIMITS"
    init() { super.init(height: 26) }
    required init?(coder: NSCoder) { fatalError() }
    override func draw(_ r: NSRect) {
        accent.setFill(); NSBezierPath(roundedRect: NSRect(x: 14, y: 9, width: 8, height: 8), xRadius: 2, yRadius: 2).fill()
        text(title, x: 29, y: 6, font: caps, color: accent)
        let note = !online ? "hub offline" : (busy ? "refreshing…" : (updated.map { "updated \($0)" } ?? ""))
        text(note, x: bounds.width - 14, y: 6, font: small, color: .secondaryLabelColor, right: true)
    }
}

final class LimitRow: Row {
    var win = Win()
    init() { super.init(height: 40) }
    required init?(coder: NSCoder) { fatalError() }
    override func draw(_ r: NSRect) {
        let w = bounds.width
        text(win.label, x: 14, y: 4, font: bodyBold, color: .labelColor)
        text(win.pct, x: w - 14, y: 4, font: digits, color: win.percent == nil ? .secondaryLabelColor : win.tint, right: true)
        bar(x: 46, y: 9, w: w - 46 - 70, fraction: win.percent.map { CGFloat($0) / 100 }, color: win.tint, dim: win.state == "stale")
        var sub = win.detail
        if let out = win.runOutIn() {
            sub = "out in \(out) · " + sub
        }
        if let of = win.of, let total = win.total, win.percent != nil, win.runOutIn() == nil {
            sub += " · \(of) of \(total) account\(total == 1 ? "" : "s")"
        }
        let subColor = win.runOutIn() != nil ? (win.tint == .labelColor ? accent : win.tint) : .secondaryLabelColor
        text(clip(sub, 44), x: 46, y: 22, font: small, color: subColor)
    }
}

final class SplitRow: Row {
    var shares: [Share] = []
    var owner = ""
    init() { super.init(height: 62) }
    required init?(coder: NSCoder) { fatalError() }
    override func draw(_ r: NSRect) {
        text("7D USAGE BY PRODUCT" + (owner.isEmpty ? "" : " · \(owner.uppercased())"), x: 14, y: 12, font: caps, color: .secondaryLabelColor)
        let total = CGFloat(max(1, shares.reduce(0) { $0 + $1.percent }))
        let left: CGFloat = 14, width = bounds.width - 28
        var x = left
        for (i, s) in shares.enumerated() {
            let w = max(3, width * CGFloat(s.percent) / total - 1)
            palette[i % palette.count].setFill()
            NSBezierPath(roundedRect: NSRect(x: x, y: 29, width: w, height: 6), xRadius: 3, yRadius: 3).fill()
            x += w + 1
        }
        var lx = left
        for (i, s) in shares.enumerated() {
            palette[i % palette.count].setFill()
            NSBezierPath(ovalIn: NSRect(x: lx, y: 44, width: 7, height: 7)).fill()
            lx += 11 + text("\(s.name) \(s.percent)%", x: lx + 11, y: 41, font: small, color: .labelColor) + 10
        }
    }
}

final class NoteRow: Row {
    var line = "" { didSet { needsDisplay = true } }
    var tint = NSColor.secondaryLabelColor
    init() { super.init(height: 22) }
    required init?(coder: NSCoder) { fatalError() }
    override func draw(_ r: NSRect) { text(line, x: 14, y: 3, font: small, color: tint) }
}

/// System metrics row: Docker containers memory + macOS memory pressure
final class MetricsRow: Row {
    var dockerLine = "" { didSet { needsDisplay = true } }
    var memLine = "" { didSet { needsDisplay = true } }
    var localLine = "" { didSet { needsDisplay = true } }      // odyssеus: local models loaded/running
    var localUsageLine = "" { didSet { needsDisplay = true } } // odyssеus: token totals
    init() { super.init(height: 74) }
    required init?(coder: NSCoder) { fatalError() }
    override func draw(_ r: NSRect) {
        text(dockerLine, x: 14, y: 3, font: small, color: .secondaryLabelColor)
        text(memLine, x: 14, y: 21, font: small, color: .secondaryLabelColor)
        if !localLine.isEmpty { text(localLine, x: 14, y: 39, font: small, color: .secondaryLabelColor) }
        if !localUsageLine.isEmpty { text(localUsageLine, x: 14, y: 57, font: small, color: .secondaryLabelColor) }
    }
}

/// Overall totals row: lifetime, monthly, weekly, daily, hourly token totals and costs across all models (+ local models)
final class TotalUsageRow: Row {
    var line1 = "" { didSet { needsDisplay = true } }
    var line2 = "" { didSet { needsDisplay = true } }
    init() { super.init(height: 54) }
    required init?(coder: NSCoder) { fatalError() }
    override func draw(_ r: NSRect) {
        text("TOTAL USAGE · ALL + LOCAL MODELS", x: 14, y: 3, font: caps, color: accent)
        if !line1.isEmpty { text(line1, x: 14, y: 19, font: small, color: .labelColor) }
        if !line2.isEmpty { text(line2, x: 14, y: 35, font: small, color: .secondaryLabelColor) }
    }
}

// MARK: - app

/// A picture of the page as it was when it was last put away, laid over it the moment it comes back (15 Nov: "the menu bar when opening
/// the full agent view is STILL LAGGY"). The page itself is fast (WebKit: 1–2 ms to wake, 9–13 ms to open an agent), but under memory
/// pressure macOS pages an idle web view out (8.8 GB of swap that day, with a 17 GB local model loaded), and the live page then takes a
/// moment to page back in and draw. The picture is up at once; clicks go straight through it to the page, and it fades as soon as the
/// page has drawn a frame (2 s at most). Shown only when the size has not changed since.
final class PageCover {
    private final class Pic: NSImageView { override func hitTest(_ point: NSPoint) -> NSView? { nil } }
    private let pic = Pic()
    private var shot: NSImage?
    private var gen = 0
    /// Keep a picture of the page as it is now (it must still be on screen), then `then` (at once when there is nothing to picture,
    /// else when the picture is taken or after 0.25 s, whichever is first).
    func keep(_ w: WKWebView?, then: @escaping () -> Void = {}) {
        guard let w = w, w.window?.isVisible == true, w.bounds.width > 0 else { then(); return }
        var done = false
        let finish = { if !done { done = true; then() } }
        w.takeSnapshot(with: nil) { [weak self] img, _ in if let img = img { self?.shot = img }; finish() }
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: finish)
    }
    /// Lay the last picture over `w` now; it fades once the page has drawn.
    func show(over w: WKWebView) {
        guard let shot = shot, abs(shot.size.width - w.bounds.width) < 1, abs(shot.size.height - w.bounds.height) < 1 else { return }
        gen += 1
        let g = gen
        pic.image = shot
        pic.imageScaling = .scaleAxesIndependently
        pic.frame = w.bounds
        pic.autoresizingMask = [.width, .height]
        pic.alphaValue = 1
        if pic.superview !== w { pic.removeFromSuperview(); w.addSubview(pic) }
        w.callAsyncJavaScript("await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))", arguments: [:], in: nil, in: .page) { [weak self] _ in self?.drop(g) }
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in self?.drop(g) }
    }
    private func drop(_ g: Int) {
        guard g == gen, pic.superview != nil else { return }
        gen += 1
        let faded = gen
        NSAnimationContext.runAnimationGroup({ c in c.duration = 0.12; pic.animator().alphaValue = 0 },
                                             completionHandler: { [weak self] in if self?.gen == faded { self?.pic.removeFromSuperview() } })
    }
}

// MARK: - the app window (the full deck, like the browser tab, in a window of its own)

/// "Agent Monitor" as an app: a normal resizable window with the whole deck (http://127.0.0.1:4040/), a Dock icon and ⌘-Tab entry
/// while it is open. Closing it leaves the menu bar item running, as before. The page is dropped on close, so nothing renders or
/// polls in the background.
/// Floating, borderless, transparent desktop HUD overlay for Capri + live Agent Deck info.
final class CapriHUDWindow: NSObject, WKNavigationDelegate, WKScriptMessageHandler {
    let url = URL(string: hubBase + "/capri.html")!
    let hudSize = NSSize(width: 480, height: 320)
    var window: NSWindow?
    var web: WKWebView?
    var retry: Timer?
    var mouseTimer: Timer?
    var lastGaze = ""
    var lastHitCheck = Date.distantPast
    var hitTestBusy = false
    var onHide: (() -> Void)?
    var onOpenDeck: (() -> Void)?

    var isVisible: Bool { window?.isVisible == true }

    func show() {
        if window == nil { build() }
        guard let w = window else { return }
        clampToScreen(w)
        w.ignoresMouseEvents = true
        w.orderFrontRegardless()
        web?.evaluateJavaScript("window.setHudActive && window.setHudActive(true);", completionHandler: nil)
        startMouseWatch()
    }

    func hide() {
        stopMouseWatch()
        retry?.invalidate()
        retry = nil
        if let w = web {
            w.evaluateJavaScript("window.setHudActive && window.setHudActive(false);", completionHandler: nil)
            w.configuration.userContentController.removeScriptMessageHandler(forName: "capriHud")
            w.stopLoading()
            w.navigationDelegate = nil
        }
        window?.orderOut(nil)
        window = nil
        web = nil
    }

    private func build() {
        let vf = (NSScreen.main ?? NSScreen.screens.first)?.visibleFrame ?? NSRect(x: 0, y: 0, width: 1280, height: 800)
        var origin = NSPoint(x: vf.maxX - hudSize.width - 14, y: vf.minY + 14)
        if let saved = UserDefaults.standard.dictionary(forKey: "capriHudOrigin"),
           let sx = saved["x"] as? Double, let sy = saved["y"] as? Double {
            origin = NSPoint(x: sx, y: sy)
        }
        let w = NSWindow(
            contentRect: NSRect(origin: origin, size: hudSize),
            styleMask: [.borderless],
            backing: .buffered,
            defer: false
        )
        w.isOpaque = false
        w.backgroundColor = .clear
        w.hasShadow = false
        w.ignoresMouseEvents = true
        w.level = .floating
        w.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .ignoresCycle]
        w.isReleasedWhenClosed = false
        clampToScreen(w)

        let cfg = WKWebViewConfiguration()
        cfg.userContentController.add(self, name: "capriHud")
        let wv = WKWebView(frame: NSRect(origin: .zero, size: hudSize), configuration: cfg)
        wv.autoresizingMask = [.width, .height]
        wv.navigationDelegate = self
        wv.setValue(false, forKey: "drawsBackground")
        wv.underPageBackgroundColor = .clear
        wv.load(URLRequest(url: url))
        w.contentView = wv
        window = w
        web = wv
    }

    private func clampToScreen(_ w: NSWindow) {
        let scr = w.screen ?? NSScreen.main ?? NSScreen.screens.first
        guard let vf = scr?.visibleFrame else { return }
        var f = w.frame
        f.origin.x = min(max(f.origin.x, vf.minX + 6), max(vf.minX + 6, vf.maxX - f.width - 6))
        f.origin.y = min(max(f.origin.y, vf.minY + 6), max(vf.minY + 6, vf.maxY - f.height - 6))
        w.setFrameOrigin(f.origin)
    }

    private func saveOrigin(_ o: NSPoint) {
        UserDefaults.standard.set(["x": Double(o.x), "y": Double(o.y)], forKey: "capriHudOrigin")
    }

    private func startMouseWatch() {
        stopMouseWatch()
        let t = Timer(timeInterval: 1.0 / 30.0, repeats: true) { [weak self] _ in
            guard let self = self, let w = self.window, w.isVisible else { return }
            let m = NSEvent.mouseLocation
            let f = w.frame
            // Click-through everywhere except Capri's opaque pixels and the HUD card
            if !f.contains(m) {
                if !w.ignoresMouseEvents && NSEvent.pressedMouseButtons == 0 {
                    w.ignoresMouseEvents = true
                }
            } else if !self.hitTestBusy && (NSEvent.pressedMouseButtons == 0 || w.ignoresMouseEvents) {
                let lx = m.x - f.minX
                let ly = f.maxY - m.y
                self.hitTestBusy = true
                self.web?.evaluateJavaScript("window.capriHitTest ? window.capriHitTest(\(String(format: "%.1f,%.1f", lx, ly))) : false") { [weak self, weak w] r, _ in
                    self?.hitTestBusy = false
                    guard let w = w, w.isVisible else { return }
                    let hit = (r as? Bool) ?? false
                    let wantIgnore = !hit
                    if w.ignoresMouseEvents != wantIgnore && (NSEvent.pressedMouseButtons == 0 || !wantIgnore) {
                        w.ignoresMouseEvents = wantIgnore
                    }
                }
            }
            // Update eye gaze at ~12 Hz
            let now = Date()
            if now.timeIntervalSince(self.lastHitCheck) >= 0.08 {
                self.lastHitCheck = now
                let hx = f.minX + 106
                let hy = f.minY + 158
                let nx = max(-1.0, min(1.0, (m.x - hx) / 360.0))
                let ny = max(-1.0, min(1.0, (hy - m.y) / 280.0))
                let sig = String(format: "%.2f,%.2f", nx, ny)
                if sig != self.lastGaze {
                    self.lastGaze = sig
                    self.web?.evaluateJavaScript("window.setGlobalPointer && window.setGlobalPointer(\(sig))", completionHandler: nil)
                }
            }
        }
        RunLoop.main.add(t, forMode: .common)
        mouseTimer = t
    }

    private func stopMouseWatch() {
        mouseTimer?.invalidate()
        mouseTimer = nil
    }

    func userContentController(_ c: WKUserContentController, didReceive m: WKScriptMessage) {
        guard m.name == "capriHud", let dict = m.body as? [String: Any], let action = dict["action"] as? String else { return }
        switch action {
        case "move":
            guard let w = window, let dx = dict["dx"] as? Double, let dy = dict["dy"] as? Double else { return }
            var f = w.frame
            f.origin.x += dx
            f.origin.y -= dy
            w.setFrameOrigin(f.origin)
            clampToScreen(w)
            saveOrigin(w.frame.origin)
        case "teleport":
            guard let w = window, let corner = dict["corner"] as? String else { return }
            let vf = (w.screen ?? NSScreen.main ?? NSScreen.screens.first)?.visibleFrame ?? NSRect(x: 0, y: 0, width: 1280, height: 800)
            let pad: CGFloat = 14
            var o = w.frame.origin
            switch corner {
            case "bottom-left":  o = NSPoint(x: vf.minX + pad, y: vf.minY + pad)
            case "top-right":    o = NSPoint(x: vf.maxX - hudSize.width - pad, y: vf.maxY - hudSize.height - pad)
            case "top-left":     o = NSPoint(x: vf.minX + pad, y: vf.maxY - hudSize.height - pad)
            default:             o = NSPoint(x: vf.maxX - hudSize.width - pad, y: vf.minY + pad)
            }
            w.setFrameOrigin(o)
            saveOrigin(w.frame.origin)
        case "openDeck":
            onOpenDeck?()
        case "hide":
            onHide?()
        default:
            break
        }
    }

    private func scheduleRetry() {
        retry?.invalidate()
        retry = Timer.scheduledTimer(withTimeInterval: 4, repeats: false) { [weak self] _ in
            guard let self = self, let w = self.web else { return }
            w.load(URLRequest(url: self.url))
        }
    }

    func webView(_ w: WKWebView, didFailProvisionalNavigation n: WKNavigation!, withError e: Error) { scheduleRetry() }
    func webView(_ w: WKWebView, didFail n: WKNavigation!, withError e: Error) { scheduleRetry() }
    func webViewWebContentProcessDidTerminate(_ w: WKWebView) { scheduleRetry() }
}

final class DeckWindow: NSObject, NSWindowDelegate, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler {
    let url = URL(string: hubBase + "/?nohud=1")!
    var window: NSWindow?
    var web: WKWebView?
    var retry: Timer?
    var onClose: (() -> Void)?
    var getCapriEnabled: (() -> Bool)?
    var onCapriChange: ((Bool) -> Void)?

    var isOpen: Bool { window?.isVisible == true }
    let cover = PageCover()

    func pushCapri(_ on: Bool) {
        web?.evaluateJavaScript("window.setCapriEnabled && window.setCapriEnabled(\(on ? "true" : "false"))", completionHandler: nil)
    }

    func userContentController(_ c: WKUserContentController, didReceive m: WKScriptMessage) {
        guard m.name == "capri" else { return }
        if let msg = m.body as? String, msg == "ready" {
            pushCapri(getCapriEnabled?() ?? true)
        } else if let on = m.body as? Bool {
            onCapriChange?(on)
        }
    }

    func show() {
        if window == nil { build() } else if let w = web, window?.isVisible != true { cover.show(over: w) }
        web?.evaluateJavaScript("window.setActive && window.setActive(true);", completionHandler: nil)
        window?.makeKeyAndOrderFront(nil)
        NSApp.activate(ignoringOtherApps: true)
    }

    func reload() { web?.load(URLRequest(url: url)) }
    func close() {
        cover.keep(web) { [weak self] in
            self?.web?.evaluateJavaScript("window.setActive && window.setActive(false);", completionHandler: nil)
            self?.window?.orderOut(nil)
            self?.onClose?()
        }
    }

    private func build() {
        let w = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1280, height: 820),
                         styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)
        w.title = "Agent Monitor"
        w.titlebarAppearsTransparent = true   // a dark title bar above the page (the page starts below it)
        w.appearance = NSAppearance(named: .darkAqua)
        w.backgroundColor = NSColor(srgbRed: 0.04, green: 0.04, blue: 0.04, alpha: 1)
        w.minSize = NSSize(width: 480, height: 520)
        w.isReleasedWhenClosed = false
        w.tabbingMode = .disallowed
        w.delegate = self
        w.center()
        w.setFrameAutosaveName("AgentMonitorWindow")   // where you left it, next time
        // Its own storage, apart from the popover's: the page keeps settings in localStorage, and the popover's (the small 4x4 "panel
        // view" board among them) squashed the tiles here. The window keeps its own layout and filters from now on.
        let cfg = WKWebViewConfiguration()
        if #available(macOS 14.0, *), let id = UUID(uuidString: "5C0FA1E2-7B3D-4E8A-9C61-2D4F8B7A0E13") { cfg.websiteDataStore = WKWebsiteDataStore(forIdentifier: id) }
        cfg.userContentController.add(self, name: "capri")
        let wv = WKWebView(frame: w.contentLayoutRect, configuration: cfg)
        wv.autoresizingMask = [.width, .height]
        wv.navigationDelegate = self
        wv.uiDelegate = self
        wv.underPageBackgroundColor = w.backgroundColor
        wv.allowsMagnification = true
        wv.load(URLRequest(url: url))
        w.contentView = wv
        window = w; web = wv
    }

    func windowShouldClose(_ sender: NSWindow) -> Bool {
        close()
        return false
    }

    func windowWillClose(_ n: Notification) {
        retry?.invalidate()
        web?.configuration.userContentController.removeScriptMessageHandler(forName: "capri")
        web?.stopLoading(); web?.navigationDelegate = nil; web?.uiDelegate = nil
        window?.delegate = nil
        web = nil; window = nil
        onClose?()
    }

    private func offline() {
        web?.loadHTMLString("""
        <body style="background:#0A0A0A;color:#C9C5BC;font:13px ui-monospace,Menlo,monospace;display:flex;\
        align-items:center;justify-content:center;height:100vh;margin:0;text-align:center"><div>\
        <div style="color:#FF4D00;font-size:15px;margin-bottom:10px">■ hub not reachable</div>\
        <div>nothing is answering on 127.0.0.1:4040</div>\
        <div style="opacity:.55;margin-top:10px">start it: npm start (in Pi-5-Monitor)<br>retrying…</div></div></body>
        """, baseURL: nil)
        retry?.invalidate()
        retry = Timer.scheduledTimer(withTimeInterval: 4, repeats: false) { [weak self] _ in self?.reload() }
    }
    func webView(_ w: WKWebView, didFailProvisionalNavigation n: WKNavigation!, withError e: Error) { offline() }
    func webView(_ w: WKWebView, didFail n: WKNavigation!, withError e: Error) { offline() }
    func webViewWebContentProcessDidTerminate(_ w: WKWebView) { reload() }
    // Links that leave the hub open in the real browser.
    func webView(_ w: WKWebView, decidePolicyFor a: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if let u = a.request.url, a.navigationType == .linkActivated,
           !["127.0.0.1", "localhost"].contains(u.host ?? ""), u.scheme?.hasPrefix("http") == true {
            NSWorkspace.shared.open(u); decisionHandler(.cancel); return
        }
        decisionHandler(.allow)
    }
    func webView(_ w: WKWebView, createWebViewWith c: WKWebViewConfiguration, for a: WKNavigationAction, windowFeatures f: WKWindowFeatures) -> WKWebView? {
        if let u = a.request.url { NSWorkspace.shared.open(u) }
        return nil
    }
    // The page's confirm() / alert() (e.g. "stop this agent?") as sheets on the window.
    func webView(_ w: WKWebView, runJavaScriptAlertPanelWithMessage m: String, initiatedByFrame f: WKFrameInfo, completionHandler: @escaping () -> Void) {
        let al = NSAlert(); al.messageText = m
        if let win = window { al.beginSheetModal(for: win) { _ in completionHandler() } } else { al.runModal(); completionHandler() }
    }
    func webView(_ w: WKWebView, runJavaScriptConfirmPanelWithMessage m: String, initiatedByFrame f: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        let al = NSAlert(); al.messageText = m
        al.addButton(withTitle: "OK"); al.addButton(withTitle: "Cancel")
        if let win = window { al.beginSheetModal(for: win) { completionHandler($0 == .alertFirstButtonReturn) } }
        else { completionHandler(al.runModal() == .alertFirstButtonReturn) }
    }
}

final class App: NSObject, NSApplicationDelegate, NSMenuDelegate, NSPopoverDelegate, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler {
    let item: NSStatusItem = {
        // macOS puts a brand-new status item at the far left of the extras, which on a notched,
        // crowded bar is behind the notch (invisible). Seed a spot on the visible side once; after
        // that macOS remembers wherever the user drags it (command-drag).
        let key = "NSStatusItem Preferred Position agents-menu"
        let currentPos = UserDefaults.standard.double(forKey: key)
        if currentPos == 0 || currentPos >= 520 {
            UserDefaults.standard.set(seedPosition, forKey: key)
        }
        let i = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
        i.autosaveName = "agents-menu"
        return i
    }()
    let menu = NSMenu()
    let popover = NSPopover()
    var web: WKWebView?          // created fresh on every show, dropped on close (see makeWeb)
    let webHost = NSView()       // the popover's content: a dark backdrop the web view sits in
    var webFailed = false
    var retry: Timer?

    var overallShort = Win(), overallWeek = Win()   // over the focused accounts (= hub's overall when none)
    var hubShort = Win(), hubWeek = Win()           // the hub's overall, over all accounts
    var accounts: [Acct] = []
    /// The ticked accounts — the ones whose usage is shown. nil = all three (the default). A set means exactly those,
    /// and an EMPTY set means nothing is ticked, so no usage is shown. Click an account to tick / untick it (remembered).
    /// Saved values from before "nothing ticked = nothing shown" have no `focusExplicit` flag and mean the default.
    var focus: Set<String>? = {
        let d = UserDefaults.standard
        guard d.bool(forKey: "focusExplicit"), let a = d.stringArray(forKey: "focusAccounts") else { return nil }
        return Set(a.flatMap { $0 == "agy" ? ["agy-work", "agy-personal", "agy-free"] : [$0] })   // (saved while antigrav was one account)
    }()
    /// Ticked backup tools (codex / cursor / copilot …) whose usage replaces the Claude overall in the bar.
    /// nil / empty = none (the bar keeps the account overall). Remembered; kept in sync with the page's dock pills.
    var toolFocus: Set<String> = {
        Set(UserDefaults.standard.stringArray(forKey: "focusTools") ?? [])
    }()
    var menuOpen = false
    var lastBarSig = ""
    var pollTimer: Timer?
    var pollEvery: TimeInterval = 0
    var shares: [Share] = []
    var splitOwner = ""
    var refreshing = false
    var asOf: String?
    var counts = Counts()
    var online = false

    let header = HeaderRow(), shortRow = LimitRow(), weekRow = LimitRow()
    let hintRow = NoteRow()
    let splitRow = SplitRow()
    let agentsRow = NoteRow()
    let metricsRow = MetricsRow()   // Pi telemetry + Docker + macOS memory metrics
    let totalUsageRow = TotalUsageRow() // today, 7-day and 30-day totals across every agent and company
    var localTokensOnly = ""
    var piStatusItem: NSMenuItem!
    var piConnected = false
    var piSimulated = false
    var piTemperatureC: Double?
    var piCPUPercent: Double?
    var piFanRPM: Int?
    var piLastSeen = "Never"
    var splitItem: NSMenuItem!
    var acctItems: [NSMenuItem] = []

    // The agents section of the details menu: one item (with a submenu) per live agent, inserted under `agentsItem`.
    let maxAgentsShown = 12
    var agentsItem: NSMenuItem!
    var agentItems: [NSMenuItem] = []
    var agents: [AgentInfo] = []
    var hand: [HandSession] = []   // sessions started by hand in a terminal (read with the extras)
    var lastAgentSig = ""
    var pendingMenuRebuild = false   // data changed while the pointer was on an agent item: rebuild once it moves off / the menu closes
    // Percentage usage and what the hand-over dialog can start; read when the menu opens.
    let toolsHead = HeaderRow()
    let toolRows = (0..<12).map { _ in NoteRow() }   // codex, cursor, kiro, opencode, gemini, antigrav, the local model (+1)
    var toolItems: [NSMenuItem] = []                 // legacy: still set for the self-test
    var toolMenuItems: [NSMenuItem] = []             // the actual menu items with submenus
    var toolsSep: NSMenuItem!, toolsHeadItem: NSMenuItem!
    var tools: [ToolInfo] = []
    var handTargets: [String: Bool] = [:]   // /api/handover/targets: is the program on this Mac?
    var claudeLogins: [String] = []         // /v1/accounts: the Claude logins an agent can continue on
    var lastExtras = Date.distantPast
    // System metrics: Docker containers memory + macOS memory pressure
    var dockerLine = ""
    var memLine = ""
    var localLine = ""          // odysseus / local model status: loaded models, opencode running
    var localUsageLine = ""     // opencode token totals from /api/local-usage
    var metricsOnline = false
    var lastMetricsRefresh = Date.distantPast
    // Docker Desktop dynamic RAM mode (collectors/docker_mode.js)
    var dockerModeItem: NSMenuItem!
    var dockerModeProfile = "unknown"
    var dockerModeAllocatedGB: Double?
    var dockerModeHostGB: Double = 48.0
    var dockerModeHostAvailGB: Double?
    var dockerModeDaemonUp = false
    var dockerModeSettingsOk = false
    var dockerModeSettingsError = ""
    var dockerModeAppflowyConfigured = false
    var dockerModeAppflowyRun = 0
    var dockerModeAppflowyTotal = 0
    var dockerModeBusy = false
    var dockerModeWasBusy = false
    var dockerModeStep = ""
    var dockerModePollTimer: Timer?
    // The last thing an item of this menu did ("focused its terminal", "couldn't …"), shown for a minute.
    let actionRow = NoteRow()
    var actionItem: NSMenuItem!
    var actionTimer: Timer?
    // Auto-continue on limits: automatically resume Claude & Antigravity agents when limits reset
    var autoContinueAll = false
    var autoContinueMessage = "continue"
    var autoContinueItem: NSMenuItem!
    var autoContinueAgents: [String: [String: Any]] = [:]
    // Capri HUD companion: toggleable from the menubar menu and synced with the Agent Monitor window + web settings
    var capriEnabled: Bool = {
        UserDefaults.standard.object(forKey: "capriEnabled") as? Bool ?? true
    }()
    var capriItem: NSMenuItem!
    // Folder broadcast: multi-agent / multi-company clusters from /api/agents/broadcast
    var broadcastClusters: [BroadcastCluster] = []
    var broadcastItem: NSMenuItem!
    // A call to make on the deck page once it has started (the popover builds a fresh page on every show).
    var pendingPage: String?
    var lastDeckCall = ""   // self-test: what the last deck-opening item asked of the page
    var confirmHook: ((String, String) -> Bool)?   // self-test: answers the confirmation without a dialog

    let deckWindow = DeckWindow()
    let capriHUD = CapriHUDWindow()

    func applicationDidFinishLaunching(_ n: Notification) {
        NSApp.applicationIconImage = appIcon()
        deckWindow.onClose = { NSApp.setActivationPolicy(.accessory) }   // window gone: back to a menu bar item only (no Dock icon)
        deckWindow.getCapriEnabled = { [weak self] in self?.capriEnabled ?? true }
        deckWindow.onCapriChange = { [weak self] on in self?.setCapriEnabled(on, pushWindow: false) }
        capriHUD.onHide = { [weak self] in
            self?.setCapriEnabled(false)
            self?.say("Capri HUD hidden (re-enable from menu)")
        }
        capriHUD.onOpenDeck = { [weak self] in self?.openWindow() }
        NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(willPowerOff(_:)), name: NSWorkspace.willPowerOffNotification, object: nil)
        // A second launch (Finder, Spotlight, `open`) while this one runs asks it to show the window, then quits (see the end of the file).
        DistributedNotificationCenter.default().addObserver(self, selector: #selector(openWindow), name: showWindowNote, object: nil)
        installMainMenu()
        buildPopover()
        buildMenu()
        if let b = item.button {
            b.target = self
            b.action = #selector(clicked(_:))
            b.sendAction(on: [.leftMouseDown, .rightMouseDown])
        }
        render()
        refresh()
        refreshExtras(force: true)
        schedulePolling()
        preloadWeb()

        // Test hooks: `--popover` / `--menu` open the UI shortly after launch (for screenshots).
        let args = CommandLine.arguments
        // Opened as an app (Finder, Dock, Spotlight: no switches): show the window. At login (`--login`, the LaunchAgent) and under the
        // test switches it starts as the menu bar item only. `--window` opens it too (screenshots).
        if args.count == 1 || args.contains("--window") { DispatchQueue.main.async { self.openWindow() } }
        if !args.contains("--selftest"), !args.contains("--toggletest"), capriEnabled {
            DispatchQueue.main.async { self.capriHUD.show() }
        }
        if args.contains("--pin") || args.contains("--selftest") { selfTesting = true; popover.behavior = .applicationDefined }   // test: stop outside clicks closing it
        if args.contains("--popover") { DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { self.showPopover() } }
        if args.contains("--menu") { DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { self.showMenu() } }
        if args.contains("--toggletest") {   // click the icon 4 times through the button action; the popover must alternate
            for (i, t) in [1.5, 2.3, 3.1, 3.9].enumerated() {
                DispatchQueue.main.asyncAfter(deadline: .now() + t) {
                    self.item.button?.performClick(nil)
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
                        tlog("click \(i + 1): popover is \(self.popover.isShown ? "OPEN" : "CLOSED") (expected \(i % 2 == 0 ? "OPEN" : "CLOSED"))")
                        if i == 3 { exit(0) }
                    }
                }
            }
        }
        if args.contains("--reopen") {   // test: show, close, show again
            DispatchQueue.main.asyncAfter(deadline: .now() + 4.0) { self.closePopover() }
            DispatchQueue.main.asyncAfter(deadline: .now() + 6.0) { self.showPopover() }
        }
        if args.contains("--selftest") {
            func trySelfTest(retries: Int) {
                if !self.accounts.isEmpty || retries <= 0 {
                    self.selfTest()
                } else {
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { trySelfTest(retries: retries - 1) }
                }
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { trySelfTest(retries: 15) }
        }
        if let a = args.first(where: { $0.hasPrefix("--focus=") }) {   // e.g. --focus=work,agy
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { self.setFocus(a.dropFirst(8) == "none" ? Set<String>() : Set(a.dropFirst(8).split(separator: ",").map(String.init)), persist: false) }
        }
    }

    // Edit shortcuts (copy/paste in the deck's text boxes) need a main menu even for a menu bar app.
    func installMainMenu() {
        let main = NSMenu(), appItem = NSMenuItem(), fileItem = NSMenuItem(), editItem = NSMenuItem(), viewItem = NSMenuItem(), winItem = NSMenuItem()
        for mi in [appItem, fileItem, editItem, viewItem, winItem] { main.addItem(mi) }
        let appM = NSMenu(title: "Agent Monitor")
        appM.addItem(withTitle: "About Agent Monitor", action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)), keyEquivalent: "")
        appM.addItem(.separator())
        appM.addItem(withTitle: "Hide Agent Monitor", action: #selector(NSApplication.hide(_:)), keyEquivalent: "h")
        appM.addItem(.separator())
        appM.addItem(withTitle: "Quit Agent Monitor", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
        appItem.submenu = appM
        let file = NSMenu(title: "File")
        file.addItem(withTitle: "Close Window", action: #selector(NSWindow.performClose(_:)), keyEquivalent: "w")
        fileItem.submenu = file
        let view = NSMenu(title: "View")
        view.addItem(withTitle: "Reload", action: #selector(reloadWindow), keyEquivalent: "r").target = self
        view.addItem(withTitle: "Open in Browser", action: #selector(openDash), keyEquivalent: "").target = self
        viewItem.submenu = view
        let win = NSMenu(title: "Window")
        win.addItem(withTitle: "Minimize", action: #selector(NSWindow.performMiniaturize(_:)), keyEquivalent: "m")
        win.addItem(withTitle: "Zoom", action: #selector(NSWindow.performZoom(_:)), keyEquivalent: "")
        winItem.submenu = win
        NSApp.windowsMenu = win
        let edit = NSMenu(title: "Edit")
        edit.addItem(withTitle: "Cut", action: #selector(NSText.cut(_:)), keyEquivalent: "x")
        edit.addItem(withTitle: "Copy", action: #selector(NSText.copy(_:)), keyEquivalent: "c")
        edit.addItem(withTitle: "Paste", action: #selector(NSText.paste(_:)), keyEquivalent: "v")
        edit.addItem(withTitle: "Select All", action: #selector(NSText.selectAll(_:)), keyEquivalent: "a")
        editItem.submenu = edit
        NSApp.mainMenu = main
    }

    // MARK: popover (the deck)

    /// 460 wide, and as tall as the screen allows (700 at least, 920 at most): the agent panel's stats, last prompt and buttons
    /// need more than 700, and the page lays itself out to the height it is given.
    func popoverSize() -> NSSize {
        let screen = item.button?.window?.screen ?? NSScreen.main
        let room = (screen?.visibleFrame.height ?? 740) - 40   // the menu bar is already out of visibleFrame; 40 = arrow + a margin
        return NSSize(width: 460, height: min(920, max(700, room.rounded())))
    }

    func buildPopover() {
        let size = popoverSize()
        webHost.frame = NSRect(origin: .zero, size: size)
        webHost.wantsLayer = true
        webHost.layer?.backgroundColor = NSColor(srgbRed: 0.04, green: 0.04, blue: 0.04, alpha: 1).cgColor
        let vc = NSViewController()
        vc.view = webHost
        popover.contentViewController = vc
        popover.contentSize = size
        // Closing is ours, not NSPopover's `.transient`: that closes on mouse-DOWN, so the click on the icon that should close
        // it reaches the button afterwards, finds it closed and re-opens it. Now: icon click toggles, and it also closes on a click
        // in another app (global monitor), when you switch apps, and on Escape.
        popover.behavior = .applicationDefined
        popover.animates = false
        popover.appearance = NSAppearance(named: .darkAqua)
        popover.delegate = self
    }

    /// A pre-warmed web view that stays alive across popovers for instant deck/agents view loading.
    /// When the popover closes, window.setActive(false) pauses rendering and polling (0% CPU).
    /// When the popover opens, window.setActive(true) immediately wakes it without re-creating the view.
    func makeWeb() {
        dropWeb()
        let cfg = WKWebViewConfiguration()
        cfg.userContentController.add(self, name: "focus")       // the page's account pills report selection changes
        cfg.userContentController.add(self, name: "toolFocus")   // the dock's codex / cursor / … pills: show their usage in the bar
        cfg.userContentController.add(self, name: "capri")       // sync Capri companion toggle with web Settings
        let w = WKWebView(frame: webHost.bounds, configuration: cfg)
        w.autoresizingMask = [.width, .height]
        w.navigationDelegate = self
        w.uiDelegate = self
        w.underPageBackgroundColor = NSColor(srgbRed: 0.04, green: 0.04, blue: 0.04, alpha: 1)
        webHost.addSubview(w)
        web = w
        webFailed = false
        w.load(URLRequest(url: deckURL))
    }

    func preloadWeb() {
        if web == nil {
            makeWeb()
        }
    }

    func dropWeb() {
        retry?.invalidate()
        guard let w = web else { return }
        w.stopLoading()
        w.configuration.userContentController.removeScriptMessageHandler(forName: "focus")
        w.configuration.userContentController.removeScriptMessageHandler(forName: "toolFocus")
        w.configuration.userContentController.removeScriptMessageHandler(forName: "capri")
        w.navigationDelegate = nil; w.uiDelegate = nil
        w.removeFromSuperview()
        web = nil
    }

    let cover = PageCover()      // the page's picture, up the moment the popover opens (see PageCover)
    var closing = false
    func closePopover() {
        guard popover.isShown, !closing else { return }
        guard !webFailed, !selfTesting else { popover.close(); return }
        closing = true
        cover.keep(web) { [weak self] in self?.closing = false; self?.popover.close() }
    }

    func showPopover() {
        guard let b = item.button else { return }
        tShow = Date(); dlog("show requested")
        let size = popoverSize()   // the screen (or its Dock) may have changed since the last show
        // Resize only. NSPopover puts the content view 13 pt inside its window (the border and shadow) when it first shows it and leaves
        // it there; resetting the whole frame to origin (0,0) here moved the page 13 pt left and down on every open after the first.
        webHost.setFrameSize(size)
        popover.contentSize = size
        if web == nil || webFailed {
            popover.show(relativeTo: b.bounds, of: b, preferredEdge: .minY)
            popover.contentViewController?.view.window?.makeKey()
            makeWeb()
        } else {
            if web?.superview == nil { webHost.addSubview(web!) }
            web?.frame = webHost.bounds
            if let w = web { cover.show(over: w) }
            let allIds = accounts.isEmpty ? ["work", "personal", "agy-work", "agy-personal", "agy-free"] : accounts.map { $0.id }
            let set = focus ?? Set(allIds)
            let fIds = "[" + set.sorted().map { "\"\($0)\"" }.joined(separator: ",") + "]"
            let tIds = "[" + toolFocus.sorted().map { "\"\($0)\"" }.joined(separator: ",") + "]"
            let batchJS = "document.documentElement.classList.remove('loading'); window.setActive && window.setActive(true); typeof window.setFocusAccounts === 'function' && window.setFocusAccounts(\(fIds)); typeof window.setFocusTools === 'function' && window.setFocusTools(\(tIds)); window.setCapriEnabled && window.setCapriEnabled(\(capriEnabled ? "true" : "false"));"
            web?.evaluateJavaScript(batchJS, completionHandler: nil)
            popover.show(relativeTo: b.bounds, of: b, preferredEdge: .minY)
            popover.contentViewController?.view.window?.makeKey()
            runPendingPage()
        }
        refresh()
    }

    @objc func clicked(_ sender: NSStatusBarButton) {
        dlog("clicked: popover.isShown=\(popover.isShown) event=\(NSApp.currentEvent.map { "\($0.type.rawValue)@\($0.timestamp)" } ?? "nil")")
        let e = NSApp.currentEvent
        let isRight = e?.type == .rightMouseDown || e?.type == .rightMouseUp || e?.modifierFlags.contains(.control) == true
        if isRight {
            if popover.isShown { closePopover() }
            showMenu()
        } else if popover.isShown {
            closePopover()
        } else {
            showPopover()
        }
    }

    // MARK: hiding the popover
    // A transient NSPopover from a menu bar (accessory) app can miss clicks that land on other apps'
    // windows or the desktop, and it stays up when you switch apps. Watch for both ourselves so the
    // window always hides.
    var outsideClickMonitor: Any?

    var escapeMonitor: Any?

    func popoverDidShow(_ notification: Notification) {
        dlog("popoverDidShow")
        if let m = escapeMonitor { NSEvent.removeMonitor(m) }
        escapeMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] e in
            if e.keyCode == 53, self?.popover.isShown == true, !selfTesting { self?.closePopover(); return nil }   // Escape
            return e
        }
        schedulePolling()
        if let m = outsideClickMonitor { NSEvent.removeMonitor(m) }
        // Global monitors only see events meant for other apps, so clicks inside the popover or on our
        // own menu bar button are untouched.
        outsideClickMonitor = NSEvent.addGlobalMonitorForEvents(
            matching: [.leftMouseDown, .rightMouseDown, .otherMouseDown]) { [weak self] e in
            dlog("global mouse event type=\(e.type.rawValue) at \(NSEvent.mouseLocation) icon=\(String(describing: self?.item.button?.window?.frame))")
            guard let self = self else { return }
            // A click on OUR OWN icon belongs to the icon's toggle. Closing here too would close it on mouse-down and
            // then the icon's action (on mouse-up) would find it closed and open it again: "click to hide does nothing".
            if self.mouseIsOnIcon() { dlog("click on our own icon -> left to the toggle"); return }
            dlog("outside click -> close")
            if !selfTesting { self.closePopover() }
        }
    }

    func popoverDidClose(_ notification: Notification) {
        dlog("popoverDidClose")
        pendingPage = nil   // a call that never got its page must not fire on some later open
        if let m = escapeMonitor { NSEvent.removeMonitor(m); escapeMonitor = nil }
        setPageActive(false)
        schedulePolling()
        if let m = outsideClickMonitor { NSEvent.removeMonitor(m); outsideClickMonitor = nil }
    }

    /// True while the pointer is over our menu bar icon. Pressing the icon makes the app lose focus and the monitor see a
    /// click, but that press is the toggle's: closing here would shut the popover on mouse-down and the same click
    /// (mouse-up) would then open it again.
    func mouseIsOnIcon() -> Bool {
        guard let w = item.button?.window else { return false }
        return w.frame.insetBy(dx: -3, dy: -3).contains(NSEvent.mouseLocation)
    }

    func applicationDidResignActive(_ notification: Notification) {
        dlog("resignActive (popover shown=\(popover.isShown))")
        if popover.isShown && !selfTesting && !mouseIsOnIcon() { closePopover() }
    }

    func showMenu() {
        guard let b = item.button else { return }
        if popover.isShown { closePopover() }
        menuOpen = true
        rebuildAgentMenu(force: false)
        redrawRows()
        menu.popUp(positioning: nil, at: NSPoint(x: 0, y: b.bounds.height + 4), in: b)
    }

    func showOffline() {
        webFailed = true
        web?.loadHTMLString("""
        <body style="background:#0A0A0A;color:#C9C5BC;font:13px ui-monospace,Menlo,monospace;display:flex;\
        align-items:center;justify-content:center;height:100vh;margin:0;text-align:center"><div>\
        <div style="color:#FF4D00;font-size:15px;margin-bottom:10px">■ hub not reachable</div>\
        <div>nothing is answering on 127.0.0.1:4040</div>\
        <div style="opacity:.55;margin-top:10px">start it: npm start (in Pi-5-Monitor)<br>retrying…</div></div></body>
        """, baseURL: nil)
        retry?.invalidate()
        retry = Timer.scheduledTimer(withTimeInterval: 4, repeats: false) { [weak self] _ in
            self?.web?.load(URLRequest(url: deckURL))
        }
    }

    func webView(_ w: WKWebView, didFailProvisionalNavigation n: WKNavigation!, withError e: Error) { dlog("web didFailProvisional \(e.localizedDescription)"); showOffline() }
    func webView(_ w: WKWebView, didFail n: WKNavigation!, withError e: Error) { dlog("web didFail \(e.localizedDescription)"); showOffline() }
    func webView(_ w: WKWebView, didStartProvisionalNavigation n: WKNavigation!) { dlog("web start \(w.url?.absoluteString ?? "-")") }
    func webView(_ w: WKWebView, didCommit n: WKNavigation!) { dlog("web commit") }
    /// The web content process can be killed (memory pressure, crash); without this the popover stays blank.
    func webViewWebContentProcessDidTerminate(_ w: WKWebView) { dlog("web process terminated -> reload"); makeWeb() }
    func webView(_ w: WKWebView, didFinish n: WKNavigation!) {
        dlog("web didFinish \(w.url?.absoluteString ?? "-") popoverShown=\(popover.isShown)")
        if w.url?.host == "127.0.0.1" {
            webFailed = false
            pushFocus()
            pushToolFocus()
            if popover.isShown {
                setPageActive(true)
                runPendingPage()
            } else {
                setPageActive(false)
            }
        }
    }
    func userContentController(_ c: WKUserContentController, didReceive m: WKScriptMessage) {
        if m.name == "toolFocus" {
            guard let ids = m.body as? [String] else { return }
            setToolFocus(Set(ids))
            return
        }
        if m.name == "capri" {
            if let msg = m.body as? String, msg == "ready" {
                web?.evaluateJavaScript("window.setCapriEnabled && window.setCapriEnabled(\(capriEnabled ? "true" : "false"))", completionHandler: nil)
            } else if let on = m.body as? Bool {
                setCapriEnabled(on, pushPopover: false)
            }
            return
        }
        guard m.name == "focus" else { return }
        if let msg = m.body as? String, msg == "ready" {   // the page's script finished starting: give it our state
            dlog("page ready"); pushFocus(); pushToolFocus()
            if popover.isShown {
                setPageActive(true)
                runPendingPage()
            } else {
                setPageActive(false)
            }
            if debugLog {   // what the web view actually shows, a moment later (debug runs only)
                for ms in [150, 400, 1500] {
                    DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(ms)) { [weak self] in
                        self?.web?.evaluateJavaScript("document.documentElement.className + ' | body opacity=' + getComputedStyle(document.body).opacity + ' | tiles=' + document.querySelectorAll('.tile').length + ' | rearrange hidden=' + (getComputedStyle(document.getElementById('swap-toggle')).display === 'none') + ' | width=' + innerWidth") { r, _ in dlog("page state +\(ms)ms after ready: \(String(describing: r))") }
                    }
                }
            }
            return
        }
        guard let ids = m.body as? [String] else { return }
        setFocus(Set(ids))
    }
    /// Tell the page whether it's on screen; hidden, it stops rendering and polling.
    func setPageActive(_ on: Bool) {
        web?.evaluateJavaScript("window.setActive && window.setActive(\(on))", completionHandler: nil)
    }
    func pushFocus() {
        let allIds = accounts.isEmpty ? ["work", "personal", "agy-work", "agy-personal", "agy-free"] : accounts.map { $0.id }
        let set = focus ?? Set(allIds)
        let ids = "[" + set.sorted().map { "\"\($0)\"" }.joined(separator: ",") + "]"
        web?.evaluateJavaScript("typeof window.setFocusAccounts === 'function' ? (window.setFocusAccounts(\(ids)), 'applied') : 'page not ready'") { r, e in
            dlog("pushFocus \(ids) -> \(String(describing: r)) err=\(String(describing: e))")
        }
    }
    func pushToolFocus() {
        let ids = "[" + toolFocus.sorted().map { "\"\($0)\"" }.joined(separator: ",") + "]"
        web?.evaluateJavaScript("typeof window.setFocusTools === 'function' ? (window.setFocusTools(\(ids)), 'applied') : 'page not ready'") { r, e in
            dlog("pushToolFocus \(ids) -> \(String(describing: r)) err=\(String(describing: e))")
        }
    }
    // Links that leave the hub open in the real browser instead of inside the popover.
    func webView(_ w: WKWebView, decidePolicyFor a: WKNavigationAction,
                 decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if let u = a.request.url, a.navigationType == .linkActivated,
           !["127.0.0.1", "localhost"].contains(u.host ?? ""), u.scheme?.hasPrefix("http") == true {
            NSWorkspace.shared.open(u); decisionHandler(.cancel); return
        }
        decisionHandler(.allow)
    }
    func webView(_ w: WKWebView, createWebViewWith c: WKWebViewConfiguration, for a: WKNavigationAction,
                 windowFeatures f: WKWindowFeatures) -> WKWebView? {
        if let u = a.request.url { NSWorkspace.shared.open(u) }
        return nil
    }

    // MARK: details menu

    func buildMenu() {
        menu.autoenablesItems = false
        menu.delegate = self
        func add(_ v: NSView) -> NSMenuItem {
            let mi = NSMenuItem(); mi.view = v; menu.addItem(mi); return mi
        }
        _ = add(header)
        _ = add(shortRow)
        _ = add(weekRow)
        menu.addItem(.separator())
        for i in 0..<6 {   // standard items, not views: AppKit doesn't deliver clicks to custom-view rows
            let mi = NSMenuItem(title: "Focus", action: #selector(toggleAccount(_:)), keyEquivalent: "")
            mi.target = self; mi.tag = i; mi.isHidden = true
            menu.addItem(mi)
            acctItems.append(mi)
        }
        hintRow.line = "tick the accounts whose usage you want shown · untick all to hide it"
        _ = add(hintRow)
        splitItem = add(splitRow)
        menu.addItem(.separator())
        agentsItem = add(agentsRow)   // the agents (one submenu item each) are inserted right under this row
        metricsRow.dockerLine = "no system metrics"
        metricsRow.memLine = ""
        metricsRow.localLine = "odyssеus local models: —"
        metricsRow.localUsageLine = ""
        piStatusItem = NSMenuItem(title: "Raspberry Pi 5 · not connected", action: #selector(openPiStatus), keyEquivalent: "")
        piStatusItem.target = self
        menu.addItem(piStatusItem)
        _ = add(metricsRow)
        dockerModeItem = NSMenuItem(title: "Docker mode · —", action: nil, keyEquivalent: "")
        menu.addItem(dockerModeItem)
        renderDockerModeMenu()
        _ = add(totalUsageRow)
        menu.addItem(.separator())
        toolsSep = NSMenuItem.separator(); menu.addItem(toolsSep)
        toolsHead.title = "TOOLS · USAGE"
        let toolsHeadTitle = NSAttributedString(string: "TOOLS · USAGE", attributes: [.font: caps, .foregroundColor: accent])
        toolsHeadItem = NSMenuItem(); toolsHeadItem.attributedTitle = toolsHeadTitle
        let afterSepIdx = menu.index(of: toolsSep) + 1
        menu.insertItem(toolsHeadItem, at: afterSepIdx)
        for i in 0..<12 {
            let mi = NSMenuItem(); mi.title = ""   // set in renderTools()
            mi.submenu = NSMenu(); mi.submenu!.autoenablesItems = false
            menu.insertItem(mi, at: afterSepIdx + 1 + i)
            toolMenuItems.append(mi)
            toolItems.append(mi)   // legacy: still set for the self-test
        }
        actionItem = add(actionRow); actionItem.isHidden = true
        menu.addItem(.separator())
        broadcastItem = NSMenuItem(title: "Broadcast to folder…", action: #selector(menuBroadcast(_:)), keyEquivalent: "b")
        broadcastItem.target = self
        broadcastItem.representedObject = ""
        menu.addItem(broadcastItem)
        renderBroadcastMenu()
        autoContinueItem = NSMenuItem(title: "Auto-continue on limits (OFF)", action: #selector(toggleAutoContinue), keyEquivalent: "")
        autoContinueItem.target = self
        menu.addItem(autoContinueItem)
        renderAutoContinue()
        capriItem = NSMenuItem(title: "Capri HUD (ON)", action: #selector(toggleCapri), keyEquivalent: "")
        capriItem.target = self
        menu.addItem(capriItem)
        renderCapriMenu()
        for (title, sel, key) in [("Open Agent Monitor window", #selector(openWindow), "o"),
                                  ("Open dashboard in browser", #selector(openDash), ""),
                                  ("Refresh now", #selector(refreshNow), "r"),
                                  ("Quit Agent Monitor and this menu bar item", #selector(quitAll), "q")] as [(String, Selector, String)] {
            let mi = NSMenuItem(title: title, action: sel, keyEquivalent: key)
            mi.target = self
            menu.addItem(mi)
        }
    }

    var lastQuietRefresh = Date.distantPast
    /// Ask the hub to re-run the usage CLIs (it ignores this if it just did), then re-read — so what you open is fresh.
    func refreshQuiet() {
        guard Date().timeIntervalSince(lastQuietRefresh) > 24 else { return }
        lastQuietRefresh = Date()
        var req = URLRequest(url: refreshURL)
        req.httpMethod = "POST"; req.timeoutInterval = 45
        URLSession.shared.dataTask(with: req) { [weak self] _, _, _ in DispatchQueue.main.async { self?.refresh() } }.resume()
    }

    func menuWillOpen(_ m: NSMenu) {
        guard m == menu else { return }
        menuOpen = true
        rebuildAgentMenu()
        refreshMetrics(force: dockerModeBusy)
        redrawRows()
        schedulePolling()
    }
    func menuDidClose(_ m: NSMenu) { dlog("menuDidClose"); menuOpen = false; schedulePolling(); if pendingMenuRebuild { rebuildAgentMenu(force: true); renderDockerModeMenu() } }

    /// Poll fast (5s) while the popover or menu is open, or a backup tool is pinned to the bar; slowly (15s) otherwise.
    func schedulePolling() {
        let every: TimeInterval = (popover.isShown || menuOpen || !toolFocus.isEmpty) ? 5 : 15
        // Rebuild when the interval changes, or when we start/stop needing tool readings with the popover closed.
        let sig = every + (!toolFocus.isEmpty ? 0.01 : 0)
        guard sig != pollEvery else { return }
        pollEvery = sig
        pollTimer?.invalidate()
        let watching = popover.isShown || menuOpen   // ask the hub for a fresh CLI reading while you are looking
        let t = Timer(timeInterval: every, repeats: true) { [weak self] _ in
            guard let self = self else { return }
            self.refresh()
            if watching { self.refreshQuiet() }
            if !self.toolFocus.isEmpty { self.refreshExtras() }   // a ticked tool's bar figure needs /api/models
            self.refreshLocalUsage()   // odyssеus local-model tokens: 30 s cadence
        }
        t.tolerance = every * 0.2   // let the system coalesce wakeups
        RunLoop.main.add(t, forMode: .common)   // keep updating while the menu is open
        pollTimer = t
    }

    // MARK: self-test (`agents menu --selftest`): no mouse, no screen, never persists the selection

    func selfTest() {
        selfTesting = true
        persistFocus = false
        focus = nil
        recompute()
        render()
        popover.behavior = .applicationDefined   // a live desktop's clicks must not close the popover mid-test
        var fails = 0
        func check(_ name: String, _ ok: Bool, _ detail: @autoclosure () -> String = "") {
            tlog((ok ? "PASS  " : "FAIL  ") + name + (ok ? "" : "   -> " + detail()))
            if !ok { fails += 1 }
        }
        func finish() { tlog(fails == 0 ? "ALL PASS" : "\(fails) FAILED"); exit(fails == 0 ? 0 : 1) }
        func pick(_ i: Int) { menu.performActionForItem(at: menu.index(of: acctItems[i])) }   // what AppKit does on a click
        func states() -> String { acctItems.prefix(accounts.count).map { $0.state == .on ? "✓" : "·" }.joined() }
        func barText() -> String { item.button?.attributedTitle.string ?? "nil" }

        // 7. the agents section of the details menu. First from fixed data (built, sorted, wired; no hub, nothing acts), then against
        // the live hub (one item per live agent) and the live page (the hook the menu's continue / hand-over items call).
        func agentChecks() {
            func agent(_ id: String, _ tool: String, _ status: String, _ title: String, account: String? = nil, ctx: Int? = nil) -> AgentInfo {
                var d: [String: Any] = ["id": id, "tool": tool, "status": status, "title": title, "folder": "demo", "slot": Int(id.suffix(1)) ?? 0]
                if let a = account { d["account"] = ["name": a] }
                if let c = ctx { d["context"] = ["used": c * 10, "window": 1000]; d["costUsd"] = 1.5 }
                return AgentInfo(d)
            }
            func acct(_ id: String, _ five: Int, _ week: Int) -> Acct {
                var a = Acct(); a.id = id; a.label = id == "agy-work" ? "antigrav work" : id == "agy-personal" ? "antigrav personal" : id   // (the hub's labels for the antigrav accounts)
                if id.hasPrefix("agy") { a.unit = "used" }
                a.short = Win(["label": "5h", "percent": five, "state": "live"]); a.week = Win(["label": "7d", "percent": week, "state": "live"])
                return a
            }
            func sub(_ m: NSMenu, _ title: String) -> NSMenu? { m.items.first { $0.title == title }?.submenu }
            func titles(_ m: NSMenu?) -> [String] { (m?.items ?? []).filter { $0.view == nil && !$0.isSeparatorItem }.map { $0.title } }
            func lines(_ m: NSMenu) -> [String] { m.items.compactMap { ($0.view as? NoteRow)?.line } }

            let keep = (agents, tools, handTargets, claudeLogins, accounts, online)
            let keepHand = hand
            let keepClusters = broadcastClusters
            hand = []
            broadcastClusters = []
            online = true
            accounts = [acct("work", 90, 60), acct("personal", 20, 10), acct("agy-work", 30, 30), acct("agy-personal", 20, 40)]
            agents = [agent("ffff6", "codex", "exited", "gone"), agent("eeee5", "shell", "idle", "plain shell"),
                      agent("dddd4", "shell", "idle", "antigrav · demo"), agent("cccc3", "gemini", "running", "Gemini run"),
                      agent("bbbb2", "claude", "idle", "Idle claude", account: "personal"),
                      agent("aaaa1", "claude", "waiting", "Fix the build", account: "work", ctx: 40)]
            tools = [ToolInfo(["id": "codex", "installed": true, "loggedIn": true, "login": "ChatGPT",
                               "usage": ["plan": "free", "windows": [["label": "30d", "percent": 3, "state": "measured"]]]]),
                     ToolInfo(["id": "cursor", "installed": true, "loggedIn": true,
                               "usage": ["plan": "free", "windows": [["label": "Included", "percent": 96, "state": "measured"],
                                                                         ["label": "Auto", "percent": 100, "state": "measured"],
                                                                         ["label": "API", "percent": 0, "state": "measured"]]]]),
                     ToolInfo(["id": "kiro", "label": "kiro", "installed": true, "loggedIn": true,
                               "usage": ["plan": "free", "windows": [["label": "month", "percent": 0, "used": 0, "limit": 50, "unit": "credits", "state": "measured"]]]]),
                     ToolInfo(["id": "opencode", "label": "opencode", "installed": true, "login": "keyless", "keyless": true,
                               "usage": ["plan": "free", "windows": [], "tokens": ["today": ["requests": 2, "input": 16773, "output": 6]]]]),
                     ToolInfo(["id": "gemini", "label": "gemini", "installed": true, "sameAs": "agy", "usage": ["from": "agy", "windows": []]]),
                     ToolInfo(["id": "agy", "label": "antigrav", "installed": true, "loggedIn": true,
                               "usage": ["from": "agy", "group": "Gemini", "windows": [["label": "5h", "percent": 30, "state": "measured"], ["label": "7d", "state": "missing"]],
                                         "profiles": [["id": "agy-work", "label": "antigrav work", "windows": [["label": "7d", "percent": 0, "state": "measured"]]],
                                                      ["id": "agy-personal", "label": "antigrav personal", "windows": [["label": "5h", "percent": 100, "state": "measured"]]]],
                                         "others": [["group": "Claude + GPT", "short": 100, "week": 100]]]])]
            handTargets = ["agy-work": true, "agy-personal": true, "local": false, "codex": true, "cursor": true, "kiro": true, "opencode": false, "gemini": true]
            claudeLogins = ["work", "personal"]
            showAgyTool = true
            render(); rebuildAgentMenu(force: true)

            let names = agentItems.map { $0.attributedTitle?.string ?? "" }
            check("agents menu: the 5 live agents are listed (the exited one is not)", names.count == 5 && !names.joined().contains("gone"), names.joined(separator: " | "))
            check("agents menu: needs-you first, then running, then idle in deck order",
                  names.count == 5 && names[0].contains("Fix the build") && names[1].contains("Gemini run") && names[2].contains("Idle claude") && names[3].contains("demo   antigrav personal") && names[4].contains("plain shell"), names.joined(separator: " | "))
            check("agents menu: the title says the tool, the login and that it needs you", names.first?.contains("claude · work · needs you") == true, names.first ?? "")
            let adopted = agent("gggg7", "shell", "idle", "agy-work · Fix the parser"), adoptedFree = agent("gggg8", "shell", "idle", "agy-free · Fix free"), local = agent("hhhh8", "shell", "idle", "local model · notes")
            check("agents menu: an agy put on the deck by hand (\"agy-work · …\") is antigrav work, titled without its prefix",
                  adopted.isAntigrav && adopted.agyProfile == "work" && adopted.handoverKey == "agy-work" && adopted.cleanTitle == "Fix the parser" && adopted.movable,
                  "\(adopted.kind) \(adopted.agyProfile) \(adopted.cleanTitle)")
            check("agents menu: an agy-free tile is antigrav free, titled without its prefix",
                  adoptedFree.isAntigrav && adoptedFree.agyProfile == "free" && adoptedFree.handoverKey == "agy-free" && adoptedFree.cleanTitle == "Fix free" && adoptedFree.movable,
                  "\(adoptedFree.kind) \(adoptedFree.agyProfile) \(adoptedFree.cleanTitle)")
            check("agents menu: a local model tile is a local tile; a title that is only the prefix, or a plain shell's, stays as it is",
                  local.kind == "local" && local.cleanTitle == "notes" && agent("iiii9", "shell", "idle", "kiro · ").cleanTitle == "kiro · " && agent("jjjj0", "shell", "idle", "zsh · x").cleanTitle == "zsh · x",
                  "\(local.kind) \(local.cleanTitle)")
            let standIn = agent("kkkk1", "shell", "idle", "codex · Github Master"), standInGem = agent("llll2", "shell", "idle", "gemini · notes")
            check("agents menu: a codex / gemini put on the deck by hand (stand-in shell tile \"codex · …\") is tagged as that tool, without the prefix",
                  standIn.kind == "codex" && standIn.cleanTitle == "Github Master" && standInGem.kind == "gemini" && standInGem.cleanTitle == "notes" && !standIn.movable,
                  "\(standIn.kind) \(standIn.cleanTitle) \(standInGem.kind) \(standInGem.cleanTitle)")
            if names.count == 5, let claude = agentItems[0].submenu, let gem = agentItems[1].submenu, let agy = agentItems[3].submenu, let shell = agentItems[4].submenu {
                check("claude agent: usage lines show percentages before their windows, context and cost", lines(claude).contains("work · 90% 5h · 60% 7d") && lines(claude).contains("context 40% · $1.50"), lines(claude).joined(separator: " | "))
                check("claude agent: continue on offers only the OTHER login, with what it has used", titles(sub(claude, "Continue on")) == ["personal · 20% used"], titles(sub(claude, "Continue on")).joined(separator: ","))
                let hand = sub(claude, "Hand over to")
                check("claude agent: hand over lists the other tools, never claude (nor gemini, antigrav's program)", titles(hand) == ["antigrav work", "antigrav personal", "codex", "cursor", "kiro", "opencode (not installed)", "local model (not installed)"], titles(hand).joined(separator: ","))
                check("an uninstalled tool is greyed out", hand?.items.first { $0.title.hasPrefix("local model") }?.isEnabled == false)
                check("gemini agent: no 'continue on', hand over offers claude per login (not gemini)", sub(gem, "Continue on") == nil && titles(sub(gem, "Hand over to")) == ["Claude · work · 90% used", "Claude · personal · 20% used", "antigrav work", "antigrav personal", "codex", "cursor", "kiro", "opencode (not installed)", "local model (not installed)"], titles(sub(gem, "Hand over to")).joined(separator: ","))
                check("gemini agent: the same program as antigrav, so antigrav's figures", lines(gem).contains("gemini = antigrav work · 30% 5h · 30% 7d"), lines(gem).joined(separator: " | "))
                check("antigrav tile (a plain one = the personal launcher): its usage is that account's; its own login is not a target, the other one is", lines(agy).contains("antigrav personal · 20% 5h · 40% 7d") && !titles(sub(agy, "Hand over to")).contains("antigrav personal") && titles(sub(agy, "Hand over to")).contains("antigrav work"), lines(agy).joined(separator: " | ") + " / " + titles(sub(agy, "Hand over to")).joined(separator: ","))
                check("a plain shell can only be focused (no conversation to move)", sub(shell, "Continue on") == nil && sub(shell, "Hand over to") == nil && titles(shell) == ["Focus terminal"], titles(shell).joined(separator: ","))
            } else { check("agents menu: submenus exist", false, "\(agentItems.count) items") }
            do {   // what the live hub sends: NO gemini row (folded into antigrav's), and the accounts are named by login
                let kept = tools
                tools = tools.filter { $0.id != "gemini" }
                render(); rebuildAgentMenu(force: true)
                func menuOf(_ part: String) -> NSMenu? { agentItems.first { ($0.attributedTitle?.string ?? "").contains(part) }?.submenu }
                if let gem = menuOf("Gemini run"), let agy = menuOf("demo   antigrav personal") {
                    check("gemini agent, its row folded away: still antigrav's figures, named by profile", lines(gem).contains("gemini = antigrav work · 30% 5h · 30% 7d"), lines(gem).joined(separator: " | "))
                    check("antigrav tile with two logins: its own login is named", lines(agy).contains("antigrav personal · 20% 5h · 40% 7d"), lines(agy).joined(separator: " | "))
                } else { check("gemini and antigrav agents are listed (row folded away)", false, agentItems.map { $0.title }.joined(separator: " | ")) }
                tools = tools.filter { $0.id != "agy" }   // no antigrav on this Mac: a gemini agent has nobody's figures to borrow
                render(); rebuildAgentMenu(force: true)
                check("gemini agent with no percentage source adds no placeholder", menuOf("Gemini run").map { !lines($0).contains { $0.hasPrefix("gemini ·") } } == true, menuOf("Gemini run").map { lines($0).joined(separator: " | ") } ?? "-")
                tools = kept
                render(); rebuildAgentMenu(force: true)
            }
            let rows = toolRows.map { $0.line }
            let visibleRows = rows.filter { !$0.isEmpty }
            check("tools: codex line shows its percentage before account metadata", rows[0].hasPrefix("codex · 3% 30d · ChatGPT free"), rows[0])
            check("tools: Cursor /usage shows each measured percentage first", rows[1] == "cursor · 96% Included · 100% Auto · 0% API · logged in", rows[1])
            check("tools: kiro /usage shows the percentage first", rows[2] == "kiro · 0% month · 0/50 credits · free", rows[2])
            check("tools: antigrav lists profile usage without the weekly model split", rows[3] == "antigrav = gemini · work 0% · personal 100%", rows[3])
            let renderedToolItems = toolMenuItems.isEmpty ? toolItems : toolMenuItems
            check("tools: unavailable and token-only usage rows are omitted", visibleRows.count == 4 && renderedToolItems.prefix(4).allSatisfy { !$0.isHidden } && renderedToolItems.dropFirst(4).allSatisfy { $0.isHidden } && !toolsHeadItem.isHidden, "\(visibleRows.joined(separator: " | ")) [menu items: \(renderedToolItems.map { $0.isHidden ? "hidden" : "visible" }.joined(separator: ",")); head hidden: \(toolsHeadItem.isHidden)]")

            // run-out predictions on limit windows
            do {
                var w = Win(["label": "5h", "percent": 42, "state": "live"])
                w.resetsAt = Date().addingTimeInterval(3 * 3600 + 17 * 60)
                check("prediction: 42% 5h with 3h 17m left predicts run out", w.runOutIn() == "2h 22m" && w.runsOutBeforeReset(), "\(String(describing: w.runOutIn()))")
                check("limit detail shows predicted run-out inside the menu", w.detail.contains("out in 2h 22m"), w.detail)
                let keep = overallShort
                overallShort = w
                let bar = title(now: Date()).string
                check("menubar title is minimalist and keeps predictive inside the menu", bar.contains("42% 5h") && !bar.contains("out in"), bar)
                overallShort = keep
                var safe = Win(["label": "5h", "percent": 5, "state": "live"])
                safe.resetsAt = Date().addingTimeInterval(4 * 3600)
                check("prediction: 5% 5h with 4h left will not run out before reset", safe.runOutIn() == nil && !safe.runsOutBeforeReset(), "\(String(describing: safe.runOutIn()))")
                var full = Win(["label": "5h", "percent": 100, "state": "live"])
                full.resetsAt = Date().addingTimeInterval(2 * 3600)
                check("prediction: 100% 5h is already out", full.runOutIn() == "now" && full.runsOutBeforeReset(), "\(String(describing: full.runOutIn()))")
            }
            // the item for 'continue on personal' must ask the DECK (nothing moves from the menu): the call it makes on the page
            if let it = agentItems.first.flatMap({ sub($0.submenu!, "Continue on")?.items.first }) {
                menuHandover(it)
                check("continue on → asks the deck's dialog for that agent and login (nothing is sent to the hub)", lastDeckCall == "window.handoffAgent && window.handoffAgent(...[\"personal\",\"aaaa1\"])", lastDeckCall)
            }
            // a bad id or target is refused, not passed to the page
            lastDeckCall = ""
            let bad = NSMenuItem(); bad.representedObject = Act("a'b", "work"); menuHandover(bad)
            let bad2 = NSMenuItem(); bad2.representedObject = Act("aaaa1", "x\");alert(1);(\""); menuHandover(bad2)
            check("an id or target with odd characters never reaches the page", lastDeckCall == "", lastDeckCall)

            // kiro / opencode tiles: shell agents told apart by title, with their own line, movable, and not their own target
            agents = [agent("kkkk1", "shell", "idle", "kiro · demo"), agent("oooo1", "shell", "waiting", "opencode · demo")]
            render(); rebuildAgentMenu(force: true)
            if agentItems.count == 2, let oc = agentItems[0].submenu, let ki = agentItems[1].submenu {
                check("kiro tile: its percentage and credits are first, and kiro is not a target", lines(ki).contains("kiro · 0% month · 0/50 credits · free") && !titles(sub(ki, "Hand over to")).contains("kiro") && titles(sub(ki, "Hand over to")).contains("opencode (not installed)"), lines(ki).joined(separator: " | ") + " / " + titles(sub(ki, "Hand over to")).joined(separator: ","))
                check("opencode tile: token-only usage is omitted; hand over offers supported targets", !lines(oc).contains { $0.hasPrefix("opencode ·") } && titles(sub(oc, "Hand over to")).prefix(2) == ["Claude · work · 90% used", "Claude · personal · 20% used"] && titles(sub(oc, "Hand over to")).contains("kiro") && !titles(sub(oc, "Hand over to")).contains { $0.hasPrefix("opencode") }, titles(sub(oc, "Hand over to")).joined(separator: ","))
            } else { check("kiro / opencode tiles are listed", false, "\(agentItems.count) items") }

            // many agents: nothing is dropped. The busy ones stay on top, the idle ones (an idle antigrav tile among them) go one level
            // down, and the sessions started by hand in a terminal are listed with their own focus item and no continue / hand over.
            agents = (0..<14).map { i in agent("idle\(i)", "claude", "idle", "Idle \(i)", account: "work") }
                + [agent("agyt1", "shell", "idle", "antigrav · tile"), agent("runr1", "codex", "running", "Busy codex"), agent("wait1", "claude", "waiting", "Asks you", account: "personal")]
            hand = [HandSession(["pid": 4242, "tool": "antigrav", "folder": "Github Master", "cwd": NSHomeDirectory() + "/Documents/Github Master"])]
            render(); rebuildAgentMenu(force: true)
            let many = agentItems.map { $0.attributedTitle?.string ?? $0.title }
            let more = agentItems.first { $0.title.hasPrefix("Idle agents") }?.submenu
            let moved = (more?.items ?? []).map { $0.attributedTitle?.string ?? $0.title }
            check("many agents: needs-you and running on top, then one 'Idle agents · 15' submenu, then the hand-started one",
                  many.count == 4 && many[0].contains("Asks you") && many[1].contains("Busy codex") && agentItems[2].title == "Idle agents · 15" && many[3].contains("Github Master"), many.joined(separator: " | "))
            check("many agents: every idle agent is in the submenu, the antigrav tile included", moved.count == 15 && moved.contains { $0.contains("tile   antigrav personal") }, "\(moved.count): " + moved.joined(separator: " | "))
            if let h = agentItems.last?.submenu {
                check("hand-started agy (a bare agy is the personal login): shows percentages first and can only be focused", lines(h).first == "started by hand in a terminal · not on the deck" && lines(h).contains("antigrav personal · 20% 5h · 40% 7d") && titles(h) == ["Focus terminal"] && (h.items.last?.representedObject as? Act)?.id == "4242", lines(h).joined(separator: " | ") + " / " + titles(h).joined(separator: ","))
            } else { check("hand-started session is listed", false, many.joined(separator: " | ")) }
            check("quitting the app keeps the menu bar item; only its own Quit ends it",
                  applicationShouldTerminate(NSApp) == .terminateCancel && { quitForReal = true; defer { quitForReal = false }; return applicationShouldTerminate(NSApp) == .terminateNow }()
                  && menu.items.last?.title == "Quit Agent Monitor and this menu bar item" && menu.items.last?.action == #selector(quitAll))
            check("menubar has auto-continue item", autoContinueItem != nil && autoContinueItem.action == #selector(toggleAutoContinue))
            if let ci = capriItem {
                let prevCapri = capriEnabled
                check("menubar has Capri companion toggle", ci.action == #selector(toggleCapri))
                toggleCapri()
                check("Capri toggle flips state and checkmark", capriEnabled == !prevCapri && ci.state == (capriEnabled ? .on : .off))
                setCapriEnabled(prevCapri, pushWindow: false, pushPopover: false)
            } else {
                check("menubar has Capri companion toggle", false)
            }
            check("the agents line counts the hand-started ones", agentsRow.line.hasSuffix(" · 1 by hand"), agentsRow.line)
            // folder broadcast: top-level cluster submenu + per-agent & hand submenu shortcut when sharing a folder
            do {
                let clusterDir = NSHomeDirectory() + "/Documents/Github Master"
                broadcastClusters = [BroadcastCluster([
                    "cwd": clusterDir, "cwds": [clusterDir], "folder": "Github Master",
                    "agentCount": 3, "reachableCount": 2,
                    "companies": ["Anthropic", "OpenAI"], "tools": ["claude", "codex"], "isMultiCompany": true
                ])]
                var clustered = agent("runr1", "codex", "running", "Busy codex")
                clustered.cwd = clusterDir
                agents = [clustered]
                render(); rebuildAgentMenu(force: true)
                let bcFirst = broadcastItem.submenu?.items.first
                check("broadcast item lists multi-agent folder cluster",
                      broadcastItem.title == "Broadcast to cluster (1)…" && (bcFirst?.title.contains("Github Master · 3 agents · Anthropic + OpenAI") == true),
                      "\(broadcastItem.title) / \(bcFirst?.title ?? "-")")
                if let mi = bcFirst { menuBroadcast(mi) }
                let wantArgsData = try? JSONSerialization.data(withJSONObject: [clusterDir])
                let wantArgs = wantArgsData.flatMap { String(data: $0, encoding: .utf8) } ?? ""
                check("broadcast cluster item opens deck broadcast modal for that folder",
                      lastDeckCall == "window.broadcastFolder && window.broadcastFolder(...\(wantArgs))",
                      lastDeckCall)
                lastDeckCall = ""
                let badRel = NSMenuItem(); badRel.representedObject = "relative/path"; menuBroadcast(badRel)
                let badCtrl = NSMenuItem(); badCtrl.representedObject = "/tmp/bad\nline"; menuBroadcast(badCtrl)
                check("broadcast rejects relative or control-char paths", lastDeckCall == "", lastDeckCall)
                check("agent and hand submenus offer Broadcast to folder when folder has a cluster",
                      agentItems.first?.submenu.map { titles($0).contains("Broadcast to folder (3)…") } == true
                      && agentItems.last?.submenu.map { titles($0).contains("Broadcast to folder (3)…") } == true,
                      titles(agentItems.first?.submenu).joined(separator: ",") + " / " + titles(agentItems.last?.submenu).joined(separator: ","))
            }
            // Docker Mode: profile readout, submenu state, and busy progress formatting (no live restart during selftest)
            do {
                let keepOnline = online
                online = true
                renderMetrics([
                    "memory": ["usedGB": 24, "totalGB": 48, "usedPercent": 50],
                    "docker": ["count": 0, "totalUsedMB": 0, "totalLimitMB": 0],
                    "dockerMode": [
                        "profile": "models", "allocatedGB": 5.0, "hostMemoryGB": 48.0, "hostAvailableGB": 43.0,
                        "daemonRunning": false, "settingsAvailable": true,
                        "appflowy": ["configured": true, "runningCount": 0, "totalCount": 0],
                        "operation": ["busy": false]
                    ]
                ])
                check("docker mode (models stopped): line and submenu state",
                      dockerLine == "Docker · models 5.0G · stopped (~43.0G free)"
                      && dockerModeItem.title == "Docker mode · models (5.0 GB)"
                      && dockerModeItem.submenu?.item(at: 2)?.state == .on
                      && dockerModeItem.submenu?.item(at: 3)?.state == .off
                      && dockerModeItem.submenu?.item(at: 5)?.isEnabled == false,
                      "\(dockerLine) | \(dockerModeItem.title)")

                renderMetrics([
                    "memory": ["usedGB": 30, "totalGB": 48, "usedPercent": 62],
                    "docker": ["count": 11, "totalUsedMB": 4096, "totalLimitMB": 14336],
                    "dockerMode": [
                        "profile": "work", "allocatedGB": 14.0, "hostMemoryGB": 48.0, "hostAvailableGB": 34.0,
                        "daemonRunning": true, "settingsAvailable": true,
                        "appflowy": ["configured": true, "runningCount": 11, "totalCount": 11],
                        "operation": ["busy": false]
                    ]
                ])
                check("docker mode (work running): line, checkmark, and clean enabled",
                      dockerLine == "Docker · work 14.0G · 11 ctr (4.0G)"
                      && dockerModeItem.title == "Docker mode · work (14.0 GB)"
                      && dockerModeItem.submenu?.item(at: 2)?.state == .off
                      && dockerModeItem.submenu?.item(at: 3)?.state == .on
                      && dockerModeItem.submenu?.item(at: 5)?.isEnabled == true,
                      "\(dockerLine) | \(dockerModeItem.title)")

                renderMetrics([
                    "memory": ["usedGB": 30, "totalGB": 48, "usedPercent": 62],
                    "docker": ["count": 0, "totalUsedMB": 0, "totalLimitMB": 0],
                    "dockerMode": [
                        "profile": "models", "allocatedGB": 4.5, "hostMemoryGB": 48.0, "hostAvailableGB": 43.5,
                        "daemonRunning": false, "settingsAvailable": true,
                        "appflowy": ["configured": true, "runningCount": 0, "totalCount": 0],
                        "operation": ["busy": true, "action": "work", "step": "starting Docker Desktop…"]
                    ]
                ])
                check("docker mode (busy): shows step and disables switches",
                      dockerLine == "Docker · starting Docker Desktop…"
                      && dockerModeItem.submenu?.item(at: 2)?.isEnabled == false
                      && dockerModeItem.submenu?.item(at: 3)?.isEnabled == false,
                      dockerLine)
                dockerModePollTimer?.invalidate(); dockerModePollTimer = nil
                dockerModeBusy = false; dockerModeWasBusy = false
                online = keepOnline
            }

            // live: the real hub's agents, then the real page's hook
            (agents, tools, handTargets, claudeLogins, accounts, online) = keep
            hand = keepHand
            broadcastClusters = keepClusters
            showAgyTool = false; renderTools()
            check("tools: antigrav is not repeated as a tool (it has its account row), nor is gemini", !toolItems.enumerated().contains { !$0.element.isHidden && (toolRows[$0.offset].line.hasPrefix("antigrav") || toolRows[$0.offset].line.hasPrefix("gemini")) }, toolRows.map { $0.line }.joined(separator: " | "))
            pendingPage = nil
            refresh(); refreshExtras(force: true)
            DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                let live = self.liveAgents()
                self.rebuildAgentMenu(force: true)
                let (top, rest) = self.agentLayout()
                let reach = top.count + ((self.agentItems.first { $0.title.hasPrefix("Idle agents") || $0.title.hasPrefix("More agents") }?.submenu?.items.count) ?? 0)
                check("live: every live agent on the hub (\(live.count)) is in the menu or its submenu, plus \(self.hand.count) started by hand",
                      reach == live.count && rest.count + top.count == live.count && self.agentItems.count == top.count + (rest.isEmpty ? 0 : 1) + self.hand.count,
                      "\(self.agentItems.count) items, \(reach) reachable, for \(live.count) agents + \(self.hand.count) by hand")
                check("live: the tools section has the hub's installed tools", self.tools.isEmpty || !self.toolsHeadItem.isHidden, "\(self.tools.count) tools")
                guard let a = live.first(where: { $0.tool == "claude" && $0.account != "personal" }), let web = self.web else {
                    tlog("SKIP  live page hook (no Claude agent outside 'personal', or no page)"); finish(); return
                }
                self.menuHandover({ let m = NSMenuItem(); m.representedObject = Act(a.id, "personal"); return m }())
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                    web.evaluateJavaScript("[typeof window.handoffAgent, document.getElementById('handoff').hidden, document.getElementById('handoff-title').textContent].join(' | ')") { r, e in
                        let v = (r as? String) ?? "error \(String(describing: e))"
                        check("live page: the menu's call opens the hand-over dialog for that agent (and moves nothing)", v.hasPrefix("function | false | continue on personal"), v)
                        web.evaluateJavaScript("document.getElementById('handoff-close').click(); 'closed'") { _, _ in finish() }
                    }
                }
            }
        }

        // 1. default: everything ticked, everything shown
        // (an account can have no 5h reading: antigrav's has only a weekly bucket when that login's 5h window is disabled or not started)
        let n = accounts.count   // (two Claude logins and two Antigravity ones; fewer on a Mac without the launchers)
        check("starts with all \(n) ticked", focus == nil && states() == String(repeating: "✓", count: n) && overallShort.total == n && overallShort.of == accounts.filter { $0.short.percent != nil }.count && header.title == "OVERALL LIMITS", "focus=\(String(describing: focus)) \(states()) of \(String(describing: overallShort.of))/\(String(describing: overallShort.total))")
        check("the bar shows usage", barText().contains("%"), barText())
        showPopover()   // the page only exists while the popover is shown

        // 2. untick personal -> every other login stays
        pick(1)
        let rest = accounts.enumerated().filter { $0.offset != 1 }.map { $0.element }
        let restNames = rest.map { $0.label }.joined(separator: " + ")
        check("untick personal -> the other \(rest.count) stay", focus == Set(rest.map { $0.id }) && states() == accounts.indices.map { $0 == 1 ? "·" : "✓" }.joined(), "\(String(describing: focus)) \(states())")
        let w = rest.compactMap { $0.short.percent }
        let wMax: Int? = w.max()
        check("5h = highest used (lowest headroom) of the ticked logins (\(w.count) of \(rest.count))", overallShort.percent == wMax && overallShort.of == w.count && overallShort.total == rest.count, "\(String(describing: overallShort.percent)) vs \(w)")
        check("header reads FOCUS · " + restNames.uppercased(), header.title == "FOCUS · " + restNames.uppercased(), header.title)
        check("bar tooltip says what is shown", item.button?.toolTip?.contains("showing: " + restNames) == true, item.button?.toolTip ?? "nil")
        check("one dot per ticked account in the bar", barText().filter { $0 == "●" }.count == rest.count, barText())

        // 3. untick the rest -> NOTHING is shown (the reported bug: unticked accounts still showed usage)
        for i in accounts.indices where i != 1 { pick(i) }
        check("everything unticked -> an explicit empty selection", focus == Set<String>() && states() == String(repeating: "·", count: n), "\(String(describing: focus)) \(states())")
        check("the bar shows NO usage at all", !barText().contains("%") && !barText().contains("5h") && !barText().contains("7d"), barText())
        check("overall figures are empty (none), not 'all'", overallShort.state == "none" && overallShort.percent == nil && overallWeek.state == "none" && overallShort.total == 0, "\(overallShort.state) \(String(describing: overallShort.percent))")
        check("header reads NO ACCOUNTS TICKED", header.title == "NO ACCOUNTS TICKED", header.title)
        check("bar tooltip says usage is hidden", item.button?.toolTip?.contains("usage hidden") == true, item.button?.toolTip ?? "nil")

        // 4. native -> page
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) {
            guard let web = self.web else { check("page exists while popover shown", false, "web view is nil (popover closed?)"); finish(); return }
            let idsJS = "[" + self.accounts.map { $0.id }.filter { $0.range(of: "^[\\w-]{1,32}$", options: .regularExpression) != nil }.map { "'\($0)'" }.joined(separator: ",") + "]"
            web.evaluateJavaScript("[document.querySelector('.limit-tag').textContent, \(idsJS).map(i => { const p = document.querySelector('.limit-acct-pill[data-acct=\"' + i + '\"]'); return p && p.classList.contains('lim-on') ? 'on' : 'off'; }).join(','), document.getElementById('lim-1h-pct').textContent].join(' | ')") { r, e in
                let v = (r as? String) ?? "error \(String(describing: e))"
                check("page dock: NO ACCOUNTS TICKED, all pills off, no number", v == "NO ACCOUNTS TICKED | " + Array(repeating: "off", count: n).joined(separator: ",") + " | —", v)
                // 5. page -> native: tick work, then the others, from the live page
                web.evaluateJavaScript("document.getElementById('pill-work').click(); 'clicked'") { _, _ in
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
                        check("ticking work in the page ticks it natively", self.focus == Set(["work"]) && states() == "✓" + String(repeating: "·", count: n - 1), "\(String(describing: self.focus)) \(states())")
                        check("bar shows work's usage again", barText().contains("%"), barText())
                        // (an antigrav login that returned the other one's figures has none of its own: its pill cannot be ticked, so it stays out)
                        let clicks = self.accounts.filter { $0.id != "work" && $0.sameAs.isEmpty }.map { "document.querySelector('.limit-acct-pill[data-acct=\"\($0.id)\"]').click()" }.joined(separator: "; ")
                        let idle = self.accounts.filter { !$0.sameAs.isEmpty }
                        web.evaluateJavaScript(clicks + "; 'clicked'") { _, _ in
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
                                let want: Set<String>? = idle.isEmpty ? nil : Set(self.accounts.filter { $0.sameAs.isEmpty }.map { $0.id })
                                check("every tickable login ticked again -> " + (idle.isEmpty ? "back to the default" : "all but the \(idle.count) with no figures of its own"), self.focus == want && (want != nil || (states() == String(repeating: "✓", count: n) && self.header.title == "OVERALL LIMITS")), "\(String(describing: self.focus)) \(states())")
                                // 6. normalisation
                                self.setFocus(Set(self.accounts.map { $0.id }), persist: false)
                                check("ticking everything is just the default", self.focus == nil)
                                self.setFocus([], persist: false)
                                check("an empty selection means nothing shown (not all)", self.focus == Set<String>() && !barText().contains("%"), "\(String(describing: self.focus))")
                                self.setFocus(Set(self.accounts.map { $0.id }), persist: false)
                                agentChecks()
                            }
                        }
                    }
                }
            }
        }
    }

    // MARK: focus

    @objc func toggleAccount(_ sender: NSMenuItem) {
        dlog("toggleAccount tag=\(sender.tag)")
        guard sender.tag >= 0, sender.tag < accounts.count else { return }
        toggle(accounts[sender.tag].id)
    }

    /// Tick / untick an account. Untick them all and no usage is shown.
    func toggle(_ id: String) {
        var set = focus ?? Set(accounts.map { $0.id })
        if set.contains(id) { set.remove(id) } else { set.insert(id) }
        setFocus(set)
    }
    func setFocus(_ ids: Set<String>, persist: Bool = true) {
        dlog("setFocus \(ids.sorted()) persist=\(persist)")
        let all = accounts.isEmpty ? Set(["work", "personal", "agy-work", "agy-personal", "agy-free"]) : Set(accounts.map { $0.id })
        let valid = ids.intersection(all)
        focus = valid == all ? nil : valid   // everything ticked is just the default
        if persist && persistFocus {
            if let f = focus {
                UserDefaults.standard.set(Array(f).sorted(), forKey: "focusAccounts"); UserDefaults.standard.set(true, forKey: "focusExplicit")
            } else {
                UserDefaults.standard.removeObject(forKey: "focusAccounts"); UserDefaults.standard.removeObject(forKey: "focusExplicit")
            }
        }
        pushFocus(); recompute(); render()
    }
    /// Tick / untick backup tools for the bar. Empty = the Claude / antigrav overall stays on the bar.
    func setToolFocus(_ ids: Set<String>, persist: Bool = true) {
        dlog("setToolFocus \(ids.sorted()) persist=\(persist)")
        toolFocus = Set(ids.filter { !$0.isEmpty })
        if persist && persistFocus {
            if toolFocus.isEmpty { UserDefaults.standard.removeObject(forKey: "focusTools") }
            else { UserDefaults.standard.set(Array(toolFocus).sorted(), forKey: "focusTools") }
        }
        pushToolFocus()
        if !toolFocus.isEmpty { refreshExtras() }   // need their readings for the bar
        render()
        schedulePolling()   // keep /api/models fresh while a tool is pinned to the bar
    }
    /// Ticked (✓) = its usage is shown and counted in the figures. By default all three are.
    func isOn(_ id: String) -> Bool { focus == nil || focus!.contains(id) }
    func isChecked(_ id: String) -> Bool { isOn(id) }

    /// The overall window over just the focused accounts (the hub's overall when none are picked).
    func overall(_ pick: (Acct) -> Win, hub: Win) -> Win {
        guard let f = focus else { return hub }
        return overallRule(accounts.filter { f.contains($0.id) }, pick: pick, label: hub.label)
    }
    func recompute() {
        overallShort = overall({ $0.short }, hub: hubShort)
        overallWeek = overall({ $0.week }, hub: hubWeek)
    }
    func redrawRows() {
        for v in ([header, shortRow, weekRow, splitRow, agentsRow, metricsRow, totalUsageRow, hintRow, toolsHead, actionRow] as [NSView]) + toolRows { v.needsDisplay = true }
    }

    @objc func openDash() { NSWorkspace.shared.open(dashboardURL) }
    @objc func openPiStatus() {
        if piConnected {
            NSWorkspace.shared.open(piVitalsURL)
        } else if FileManager.default.fileExists(atPath: piSetupGuideURL.path) {
            NSWorkspace.shared.open(piSetupGuideURL)
        } else {
            NSWorkspace.shared.open(dashboardURL)
        }
    }

    /// The deck in a window of its own, with a Dock icon while it is open.
    @objc func openWindow() {
        if popover.isShown { closePopover() }
        NSApp.setActivationPolicy(.regular)
        deckWindow.show()
    }
    @objc func reloadWindow() { deckWindow.reload() }

    // MARK: quitting
    // Quitting the APP (⌘Q, the app menu, the Dock's Quit, `quit app "Agent Monitor"`) closes its window and leaves the menu bar
    // item running. Only the menu bar's own "Quit Agent Monitor and this menu bar item", or logging out / restarting / shutting down,
    // ends the process.
    var quitForReal = false
    @objc func quitAll() { quitForReal = true; NSApp.terminate(nil) }
    func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
        // A logout / restart / shutdown asks with a quit reason; nothing may hold that up.
        let systemQuit = NSAppleEventManager.shared().currentAppleEvent?.attributeDescriptor(forKeyword: kAEQuitReason) != nil
        if quitForReal || systemQuit || poweringOff { return .terminateNow }
        dlog("quit asked: closing the window, the menu bar item stays")
        if popover.isShown { closePopover() }
        if deckWindow.isOpen { deckWindow.close() } else { NSApp.setActivationPolicy(.accessory) }
        return .terminateCancel
    }
    var poweringOff = false
    @objc func willPowerOff(_ n: Notification) { poweringOff = true }
    /// Opening the app again (Dock, Finder, Spotlight, `open`) while it runs: show the window.
    func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
        if !deckWindow.isOpen || !flag { openWindow() }
        return true
    }
    /// Ask the hub to re-run `claude /usage` for each account now (takes a few seconds), then re-read.
    @objc func refreshNow() {
        dlog("refreshNow")
        refreshing = true; render()
        var req = URLRequest(url: refreshURL)
        req.httpMethod = "POST"; req.timeoutInterval = 60
        URLSession.shared.dataTask(with: req) { [weak self] _, _, _ in
            DispatchQueue.main.async { self?.refreshing = false; self?.refresh() }
        }.resume()
    }

    // MARK: data

    // Lightweight HTTP response cache: skip a request and JSON deserialization if we got fresh data within the TTL.
    var cache: [URL: (json: [String: Any], at: Date)] = [:]
    let cacheTTL: TimeInterval = 5    // /api/limits and /v1/state: stable, 5s is enough
    let extrasCacheTTL: TimeInterval = 30 // /api/models: login checks cost more, 30s

    func cachedFetchJSON(_ url: URL, _ ttl: TimeInterval) -> [String: Any]? {
        if let (json, at) = cache[url], Date().timeIntervalSince(at) < ttl { return json }
        return nil
    }

    func parseJSON(_ data: Data?) -> [String: Any]? {
        guard let data else { return nil }
        return try? JSONSerialization.jsonObject(with: data) as? [String: Any]
    }

    func refresh() {
        let group = DispatchGroup()
        var limitsJSON: [String: Any]?, stateJSON: [String: Any]?, statusJSON: [String: Any]?
        func fetch(_ url: URL, _ done: @escaping ([String: Any]?) -> Void) {
            // Inline cache: skip the request and JSON parsing if we have fresh data.
            if let json = cachedFetchJSON(url, cacheTTL) {
                done(json); return
            }
            var req = URLRequest(url: url)
            req.cachePolicy = .reloadIgnoringLocalCacheData
            req.timeoutInterval = 3
            group.enter()
            URLSession.shared.dataTask(with: req) { data, _, _ in
                let json = self.parseJSON(data)
                DispatchQueue.main.async {
                    if let json = json { self.cache[url] = (json, Date()) }
                    done(json)
                    group.leave()
                }
            }.resume()
        }
        fetch(limitsURL) { limitsJSON = $0 }
        fetch(stateURL) { stateJSON = $0 }
        fetch(statusURL) { statusJSON = $0 }
        group.notify(queue: .main) { [weak self] in self?.apply(limitsJSON, stateJSON, statusJSON) }
    }

    func apply(_ limits: [String: Any]?, _ state: [String: Any]?, _ status: [String: Any]?) {
        online = limits != nil || state != nil
        let pi = status?["pi"] as? [String: Any]
        let server = status?["server"] as? [String: Any]
        piConnected = (server?["piConnected"] as? Bool == true) || (pi?["connected"] as? Bool == true)
        piSimulated = server?["simulatedPi"] as? Bool == true
        piTemperatureC = (pi?["temperatureC"] as? NSNumber)?.doubleValue
        piCPUPercent = (pi?["cpuUsagePercent"] as? NSNumber)?.doubleValue
        piFanRPM = ((pi?["cooling"] as? [String: Any])?["rpm"] as? NSNumber)?.intValue
        piLastSeen = pi?["lastSeen"] as? String ?? "Never"
        if let j = limits {
            let overall = j["overall"] as? [String: Any]
            hubShort = Win(overall?["short"] as? [String: Any])
            hubWeek = Win(overall?["week"] as? [String: Any])
            asOf = overall?["asOf"] as? String
            let raw = j["accounts"] as? [[String: Any]] ?? []
            accounts = raw.map { a in
                var x = Acct()
                x.id = a["id"] as? String ?? ""
                x.unit = a["unit"] as? String ?? "used"
                x.label = a["label"] as? String ?? ""
                x.sameAs = a["sameAs"] as? String ?? ""
                x.note = a["note"] as? String ?? ""
                x.short = Win(a["short"] as? [String: Any]); x.week = Win(a["week"] as? [String: Any])
                x.color = hexColor(a["color"] as? String) ?? .secondaryLabelColor
                x.expired = (a["health"] as? [String: Any])?["state"] as? String == "expired"
                return x
            }
            // The weekly split comes from whichever account has one (the most recently read).
            let best = raw.filter { !(($0["breakdown"] as? [[String: Any]] ?? []).isEmpty) }
                .max { ($0["asOf"] as? String ?? "") < ($1["asOf"] as? String ?? "") }
            recompute()
            splitOwner = best?["label"] as? String ?? ""
            shares = (best?["breakdown"] as? [[String: Any]] ?? []).compactMap {
                guard let n = $0["name"] as? String, let p = $0["percent"] as? Int, p > 0 else { return nil }
                return Share(name: n, percent: p)
            }
        }
        if let s = state {
            var c = Counts()
            let list = (s["agents"] as? [[String: Any]] ?? []).map { AgentInfo($0) }
            for a in list {
                switch a.status {
                case "running": c.running += 1
                case "waiting": c.waiting += 1
                case "error": c.error += 1
                default: c.idle += 1
                }
            }
            counts = c
            agents = list
        }
        if let costs = status?["costs"] as? [String: Any], let totals = costs["totals"] as? [String: Any] {
            func getPeriod(_ key: String) -> (tok: String, cost: String) {
                guard let p = totals[key] as? [String: Any] else { return ("0", "$0.00") }
                let tok = p["tokensFormatted"] as? String ?? "0"
                let usd = (p["costUsd"] as? NSNumber)?.doubleValue ?? 0.0
                return (tok, usd > 0 ? String(format: "$%.2f", usd) : "$0.00")
            }
            // every agent and company at API list prices (the hub's cost card); two short lines, money first (15 Nov: "cleaner")
            let month = getPeriod("monthly")
            let week = getPeriod("weekly")
            let day = getPeriod("daily")
            totalUsageRow.line1 = "today \(day.cost) · \(day.tok) tokens"
            totalUsageRow.line2 = "7 days \(week.cost) · 30 days \(month.cost)"
        }
        render()
    }

    // MARK: agents in the details menu

    /// codex / cursor, what the hand-over dialog can start, the Claude logins and the local model's tokens. Read when the menu or the
    /// popover opens (not on every poll): /api/models runs the tools' login checks, which the hub caches for a few minutes.
    /// System metrics: Docker containers memory + macOS memory pressure. Cached for 15s (bypassed when forced or switching Docker mode).
    func refreshMetrics(force: Bool = false) {
        guard force || dockerModeBusy || Date().timeIntervalSince(lastMetricsRefresh) > 15 else { return }
        lastMetricsRefresh = Date()
        let url = force ? URL(string: systemMetricsURL.absoluteString + "?refresh=1")! : systemMetricsURL
        var req = URLRequest(url: url); req.timeoutInterval = 5
        URLSession.shared.dataTask(with: req) { [weak self] data, _, _ in
            guard let self = self else { return }
            let json = data.flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] }
            DispatchQueue.main.async {
                if let json = json {
                    self.renderMetrics(json)
                } else {
                    self.dockerLine = "system metrics: hub unreachable"
                    self.memLine = ""
                }
                self.redrawRows()
            }
        }.resume()
    }

    func renderMetrics(_ j: [String: Any]) {
        if let m = j["memory"] as? [String: Any], let used = m["usedGB"], let total = m["totalGB"], let pct = m["usedPercent"] {
            self.memLine = "macOS \(used)G / \(total)G RAM (\(pct)%)"
            metricsOnline = true
        } else {
            self.memLine = "macOS memory: unavailable"
            metricsOnline = false
        }
        let d = j["docker"] as? [String: Any]
        let count = d?["count"] as? Int ?? 0
        let usedMB = (d?["totalUsedMB"] as? NSNumber)?.doubleValue ?? 0
        let limitMB = (d?["totalLimitMB"] as? NSNumber)?.doubleValue ?? 0
        let usedG = String(format: "%.1f", usedMB / 1024)
        let limitG = String(format: "%.1f", limitMB / 1024)

        if let dm = j["dockerMode"] as? [String: Any] {
            dockerModeProfile = dm["profile"] as? String ?? "unknown"
            dockerModeAllocatedGB = (dm["allocatedGB"] as? NSNumber)?.doubleValue
            dockerModeHostGB = (dm["hostMemoryGB"] as? NSNumber)?.doubleValue ?? 48.0
            dockerModeHostAvailGB = (dm["hostAvailableGB"] as? NSNumber)?.doubleValue
            dockerModeDaemonUp = dm["daemonRunning"] as? Bool ?? false
            dockerModeSettingsOk = dm["settingsAvailable"] as? Bool ?? false
            dockerModeSettingsError = dm["settingsError"] as? String ?? ""
            let af = dm["appflowy"] as? [String: Any]
            dockerModeAppflowyConfigured = af?["configured"] as? Bool ?? false
            dockerModeAppflowyRun = af?["runningCount"] as? Int ?? 0
            dockerModeAppflowyTotal = af?["totalCount"] as? Int ?? 0

            let op = dm["operation"] as? [String: Any]
            let prevBusy = dockerModeWasBusy
            let busy = op?["busy"] as? Bool ?? false
            dockerModeBusy = busy
            dockerModeWasBusy = busy
            dockerModeStep = op?["step"] as? String ?? ""

            if prevBusy && !busy {
                stopDockerModePolling()
                if let last = op?["lastResult"] as? [String: Any], let msg = last["message"] as? String {
                    let ok = last["ok"] as? Bool ?? true
                    say(msg, bad: !ok)
                }
            }
            if busy { startDockerModePolling() }

            if busy {
                self.dockerLine = "Docker · \(dockerModeStep.isEmpty ? "switching…" : dockerModeStep)"
            } else if dockerModeSettingsOk || dockerModeDaemonUp {
                let allocStr = dockerModeAllocatedGB.map { String(format: "%.1fG", $0) } ?? "—"
                if dockerModeDaemonUp {
                    self.dockerLine = count > 0
                        ? "Docker · \(dockerModeProfile) \(allocStr) · \(count) ctr (\(usedG)G)"
                        : "Docker · \(dockerModeProfile) \(allocStr) · 0 containers"
                } else {
                    let availStr = dockerModeHostAvailGB.map { String(format: "%.1fG", $0) } ?? "—"
                    self.dockerLine = "Docker · \(dockerModeProfile) \(allocStr) · stopped (~\(availStr) free)"
                }
            } else {
                self.dockerLine = "Docker: not configured"
            }
            renderDockerModeMenu()
        } else if d != nil {
            self.dockerLine = "Docker \(count) containers · \(usedG)G / \(limitG)G"
        } else {
            self.dockerLine = "Docker: not available"
        }
        // Odyssеus / local models: Docker Model Runner, Ollama, etc. from the hub's mac_collector
        if let ai = j["localAi"] as? [String: Any] {
            let status = ai["status"] as? String ?? "STANDBY"
            let count = ai["count"] as? Int ?? 0
            let loadedCount = ai["loadedCount"] as? Int ?? 0
            if loadedCount > 0 {
                self.localLine = "\(loadedCount) of \(count) local models loaded (\(status.lowercased()))"
            } else if count > 0 {
                self.localLine = "\(count) local models · none loaded (\(status.lowercased()))"
            } else {
                self.localLine = "no local models found"
            }
        } else {
            self.localLine = "local models: unavailable"
        }
    }

    func renderDockerModeMenu() {
        guard let item = dockerModeItem else { return }
        if menuOpen { pendingMenuRebuild = true; return }
        let allocLabel = dockerModeAllocatedGB.map { String(format: "%.1f GB", $0) } ?? "—"
        if dockerModeBusy {
            item.title = "Docker mode · \(dockerModeStep.isEmpty ? "working…" : dockerModeStep)"
        } else if dockerModeSettingsOk {
            item.title = "Docker mode · \(dockerModeProfile) (\(allocLabel))"
        } else {
            item.title = "Docker mode · unavailable"
        }
        let sub = NSMenu(title: "Docker mode")
        sub.autoenablesItems = false
        let summaryText: String
        if dockerModeSettingsOk {
            let daemon = dockerModeDaemonUp ? "daemon running" : "daemon stopped"
            let avail = dockerModeHostAvailGB.map { String(format: "~%.1f GB free", $0) } ?? ""
            let af = dockerModeAppflowyConfigured
                ? (dockerModeAppflowyRun > 0 ? "AppFlowy \(dockerModeAppflowyRun)/\(dockerModeAppflowyTotal)" : "AppFlowy stopped")
                : ""
            summaryText = [daemon, avail, af].filter { !$0.isEmpty }.joined(separator: " · ")
        } else if dockerModeSettingsError == "permission" {
            summaryText = "Allow node in Full Disk Access (or run hub from Terminal)"
        } else {
            summaryText = "Docker settings-store.json not found"
        }
        let info = NSMenuItem(title: summaryText, action: nil, keyEquivalent: "")
        info.isEnabled = false
        sub.addItem(info)
        sub.addItem(.separator())

        let modelsItem = NSMenuItem(title: "Model mode (4.5 GB · stops AppFlowy)", action: #selector(menuDockerModels), keyEquivalent: "")
        modelsItem.target = self
        modelsItem.state = dockerModeProfile == "models" ? .on : .off
        modelsItem.isEnabled = !dockerModeBusy && dockerModeSettingsOk && online
        sub.addItem(modelsItem)

        let workItem = NSMenuItem(title: "Work mode (14 GB · starts AppFlowy)", action: #selector(menuDockerWork), keyEquivalent: "")
        workItem.target = self
        workItem.state = dockerModeProfile == "work" ? .on : .off
        workItem.isEnabled = !dockerModeBusy && dockerModeSettingsOk && online
        sub.addItem(workItem)

        sub.addItem(.separator())

        let cleanItem = NSMenuItem(title: "Clean build cache (safe prune)", action: #selector(menuDockerClean), keyEquivalent: "")
        cleanItem.target = self
        cleanItem.isEnabled = !dockerModeBusy && dockerModeDaemonUp && online
        sub.addItem(cleanItem)

        let vitalsItem = NSMenuItem(title: "Open Compute Vitals", action: #selector(openMacVitals), keyEquivalent: "")
        vitalsItem.target = self
        sub.addItem(vitalsItem)

        item.submenu = sub
    }

    func startDockerModePolling() {
        guard dockerModePollTimer == nil else { return }
        let t = Timer(timeInterval: 2.5, repeats: true) { [weak self] _ in
            self?.refreshMetrics(force: true)
        }
        RunLoop.main.add(t, forMode: .common)
        dockerModePollTimer = t
    }

    func stopDockerModePolling() {
        dockerModePollTimer?.invalidate()
        dockerModePollTimer = nil
    }

    func triggerDockerMode(_ action: String, title: String, body: String) {
        guard ask(title, body, ok: "Proceed") else { return }
        say("starting docker-mode \(action)…")
        hubPost("/api/docker-mode", ["action": action], timeout: 15) { [weak self] status, j in
            guard let self = self else { return }
            if (200..<300).contains(status), j["ok"] as? Bool == true {
                self.dockerModeBusy = true
                self.dockerModeWasBusy = true
                self.startDockerModePolling()
                self.refreshMetrics(force: true)
            } else {
                let why = j["error"] as? String ?? "HTTP \(status)"
                self.say("couldn't run docker-mode \(action) · \(why)", bad: true)
            }
        }
    }

    @objc func menuDockerModels() {
        triggerDockerMode("models",
                          title: "Switch Docker to Model mode (4.5 GB)?",
                          body: "This pauses AppFlowy, restarts Docker Desktop at 4.5 GB RAM, and frees unified memory for local AI models.")
    }

    @objc func menuDockerWork() {
        triggerDockerMode("work",
                          title: "Switch Docker to Work mode (14 GB)?",
                          body: "This restarts Docker Desktop at 14 GB RAM and brings up the AppFlowy stack.")
    }

    @objc func menuDockerClean() {
        triggerDockerMode("clean",
                          title: "Clean Docker build cache?",
                          body: "Prunes unused build cache and dangling image layers without touching running or stopped containers.")
    }

    @objc func openMacVitals() {
        NSWorkspace.shared.open(macVitalsURL)
    }

    /// Odyssеus local-model usage: token totals, sessions, running state from /api/local-usage.
    /// Read on a 30 s cadence (the hub polls the opencode DB every 30 s).
    var lastLocalUsage = Date.distantPast
    func refreshLocalUsage() {
        guard Date().timeIntervalSince(lastLocalUsage) > 30 else { return }
        lastLocalUsage = Date()
        var req = URLRequest(url: localUsageURL); req.timeoutInterval = 5
        URLSession.shared.dataTask(with: req) { [weak self] data, _, _ in
            guard let self = self, let data = data else { return }
            let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
            DispatchQueue.main.async {
                guard let j = json else { return }
                if let oc = j["opencode"] as? [String: Any] {
                    let running = oc["running"] as? Bool ?? false
                    let sessions = (oc["sessions"] as? NSNumber)?.intValue ?? 0
                    let requests = (oc["requests"] as? NSNumber)?.intValue ?? 0
                    let prompt = (oc["prompt"] as? NSNumber)?.intValue ?? 0
                    let completion = (oc["completion"] as? NSNumber)?.intValue ?? 0
                    let model = oc["model"] as? String ?? "local model"
                    let total = prompt + completion
                    self.localUsageLine = running
                        ? "\(model): \(fmtN(total)) tok · \(sessions) sess · \(requests) req · running"
                        : "\(model): \(fmtN(total)) tok · \(sessions) sess · idle"
                    self.localTokensOnly = "\(fmtN(total)) tok"
                } else if let sources = j["sources"] as? [[String: Any]], !sources.isEmpty {
                    let totalPrompt = sources.reduce(0) { $0 + ((($1["prompt"] as? NSNumber)?.intValue) ?? 0) }
                    let totalCompletion = sources.reduce(0) { $0 + ((($1["completion"] as? NSNumber)?.intValue) ?? 0) }
                    self.localUsageLine = "local models: \(fmtN(totalPrompt + totalCompletion)) tok"
                    self.localTokensOnly = "\(fmtN(totalPrompt + totalCompletion)) tok"
                }
                self.redrawRows()
            }
        }.resume()
    }

    func refreshExtras(force: Bool = false) {
        guard force || Date().timeIntervalSince(lastExtras) > 10 else { return }
        lastExtras = Date()
        let group = DispatchGroup()
        var models: [String: Any]?, targets: [String: Any]?, logins: [String: Any]?, handJSON: [String: Any]?, autoContinueJSON: [String: Any]?, broadcastJSON: [String: Any]?
        func fetch(_ url: URL, _ done: @escaping ([String: Any]?) -> Void) {
            // Inline cache: skip the request and JSON parsing if we have fresh data.
            if !force, let json = cachedFetchJSON(url, extrasCacheTTL) {
                done(json); return
            }
            var req = URLRequest(url: url)
            req.cachePolicy = .reloadIgnoringLocalCacheData
            req.timeoutInterval = 6
            group.enter()
            URLSession.shared.dataTask(with: req) { data, _, _ in
                let json = self.parseJSON(data)
                DispatchQueue.main.async {
                    if let json = json { self.cache[url] = (json, Date()) }
                    done(json)
                    group.leave()
                }
            }.resume()
        }
        fetch(modelsURL) { models = $0 }
        fetch(targetsURL) { targets = $0 }
        fetch(accountsURL) { logins = $0 }
        fetch(handURL) { handJSON = $0 }
        fetch(autoContinueURL) { autoContinueJSON = $0 }
        fetch(broadcastURL) { broadcastJSON = $0 }
        group.notify(queue: .main) { [weak self] in
            guard let self = self else { return }
            if let m = models?["models"] as? [[String: Any]] { self.tools = m.map { ToolInfo($0) } }
            if let t = targets?["targets"] as? [String: Any] { self.handTargets = t.compactMapValues { $0 as? Bool } }
            if let a = logins?["accounts"] as? [[String: Any]] { self.claudeLogins = a.compactMap { $0["name"] as? String } }
            if let h = handJSON?["sessions"] as? [[String: Any]] { self.hand = h.map { HandSession($0) }.filter { $0.pid > 0 } }
            if let c = broadcastJSON?["clusters"] as? [[String: Any]] {
                self.broadcastClusters = c.map { BroadcastCluster($0) }.filter { !$0.cwd.isEmpty }
                self.renderBroadcastMenu()
            }
            if let ac = autoContinueJSON {
                self.autoContinueAll = ac["all"] as? Bool ?? false
                if let msg = ac["message"] as? String, !msg.isEmpty { self.autoContinueMessage = msg }
                if let ags = ac["agents"] as? [String: [String: Any]] { self.autoContinueAgents = ags }
                self.renderAutoContinue()
            }
            self.render()
        }
    }

    /// One tool's usage line, as the deck's dock words it; nil when it is not installed.
    func toolLine(_ t: ToolInfo) -> (String, NSColor)? {
        guard t.installed else { return nil }
        if t.loggedIn == false { return (clip("\(t.id) · not logged in", 58), accent) }
        let windows = measuredWindows(t.windows)
        guard !windows.isEmpty else { return nil }
        var parts = [t.id]
        parts.append(windows.map { "\($0.pct) \($0.label)" }.joined(separator: " · "))
        if t.id == "codex" {
            let who = [t.login, t.plan].filter { !$0.isEmpty }.joined(separator: " ")
            if !who.isEmpty { parts.append(who) }
        } else { parts.append(t.loggedIn == true ? "logged in" : "login unknown") }
        if !windows.isEmpty {
            if windows.count == 1, let at = windows[0].resetsAt, let r = formatIn(at.timeIntervalSinceNow) { parts.append("resets in \(r)") }
        }
        if !t.reached.isEmpty { parts.append("limit reached") }
        return (clip(parts.joined(separator: " · "), 58), t.reached.isEmpty ? .secondaryLabelColor : .systemRed)
    }

    /// kiro / opencode / gemini / antigrav, worded like the dock and the board (collectors/board_view.js otherLine). `withGemini`: gemini
    /// is antigrav's program, said once on antigrav's line; `compact`: an agent's own line (no reset).
    func otherLine(_ t: ToolInfo, withGemini: Bool = false, compact: Bool = false) -> (String, NSColor)? {
        guard t.installed else { return nil }
        let name = t.id == "agy" && withGemini ? "antigrav = gemini" : (t.label.isEmpty ? t.id : t.label)
        if t.offline { return (clip("\(name) · offline", 58), accent) }
        if t.loggedIn == false { return (clip("\(name) · not logged in", 58), accent) }
        let windows = measuredWindows(t.windows)
        let hasKiroReading = t.id == "kiro" && (t.credits?.limit ?? 0) > 0
        guard !windows.isEmpty || hasKiroReading || t.reached == "balance" else { return nil }
        func num(_ v: Double) -> String { let r = (v * 100).rounded() / 100; return r == r.rounded() ? String(Int(r)) : String(r) }
        var parts = [name]
        var tint = NSColor.secondaryLabelColor
        switch t.id {
        case "kiro":
            if let c = t.credits {
                let pct = c.limit > 0 ? c.used / c.limit * 100 : 0   // the share used, next to the credits (one decimal under 1 %)
                let pctStr = c.limit > 0 ? (pct > 0 && pct < 1 ? String(format: "%.1f%%", pct) : "\(Int(pct.rounded()))%") : ""
                let pfx = pctStr.isEmpty ? "" : pctStr + " "
                parts.append("\(pfx)\(windows.first?.label ?? "usage") · \(num(c.used))/\(num(c.limit)) credits")
                if !compact, let at = windows.first?.resetsAt, let r = formatIn(at.timeIntervalSinceNow) { parts.append("resets in \(r)") }
            } else if !windows.isEmpty {
                parts.append(windows.map { "\($0.pct) \($0.label)" }.joined(separator: " · "))
            } else { return nil }
            if !t.plan.isEmpty { parts.append(t.plan) }
            if !t.reached.isEmpty { parts.append("credits used up"); tint = .systemRed }
        case "opencode":
            parts.append(windows.map { "\($0.pct) \($0.label)" }.joined(separator: " · "))
            parts.append("keyless")
        default:
            if t.from == "agy" {   // (the menu's 58 characters leave out the shown group's name; the board says "Gemini")
                let profiles = t.profiles.compactMap { profile -> String? in
                    let ws = measuredWindows(profile.windows)
                    guard let w = ws.first(where: { $0.label == "5h" }) ?? ws.first, let percent = w.percent else { return nil }
                    return "\(profile.label.replacingOccurrences(of: "^antigrav\\s+", with: "", options: .regularExpression)) \(percent)%"
                }
                if profiles.isEmpty { parts.append(windows.map { "\($0.pct) \($0.label)" }.joined(separator: " · ")) }
                else { parts.append(profiles.joined(separator: " · ")) }
            } else if t.reached == "balance" {   // kimi: its last turn failed for want of balance
                parts.append("no balance"); tint = .systemRed
            } else if !windows.isEmpty {   // copilot: its monthly allowance; groq: the day's requests
                parts.append(windows.map { "\($0.pct) \($0.label)" }.joined(separator: " · "))
                if !t.plan.isEmpty { parts.append(t.plan) }
            } else { return nil }
        }
        return (clip(parts.joined(separator: " · "), 58), tint)
    }

    /// One tool's detailed usage breakdown, as lines for the submenu (clicking the tool name).
    func toolDetailsLine(_ t: ToolInfo) -> [(String, NSColor)] {
        var out: [(String, NSColor)] = []
        guard t.installed else { return [] }
        if t.loggedIn == false { return [("not logged in", NSColor.systemRed)] }
        let windows = measuredWindows(t.windows)
        if windows.isEmpty, t.credits == nil {
            if t.reached == "balance" { return [("no balance", NSColor.systemRed)] }
            return []
        }
        if windows.isEmpty, let c = t.credits, c.limit > 0 {
            let pct = Int((c.used / c.limit * 100).rounded())
            out.append(("\(pct)% usage · \(c.used)/\(c.limit) credits", pct >= 90 ? .systemRed : .secondaryLabelColor))
        }
        for w in windows {
            let line: String
            // credits: from ToolInfo.credits (kiro), percentages: from Win.percent
            let isCreditTool = (t.id == "kiro" && t.credits != nil)
            if isCreditTool, let c = t.credits {
                let n = { (v: Double) -> String in let r = (v * 100).rounded() / 100; return r == r.rounded() ? String(Int(r)) : String(r) }
                line = "\(w.pct) \(w.label) · \(n(c.used))/\(n(c.limit)) credits"
            } else {
                line = "\(w.pct) \(w.label)"
            }
            let pct = w.percent ?? 0
            let tint = pct >= 90 ? NSColor.systemRed : NSColor.secondaryLabelColor
            out.append((line, tint))
        }
        if !t.plan.isEmpty { out.append(("\(t.plan) plan", NSColor.secondaryLabelColor)) }
        if !t.reached.isEmpty { out.append(("limit reached", NSColor.systemRed)) }
        if t.reached == "balance" { out.append(("no balance", NSColor.systemRed)) }
        if let at = windows.first?.resetsAt {
            if let r = formatIn(at.timeIntervalSinceNow) { out.append(("resets in \(r)", NSColor.secondaryLabelColor)) }
        }
        return out
    }

    var showAgyTool = false   // the self-test turns it on to check antigrav's tool line wording
    var lastToolsSig = ""
    func renderTools() {
        let geminiIsAgy = tools.contains { $0.id == "gemini" && $0.installed && $0.sameAs == "agy" } && tools.contains { $0.id == "agy" && $0.installed }
        let rows = tools.compactMap { t -> (ToolInfo, String, NSColor)? in
            if t.id == "local" { return nil }
            if t.id == "codex" || t.id == "cursor", let line = toolLine(t) { return (t, line.0, line.1) }
            if t.id == "gemini" && geminiIsAgy { return nil }   // said once, on antigrav's line
            if t.id == "agy" && !showAgyTool { return nil }   // antigrav has its own account row above (same login, same figures)
            if extraTiles.contains(t.id) && !t.active && t.agentsTotal == 0 { return nil }   // copilot, kimi …: only while in use, as in the dock
            guard let line = otherLine(t, withGemini: geminiIsAgy) else { return nil }
            return (t, line.0, line.1)
        }
        let sig = rows.map { "\($0.0.id)|\($0.1)|\($0.2)" }.joined(separator: ";")
        guard sig != lastToolsSig else { return }
        lastToolsSig = sig
        let lines = rows.map { ($0.1, $0.2) }
        toolsHead.online = online
        toolsSep.isHidden = lines.isEmpty; toolsHeadItem.isHidden = lines.isEmpty
        // Clear old entries so stale data (e.g. from a prior live render) doesn't leak into self-test reads
        for i in lines.count..<toolRows.count { toolRows[i].line = ""; toolRows[i].tint = .clear }
        // Update both the NoteRow views (for the test) and the NSMenuItems (for the actual menu)
        let items = toolMenuItems.isEmpty ? toolItems : toolMenuItems
        for (i, mi) in items.enumerated() {
            mi.isHidden = i >= lines.count
            if i < lines.count {
                toolRows[i].line = lines[i].0; toolRows[i].tint = lines[i].1
                let title = NSAttributedString(string: lines[i].0, attributes: [.font: body, .foregroundColor: lines[i].1])
                mi.attributedTitle = title
                // Build the detailed breakdown submenu lazily on hover
                let rowTool = i < rows.count ? rows[i].0 : nil
                let sub = DynamicMenu(title: lines[i].0) { [weak self] subMenu in
                    guard let self = self, let tool = rowTool else { return }
                    let detail = self.toolDetailsLine(tool)
                    for (l, c) in detail {
                        let r = NoteRow(); r.line = l; r.tint = c
                        let li = NSMenuItem(); li.view = r; li.title = l
                        subMenu.addItem(li)
                    }
                }
                mi.submenu = sub
            }
        }
    }

    /// Live agents, the ones that need you first (error, waiting), then running, then idle; the deck's own order within a group.
    func liveAgents() -> [AgentInfo] {
        func rank(_ a: AgentInfo) -> Int { a.status == "error" ? 0 : (a.status == "waiting" ? 1 : (a.status == "running" || a.status == "starting" ? 2 : 3)) }
        return agents.filter { $0.live }.sorted { rank($0) != rank($1) ? rank($0) < rank($1) : $0.slot < $1.slot }
    }

    /// What the agent items show. Cost is left out on purpose (it moves every few seconds); opening the menu rebuilds regardless.
    func agentSignature() -> String {
        let a = liveAgents().map { "\($0.id)|\($0.status)|\($0.title)|\($0.account)|\($0.ctxPercent ?? -1)|\($0.activity)|\($0.cwd)" }.joined(separator: ";")
            + "&" + hand.map { "\($0.pid)|\($0.tool)|\($0.cwd)" }.joined(separator: ";")
        let u = accounts.map { "\($0.id)=\($0.short.percent ?? -1)/\($0.week.percent ?? -1)/\($0.expired)" }.joined(separator: ",")
        let t = tools.compactMap { toolLine($0)?.0 }.joined(separator: ",")
        let h = handTargets.sorted { $0.key < $1.key }.map { "\($0.key)=\($0.value)" }.joined(separator: ",")
        let b = broadcastClusters.map { "\($0.cwd)|\($0.agentCount)|\($0.reachableCount)|\($0.companies.joined(separator: "+"))" }.joined(separator: ";")
        return [a, u, t, h, b, claudeLogins.joined(separator: ",")].joined(separator: "#")
    }

    func rebuildAgentMenu(force: Bool = false) {
        let sig = agentSignature()
        guard force || sig != lastAgentSig else { return }
        // Never pull an item (and its open submenu) while the menu is open: wait until it closes.
        if menuOpen && !force { pendingMenuRebuild = true; return }
        lastAgentSig = sig; pendingMenuRebuild = false
        for mi in agentItems { menu.removeItem(mi) }
        agentItems.removeAll()
        renderBroadcastMenu()
        guard online else { return }
        var at = menu.index(of: agentsItem) + 1
        func put(_ mi: NSMenuItem) { menu.insertItem(mi, at: at); at += 1; agentItems.append(mi) }
        let (top, rest) = agentLayout()
        for a in top { put(agentItem(a, eager: false)) }
        if !rest.isEmpty {   // nothing is dropped: what doesn't fit on top is one submenu away
            let allIdle = rest.allSatisfy { !$0.needsYou && $0.status != "running" && $0.status != "starting" }
            let mi = NSMenuItem(title: (allIdle ? "Idle agents" : "More agents") + " · \(rest.count)", action: nil, keyEquivalent: "")
            let sub = DynamicMenu(title: mi.title) { [weak self] subMenu in
                guard let self = self else { return }
                for a in rest { subMenu.addItem(self.agentItem(a, eager: false)) }
            }
            mi.submenu = sub
            put(mi)
        }
        for h in hand { put(handItem(h)) }
    }

    /// Which agents go straight in the menu and which into the "Idle / More agents" submenu. All of them fit: one flat list. Too many:
    /// the ones that need you or are running stay on top (up to maxAgentsShown) and everything else, idle first, moves down a level.
    /// The hand-started sessions are always on top (there are few, and the deck can't show them).
    func agentLayout() -> (top: [AgentInfo], rest: [AgentInfo]) {
        let live = liveAgents()
        let room = max(4, maxAgentsShown - hand.count)
        guard live.count > room else { return (live, []) }
        let busy = live.filter { $0.needsYou || $0.status == "running" || $0.status == "starting" }
        let top = Array(busy.prefix(room - 1))   // - 1: the submenu's own row
        let shown = Set(top.map { $0.id })
        return (top, live.filter { !shown.contains($0.id) })
    }

    func agentItem(_ a: AgentInfo, eager: Bool = false) -> NSMenuItem {
        let mi = NSMenuItem(title: a.title, action: nil, keyEquivalent: "")
        mi.attributedTitle = agentTitle(a)
        mi.image = kinCritter(a.kind, faded: ["idle", "starting", "exited"].contains(a.status))
        if eager {
            mi.submenu = agentSubmenu(a)
        } else {
            mi.submenu = DynamicMenu(title: a.title) { [weak self] m in
                self?.populateAgentSubmenu(a, into: m)
            }
        }
        return mi
    }

    /// "● Github Master   antigrav · by hand": a session started in a terminal. Its submenu says so, shows its tool's usage and can
    /// raise its window; it has no continue / hand over (the deck never ran it, so there is no brief to move).
    func handItem(_ h: HandSession) -> NSMenuItem {
        let mi = NSMenuItem(title: "\(h.folder) · \(h.tool) by hand", action: nil, keyEquivalent: "")
        let s = NSMutableAttributedString()
        s.append(NSAttributedString(string: "● ", attributes: [.font: body, .foregroundColor: NSColor.systemTeal]))
        s.append(NSAttributedString(string: clip(h.folder.isEmpty ? h.tool : h.folder, 30), attributes: [.font: body]))
        s.append(NSAttributedString(string: "   \(h.tool) · by hand", attributes: [.font: small, .foregroundColor: NSColor.secondaryLabelColor]))
        mi.attributedTitle = s
        mi.image = kinCritter(h.tool)
        let sub = DynamicMenu(title: mi.title) { [weak self] m in
            guard let self = self else { return }
            func line(_ t: String, _ tint: NSColor = .secondaryLabelColor) {
                let r = NoteRow(); r.line = clip(t, 52); r.tint = tint
                let li = NSMenuItem(); li.view = r; li.title = t; m.addItem(li)
            }
            line("started by hand in a terminal · not on the deck")
            if !h.cwd.isEmpty { line((h.cwd as NSString).abbreviatingWithTildeInPath) }
            for u in self.usageLines(h.asAgent) { line(u, .labelColor) }
            m.addItem(.separator())
            let f = NSMenuItem(title: "Focus terminal", action: #selector(self.menuFocusHand(_:)), keyEquivalent: "")
            f.target = self; f.representedObject = Act(String(h.pid))
            m.addItem(f)
            if let bi = self.broadcastSubmenuItem(for: h.cwd) { m.addItem(bi) }
        }
        mi.submenu = sub
        return mi
    }

    func statusColor(_ a: AgentInfo) -> NSColor {
        switch a.status {
        case "error": return .systemRed
        case "waiting": return accent
        case "running", "starting": return .systemGreen
        default: return .tertiaryLabelColor
        }
    }

    /// "● title   claude · work · needs you": a coloured status dot, the title in the menu's own colour, the rest small and grey.
    func agentTitle(_ a: AgentInfo) -> NSAttributedString {
        let s = NSMutableAttributedString()
        s.append(NSAttributedString(string: "● ", attributes: [.font: body, .foregroundColor: statusColor(a)]))
        s.append(NSAttributedString(string: clip(a.cleanTitle, 30), attributes: [.font: body]))
        var tag = (a.isAntigrav ? "antigrav \(a.agyProfile)" : a.kind) + (a.account.isEmpty ? "" : " · \(a.account)")
        switch a.status {
        case "waiting": tag += " · needs you"
        case "error": tag += " · error"
        case "running": tag += " · running"
        default: break
        }
        s.append(NSAttributedString(string: "   " + tag, attributes: [.font: small, .foregroundColor: NSColor.secondaryLabelColor]))
        return s
    }

    func statusLine(_ a: AgentInfo) -> String {
        switch a.status {
        case "running": return "running" + (a.activity.isEmpty ? "" : " · \(a.activity)")
        case "waiting": return "needs you · answer it in its terminal"
        case "error": return "error" + (a.error.isEmpty ? "" : " · \(a.error)")
        default: return a.status.isEmpty ? "idle" : a.status
        }
    }

    /// The usage lines of one agent: its login's 5h / 7d (Claude, antigrav), codex's own windows, context and cost. Only real readings.
    func usageLines(_ a: AgentInfo) -> [String] {
        var out: [String] = []
        func acctLine(_ id: String, _ name: String) -> String? {
            guard let x = accounts.first(where: { $0.id == id }) else { return nil }
            if x.expired { return "\(name) · login expired" }
            let windows = measuredWindows([x.short, x.week])
            guard !windows.isEmpty else { return nil }
            func w(_ v: Win) -> String { v.pct + " \(v.label.isEmpty ? "?" : v.label)" }
            return "\(name) · \(windows.map(w).joined(separator: " · "))"
        }
        // An antigrav tile reads its own launcher's account ("antigrav-work" -> antigrav work); a gemini agent (the same program) the first one with a reading.
        let agyIds = accounts.filter { $0.id == "agy" || $0.id.hasPrefix("agy-") }
        let agyOwn = agyIds.first(where: { $0.id == "agy-\(a.agyProfile)" })
        let agyAcct = (a.isAntigrav ? agyOwn : nil) ?? agyIds.first(where: { $0.short.percent != nil || $0.week.percent != nil }) ?? agyIds.first
        let agyId = agyAcct?.id ?? "agy"
        let agyName = (agyAcct?.label ?? "").isEmpty ? "antigrav" : agyAcct!.label   // ("antigrav work" / "antigrav personal")
        if a.tool == "claude", !a.account.isEmpty, let l = acctLine(a.account, a.account) { out.append(l) }
        if a.isAntigrav, let l = acctLine(agyId, agyName) { out.append(l) }
        if a.tool == "codex" || a.isCursor, let t = tools.first(where: { $0.id == (a.isCursor ? "cursor" : "codex") }), let l = toolLine(t) { out.append(l.0) }
        if let k = a.tileTool, k != "cursor", let t = tools.first(where: { $0.id == k }), let l = otherLine(t, compact: true) { out.append(l.0) }
        if a.tool == "gemini" {   // the same program and login as antigrav: its figures
            // /api/models folds gemini's row into antigrav's when they are one program, so there is no gemini row then (10 Nov): "no row, antigrav
            // installed" means the same as sameAs == "agy". A gemini row of its own (a separate install) has no reading.
            let g = tools.first(where: { $0.id == "gemini" })
            let same = g.map { $0.sameAs == "agy" } ?? tools.contains { $0.id == "agy" && $0.installed }
            if same, let l = acctLine(agyId, "gemini = \(agyName)") { out.append(l) }
        }
        var own: [String] = []
        if let c = a.ctxPercent { own.append("context \(c)%") }
        if a.tool == "claude", a.costUsd > 0 { own.append(String(format: "$%.2f", a.costUsd)) }
        if !own.isEmpty { out.append(own.joined(separator: " · ")) }

        // Token usage and estimated cost based on provider and model (lifetime, weekly, daily, hourly)
        func fmtCost(_ usd: Double) -> String { usd > 0 ? String(format: "$%.2f", usd) : "$0.00" }
        let prov = (a.provider.isEmpty ? a.kind : a.provider).lowercased()
        let cleanModel = a.model.replacingOccurrences(of: "claude-", with: "")
        let modHeader = cleanModel.isEmpty ? prov : "\(prov) · \(cleanModel)"
        if a.lifeUsage.tokens > 0 || a.lifeUsage.costUsd > 0 {
            out.append(modHeader)
            out.append("life \(fmtN(a.lifeUsage.tokens)) (\(fmtCost(a.lifeUsage.costUsd))) · 7d \(fmtN(a.weekUsage.tokens)) (\(fmtCost(a.weekUsage.costUsd)))")
            out.append("today \(fmtN(a.dayUsage.tokens)) (\(fmtCost(a.dayUsage.costUsd))) · 1h \(fmtN(a.hourUsage.tokens)) (\(fmtCost(a.hourUsage.costUsd)))")
        }
        return out
    }

    /// "personal · 22% used" / "personal · login expired": what the target login has left, like the deck's button.
    func accountOption(_ id: String) -> String {
        guard let x = accounts.first(where: { $0.id == id }) else { return id }
        if x.expired { return "\(id) · login expired" }
        return x.short.percent == nil ? id : "\(id) · \(x.short.pct) used"
    }

    func populateAgentSubmenu(_ a: AgentInfo, into m: NSMenu) {
        func line(_ s: String, _ tint: NSColor = .secondaryLabelColor) {
            let r = NoteRow(); r.line = clip(s, 52); r.tint = tint
            let mi = NSMenuItem(); mi.view = r; mi.title = s; m.addItem(mi)   // the title is what VoiceOver reads
        }
        func entry(_ title: String, _ sel: Selector?, _ act: Act?, enabled: Bool = true, to dest: NSMenu) {
            let mi = NSMenuItem(title: title, action: sel, keyEquivalent: "")
            mi.target = self; mi.representedObject = act; mi.isEnabled = enabled
            dest.addItem(mi)
        }
        func parent(_ title: String, _ sub: NSMenu) {
            let mi = NSMenuItem(title: title, action: nil, keyEquivalent: ""); mi.submenu = sub; m.addItem(mi)
        }
        line(statusLine(a), a.status == "error" ? .systemRed : (a.status == "waiting" ? accent : .secondaryLabelColor))
        if !a.folder.isEmpty { line(a.folder + (a.branch.isEmpty ? "" : " · " + a.branch)) }
        for u in usageLines(a) { line(u, .labelColor) }
        m.addItem(.separator())
        entry("Focus terminal", #selector(menuFocus(_:)), Act(a.id), to: m)
        if let bi = broadcastSubmenuItem(for: a.cwd) { m.addItem(bi) }
        if isModelAgent(a) {
            let acInfo = autoContinueAgents[a.id]
            let isAgy = a.tool == "agy" || a.tool == "antigravity" || a.title.hasPrefix("antigrav") || a.title.hasPrefix("agy")
            let acEnabled = acInfo?["enabled"] as? Bool ?? (isAgy ? true : autoContinueAll)
            let acState = acInfo?["state"] as? String ?? (acEnabled ? "armed" : "off")
            let acDetail = acInfo?["detail"] as? String ?? ""
            entry("Auto-continue on limits: \(acEnabled ? "ON" : "OFF")", #selector(toggleAgentAutoContinue(_:)), Act(a.id), to: m)
            if !acDetail.isEmpty {
                line("↳ " + acDetail, acState == "waiting" ? accent : .secondaryLabelColor)
            }
        }
        guard a.movable else { return }
        let logins = claudeLogins.isEmpty ? accounts.filter { $0.id != "agy" && !$0.id.hasPrefix("agy-") }.map { $0.id } : claudeLogins
        if a.tool == "claude" {   // the conversation itself moves to another login
            let sub = NSMenu(title: "Continue on"); sub.autoenablesItems = false
            let others = logins.filter { $0 != a.account }
            for l in others { entry(accountOption(l), #selector(menuHandover(_:)), Act(a.id, l), to: sub) }
            if others.isEmpty { entry("no other Claude account", nil, nil, enabled: false, to: sub) }
            parent("Continue on", sub)
        }
        let hand = NSMenu(title: "Hand over to"); hand.autoenablesItems = false
        if a.tool != "claude" {   // another tool's job starts a NEW Claude agent from a brief
            for l in logins { entry("Claude · " + accountOption(l), #selector(menuHandover(_:)), Act(a.id, l), to: hand) }
        }
        var agyTargets: [(String, String)] = [("agy-work", "antigrav work"), ("agy-personal", "antigrav personal")]
        if handTargets["agy-free"] == true { agyTargets.append(("agy-free", "antigrav free")) }
        for (key, name) in agyTargets + [("codex", "codex"), ("cursor", "cursor"), ("kiro", "kiro"), ("opencode", "opencode")] where key != a.handoverKey {   // no gemini for now: antigrav's own program here
            let there = handTargets[key] ?? true   // unknown until the hub answered: let the hub refuse
            entry(there ? name : "\(name) (not installed)", #selector(menuHandover(_:)), Act(a.id, key), enabled: there, to: hand)
        }
        for key in extraTiles where key != a.handoverKey && handTargets[key] == true {   // copilot, kimi …: only the installed ones
            entry(key, #selector(menuHandover(_:)), Act(a.id, key), to: hand)
        }
        if a.handoverKey != "local" {   // the local model last: the weakest, the offline fallback
            let there = handTargets["local"] ?? true
            entry(there ? "local model" : "local model (not installed)", #selector(menuHandover(_:)), Act(a.id, "local"), enabled: there, to: hand)
        }
        parent("Hand over to", hand)
    }

    func agentSubmenu(_ a: AgentInfo) -> NSMenu {
        let m = NSMenu(title: a.title)
        m.autoenablesItems = false
        populateAgentSubmenu(a, into: m)
        return m
    }

    // MARK: actions of those items

    func isModelAgent(_ a: AgentInfo) -> Bool {
        if a.tool == "claude" || a.tool == "codex" || a.tool == "gemini" || a.tool == "agy" || a.tool == "antigravity" { return true }
        if let t = a.tileTool, !t.isEmpty { return true }
        let low = a.title.lowercased()
        let prefixList = ["antigrav", "agy", "codex", "cursor", "kiro", "opencode", "copilot", "kimi", "groq", "hermes", "nvidia", "cerebras", "local", "gemini"]
        return prefixList.contains { low.hasPrefix($0) }
    }

    func renderAutoContinue() {
        guard let item = autoContinueItem else { return }
        item.state = autoContinueAll ? .on : .off
        item.title = autoContinueAll ? "Auto-continue all models on limits (ON · “\(autoContinueMessage)”)" : "Auto-continue all models on limits (OFF)"
    }

    func renderCapriMenu() {
        guard let item = capriItem else { return }
        item.state = capriEnabled ? .on : .off
        item.title = capriEnabled ? "Capri HUD (ON)" : "Capri HUD (OFF)"
    }

    func setCapriEnabled(_ on: Bool, pushWindow: Bool = true, pushPopover: Bool = true) {
        capriEnabled = on
        if !selfTesting {
            UserDefaults.standard.set(on, forKey: "capriEnabled")
            if on { capriHUD.show() } else { capriHUD.hide() }
        }
        renderCapriMenu()
        if pushWindow { deckWindow.pushCapri(on) }
        if pushPopover {
            web?.evaluateJavaScript("window.setCapriEnabled && window.setCapriEnabled(\(on ? "true" : "false"))", completionHandler: nil)
        }
    }

    @objc func toggleCapri() {
        setCapriEnabled(!capriEnabled)
        say(capriEnabled ? "Capri HUD ON" : "Capri HUD OFF")
    }

    @objc func toggleAutoContinue() {
        let want = !autoContinueAll
        hubPost("/api/auto-continue", ["all": want]) { [weak self] status, j in
            guard let self = self else { return }
            if (200..<300).contains(status), j["ok"] as? Bool == true {
                self.autoContinueAll = j["all"] as? Bool ?? want
                if let msg = j["message"] as? String, !msg.isEmpty { self.autoContinueMessage = msg }
                if let ags = j["agents"] as? [String: [String: Any]] { self.autoContinueAgents = ags }
                self.renderAutoContinue()
                self.say(self.autoContinueAll ? "auto-continue on for all models (types “\(self.autoContinueMessage)” after limit reset)" : "auto-continue switched off")
                self.rebuildAgentMenu()
            } else {
                let why = j["error"] as? String ?? "HTTP \(status)"
                self.say("couldn't toggle auto-continue · \(why)", bad: true)
            }
        }
    }

    @objc func toggleAgentAutoContinue(_ s: NSMenuItem) {
        guard let a = s.representedObject as? Act, validId(a.id) else { return }
        let current = (autoContinueAgents[a.id]?["enabled"] as? Bool) ?? (a.id.hasPrefix("agy") ? true : autoContinueAll)
        let want = !current
        hubPost("/api/agents/\(a.id)/auto-continue", ["enabled": want]) { [weak self] status, j in
            guard let self = self else { return }
            if (200..<300).contains(status), j["ok"] as? Bool == true {
                if let ags = j["agents"] as? [String: [String: Any]] { self.autoContinueAgents = ags }
                self.say("auto-continue for \(a.id): \(want ? "ON" : "OFF")")
                self.rebuildAgentMenu()
            } else {
                let why = j["error"] as? String ?? "HTTP \(status)"
                self.say("couldn't toggle auto-continue for \(a.id) · \(why)", bad: true)
            }
        }
    }

    func validId(_ s: String) -> Bool { s.range(of: "^[0-9a-z]{4,12}$", options: .regularExpression) != nil }

    @objc func menuFocus(_ s: NSMenuItem) {
        guard let a = s.representedObject as? Act, validId(a.id) else { return }
        focusAgent(a.id)
    }

    @objc func menuFocusHand(_ s: NSMenuItem) {
        guard let a = s.representedObject as? Act, a.id.range(of: "^[0-9]{1,7}$", options: .regularExpression) != nil else { return }
        hubPost("/api/agents/hand/\(a.id)/focus", [:], timeout: 15) { [weak self] status, j in
            let why = j["detail"] as? String ?? j["error"] as? String ?? "the hub answered \(status)"
            if (200..<300).contains(status), j["ok"] as? Bool == true { self?.say("focused its terminal") }
            else { self?.say("couldn't focus its terminal · \(why)", bad: true) }
        }
    }

    func broadcastCluster(for cwd: String) -> BroadcastCluster? {
        guard !cwd.isEmpty else { return nil }
        return broadcastClusters.first { $0.matches(cwd) }
    }

    func broadcastSubmenuItem(for cwd: String) -> NSMenuItem? {
        guard let cl = broadcastCluster(for: cwd), cl.agentCount >= 2 else { return nil }
        let mi = NSMenuItem(title: "Broadcast to folder (\(cl.agentCount))…", action: #selector(menuBroadcast(_:)), keyEquivalent: "")
        mi.target = self; mi.representedObject = cl.cwd
        return mi
    }

    func renderBroadcastMenu() {
        guard let item = broadcastItem else { return }
        if menuOpen { pendingMenuRebuild = true; return }
        item.isHidden = !online
        let multi = broadcastClusters.filter { $0.agentCount >= 2 }
        if multi.isEmpty {
            item.submenu = nil
            item.action = #selector(menuBroadcast(_:))
            item.representedObject = ""
            item.title = broadcastClusters.isEmpty ? "Broadcast to folder…" : "Broadcast to folder (\(broadcastClusters.count))…"
            return
        }
        let sub = NSMenu(title: "Broadcast to folder")
        sub.autoenablesItems = false
        for cl in multi {
            let co = cl.companies.joined(separator: " + ")
            let label = "\(clip(cl.folder, 24)) · \(cl.agentCount) agents" + (co.isEmpty ? "" : " · \(co)")
            let mi = NSMenuItem(title: label, action: #selector(menuBroadcast(_:)), keyEquivalent: "")
            mi.target = self; mi.representedObject = cl.cwd
            sub.addItem(mi)
        }
        sub.addItem(.separator())
        let all = NSMenuItem(title: "All folders…", action: #selector(menuBroadcast(_:)), keyEquivalent: "")
        all.target = self; all.representedObject = ""
        sub.addItem(all)
        item.action = nil
        item.submenu = sub
        item.title = "Broadcast to cluster (\(multi.count))…"
    }

    /// Open the deck's folder-broadcast dialog for one folder (or the cluster picker). Nothing is sent from the menu.
    @objc func menuBroadcast(_ s: NSMenuItem) {
        let dir = (s.representedObject as? String) ?? ""
        let validDir = dir.isEmpty || (dir.count <= 1024 && dir.hasPrefix("/") && dir.unicodeScalars.allSatisfy { $0.value >= 0x20 && $0.value != 0x7f })
        guard validDir,
              let data = try? JSONSerialization.data(withJSONObject: [dir]),
              let args = String(data: data, encoding: .utf8) else { return }
        openDeck(then: "window.broadcastFolder && window.broadcastFolder(...\(args))")
    }

    /// Continue on another login / hand over to another tool. Nothing moves from this menu: it opens the deck on that agent's own
    /// dialog (which previews the brief, tells what will happen, and wants a second click).
    @objc func menuHandover(_ s: NSMenuItem) {
        guard let a = s.representedObject as? Act, validId(a.id), a.target.range(of: "^[\\w-]{1,32}$", options: .regularExpression) != nil,
              let data = try? JSONSerialization.data(withJSONObject: [a.target, a.id]), let args = String(data: data, encoding: .utf8) else { return }
        openDeck(then: "window.handoffAgent && window.handoffAgent(...\(args))")
    }

    func openDeck(then js: String?) {
        lastDeckCall = js ?? ""
        pendingPage = js
        if popover.isShown, let w = web, w.url?.host == "127.0.0.1", !webFailed { runPendingPage(); return }
        if popover.isShown { return }   // still loading (or retrying): the call goes in when the page is ready
        showPopover()
    }
    func runPendingPage() {
        guard let js = pendingPage else { return }
        pendingPage = nil
        web?.evaluateJavaScript(js, completionHandler: nil)
    }

    func focusAgent(_ id: String) {
        hubPost("/v1/agents/\(id)/focus", [:], timeout: 25) { [weak self] status, j in
            guard let self = self else { return }
            if (200..<300).contains(status) { self.say("focused its terminal"); return }
            let why = j["error"] as? String ?? "the hub answered \(status)"
            if status == 409, j["canResume"] as? Bool == true {   // nothing to raise: like the deck, offer to resume it into a Mac terminal
                guard self.ask("Resume it in a Mac terminal?", "\(why).\n\nThis resumes the conversation under the daemon and opens a terminal tab for it.", ok: "Resume and open") else { return }
                self.say("resuming it and opening a terminal…")
                self.hubPost("/api/agents/\(id)/continue-in-terminal", [:], timeout: 60) { st, r in
                    if (200..<300).contains(st) { self.say(r["opened"] as? Bool == true ? "open in a Mac terminal" : (r["note"] as? String ?? "resumed")) }
                    else { self.say("couldn't continue in a terminal · " + (r["error"] as? String ?? "HTTP \(st)"), bad: true) }
                }
                return
            }
            self.say("couldn't focus its terminal · \(why)", bad: true)
        }
    }

    /// POST to the hub (writes are accepted from this Mac); `done` runs on the main queue with the status code (0: no answer).
    func hubPost(_ path: String, _ body: [String: Any], timeout: TimeInterval = 30, _ done: @escaping (Int, [String: Any]) -> Void) {
        guard let url = URL(string: hubBase + path) else { return }
        var req = URLRequest(url: url)
        req.httpMethod = "POST"; req.timeoutInterval = timeout
        req.setValue("application/json", forHTTPHeaderField: "Content-Type")
        req.httpBody = try? JSONSerialization.data(withJSONObject: body)
        URLSession.shared.dataTask(with: req) { data, resp, err in
            let status = (resp as? HTTPURLResponse)?.statusCode ?? 0
            var j = (data.flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] }) ?? [:]
            if status == 0 { j["error"] = err?.localizedDescription ?? "the hub did not answer" }
            DispatchQueue.main.async { done(status, j) }
        }.resume()
    }

    func ask(_ message: String, _ info: String, ok: String) -> Bool {
        if let h = confirmHook { return h(message, info) }
        NSApp.activate(ignoringOtherApps: true)
        let al = NSAlert()
        al.messageText = message; al.informativeText = info
        al.addButton(withTitle: ok); al.addButton(withTitle: "Cancel")
        return al.runModal() == .alertFirstButtonReturn
    }

    /// Say what the last item did: a line at the foot of the details menu for a minute; a failure also gets a dialog (the menu is closed by then).
    func say(_ text: String, bad: Bool = false) {
        actionRow.line = "  " + clip(text, 54); actionRow.tint = bad ? .systemRed : .secondaryLabelColor
        actionItem.isHidden = false
        actionTimer?.invalidate()
        actionTimer = Timer.scheduledTimer(withTimeInterval: 60, repeats: false) { [weak self] _ in self?.actionItem.isHidden = true }
        if menuOpen { redrawRows() }
        if bad {
            if confirmHook != nil { return }
            NSApp.activate(ignoringOtherApps: true)
            let al = NSAlert(); al.alertStyle = .warning; al.messageText = "agents menu"; al.informativeText = text
            al.runModal()
        }
    }

    // MARK: render

    /// One tool's usage as a short bar phrase ("codex 41% 5h · 12% 7d", "kiro 0/50 credits", "opencode 16.8k tok").
    func barToolShort(_ t: ToolInfo) -> String {
        let name = t.label.isEmpty ? t.id : t.label
        if t.offline { return "\(name) offline" }
        if t.loggedIn == false { return "\(name) not logged in" }
        if t.reached == "balance" { return "\(name) no balance" }
        if let c = t.credits {
            let pct = c.limit > 0 ? c.used / c.limit * 100 : 0
            let pctStr = c.limit > 0 ? (pct > 0 && pct < 1 ? String(format: "%.1f%% ", pct) : "\(Int(pct.rounded()))% ") : ""
            let num = { (v: Double) -> String in let r = (v * 100).rounded() / 100; return r == r.rounded() ? String(Int(r)) : String(r) }
            return "\(name) \(pctStr)\(num(c.used))/\(num(c.limit)) credits"
        }
        if !t.windows.isEmpty {
            // "codex 41% 5h · 12% 7d" — percent then label, matching the dock header's sum.
            let bits = t.windows.prefix(2).map { w -> String in
                let p = w.percent.map { "\($0)%" } ?? "—"
                return "\(p) \(w.label)"
            }
            return "\(name) " + bits.joined(separator: " · ")
        }
        if t.id == "cursor", !t.plan.isEmpty { return "\(name) \(t.plan)" }
        return "\(name) —"
    }

    func title(now: Date = Date()) -> NSAttributedString {
        let num = NSFont.monospacedDigitSystemFont(ofSize: 11.5, weight: .medium)
        let plain = NSFont.systemFont(ofSize: 11.5, weight: .regular)
        let dotFont = NSFont.systemFont(ofSize: 10.0, weight: .regular)
        let s = NSMutableAttributedString()
        func add(_ t: String, _ f: NSFont, _ c: NSColor? = nil) {
            var a: [NSAttributedString.Key: Any] = [.font: f]
            if let c = c { a[.foregroundColor] = c }
            s.append(NSAttributedString(string: t, attributes: a))
        }
        if online, !toolFocus.isEmpty {
            // A backup tool is ticked: show its usage in the bar (like ticking a Claude / antigrav account).
            let order = ["codex", "cursor", "kiro", "opencode"] + extraTiles
            var parts: [String] = []
            for id in order where toolFocus.contains(id) {
                if let t = tools.first(where: { $0.id == id }) { parts.append(barToolShort(t)) }
                else { parts.append("\(id) …") }   // /api/models not in yet
            }
            for id in toolFocus.sorted() where !order.contains(id) {
                if let t = tools.first(where: { $0.id == id }) { parts.append(barToolShort(t)) }
                else { parts.append("\(id) …") }
            }
            add(parts.isEmpty ? "…" : parts.joined(separator: " · "), plain)
        } else if online, let f = focus, f.isEmpty {
            // nothing ticked: the bar is just the icon (no usage)
        } else if online {
            if focus != nil {   // a coloured dot per account the numbers cover
                let active = accounts.filter { isOn($0.id) }
                for a in active { add("●", dotFont, a.color) }
                if !active.isEmpty { add(" ", plain) }
            }
            add(overallShort.pct, num, overallShort.percent == nil || overallShort.tint == .labelColor ? nil : overallShort.tint)
            add(" \(overallShort.label.isEmpty ? "5h" : overallShort.label)", plain)
            // Predictive run-out is kept inside the limits dropdown menu, not in the status bar title
            add(" · ", plain)
            add(overallWeek.pct, num, overallWeek.percent == nil || overallWeek.tint == .labelColor ? nil : overallWeek.tint)
            add(" \(overallWeek.label.isEmpty ? "7d" : overallWeek.label)", plain)
            // Odyssеus local models: show ONLY tokens (minimalist: e.g. "6.1M tok")
            if !localTokensOnly.isEmpty {
                add(" · ", plain)
                add(localTokensOnly, num, accent)
            } else if !localUsageLine.isEmpty {
                if let m = localUsageLine.components(separatedBy: ":").last?.trimmingCharacters(in: .whitespaces) {
                    let tok = m.components(separatedBy: " · ").first ?? m
                    add(" · ", plain)
                    add(tok, num, accent)
                }
            } else if !localLine.isEmpty, !localLine.hasPrefix("local models: unavailable"), !localLine.hasPrefix("no local models found") {
                let loaded = localLine.components(separatedBy: " of ").first.map { Int($0.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()) ?? 0 } ?? 0
                if loaded > 0 {
                    add(" · ", plain)
                    add("\(loaded) loaded", num, accent)
                }
            }
        } else {
            add("offline", plain, .secondaryLabelColor)
        }
        return s
    }

    func render() {
        if let b = item.button {
            let badge: NSColor? = counts.error > 0 ? .systemRed : (counts.waiting > 0 ? .systemYellow : (piConnected ? .systemGreen : nil))
            let t = title()
            var tip = counts.total == 0 ? "no agents" :
                "\(counts.total) agents: \(counts.running) running, \(counts.waiting) waiting, \(counts.idle) idle" +
                (counts.error > 0 ? ", \(counts.error) error" : "")
            if !toolFocus.isEmpty {
                tip += "\nshowing tool usage: " + toolFocus.sorted().joined(separator: " + ")
                tip += "\n(untick the tool pill in the dock to show Claude / antigrav overall again)"
            } else if let f = focus, f.isEmpty { tip += "\nusage hidden — no accounts ticked (right-click to tick some)" }
            else {
                if online {
                    var u = "\n\(overallShort.pct) \(overallShort.label.isEmpty ? "5h" : overallShort.label)"
                    if let out = overallShort.runOutIn() { u += " (out in \(out))" }
                    else if (overallShort.percent ?? 0) >= 100 { u += " (limit reached)" }
                    u += " · \(overallWeek.pct) \(overallWeek.label.isEmpty ? "7d" : overallWeek.label)"
                    if let out7 = overallWeek.runOutIn() { u += " (out in \(out7))" }
                    else if (overallWeek.percent ?? 0) >= 100 { u += " (limit reached)" }
                    tip += u
                }
                if let f = focus { tip += "\nshowing: " + accounts.filter { f.contains($0.id) }.map { $0.label }.joined(separator: " + ") }
            }
            if piConnected {
                var piTip = "Pi 5 online"
                if let temp = piTemperatureC { piTip += " · \(Int(temp.rounded()))°C" }
                if let cpu = piCPUPercent { piTip += " · CPU \(Int(cpu.rounded()))%" }
                tip += "\n" + piTip
            } else if piSimulated {
                tip += "\nPi 5 simulator data"
            } else {
                tip += "\nPi 5 not connected" + (piLastSeen == "Never" ? "" : " · last seen \(piLastSeen)")
            }
            tip += "\nclick: deck · right-click: details"
            // Re-setting the image/title makes the status item re-layout; skip it when nothing changed.
            let sig = "\(badge?.description ?? "-")|\(t.string)|\(overallShort.severity ?? "")|\(overallWeek.severity ?? "")|\(tip)"
            if sig != lastBarSig {
                lastBarSig = sig
                b.image = critter(badge: badge)
                b.imagePosition = .imageLeading
                b.attributedTitle = t
                b.toolTip = tip
            }
        }

        header.online = online
        header.busy = refreshing
        header.title = focus == nil ? "OVERALL LIMITS" : (focus!.isEmpty ? "NO ACCOUNTS TICKED" : "FOCUS · " + accounts.filter { isOn($0.id) }.map { $0.label }.joined(separator: " + ").uppercased())
        header.updated = ago(asOf)
        shortRow.win = overallShort
        weekRow.win = overallWeek
        for (i, mi) in acctItems.enumerated() {
            mi.isHidden = i >= accounts.count
            guard i < accounts.count else { continue }
            let a = accounts[i], on = isOn(a.id), checked = isChecked(a.id)
            mi.title = "Focus " + a.label   // for VoiceOver / scripting; the attributed title is what's drawn
            mi.attributedTitle = accountTitle(a, on: on)
            mi.state = checked ? .on : .off   // ✓ = the bar and overall figures focus on this account
            let pred = a.short.runOutIn().map { " · 5h out in \($0)" } ?? ((a.short.percent ?? 0) >= 100 ? " · 5h limit reached" : "")
            mi.toolTip = (a.note.isEmpty ? "" : a.note + "\n") + (checked ? "ticked — its usage is shown\(pred) · click to untick" : "unticked — its usage is hidden · click to tick")
        }
        splitRow.shares = shares
        splitRow.owner = splitOwner
        splitItem.isHidden = shares.isEmpty

        var line = "no agents"
        if counts.total > 0 {
            line = "\(counts.total) agents · \(counts.running) running · \(counts.waiting) waiting · \(counts.idle) idle"
            if counts.error > 0 { line += " · \(counts.error) error" }
        }
        if !hand.isEmpty { line = (counts.total > 0 ? line : "no deck agents") + " · \(hand.count) by hand" }
        agentsRow.line = online ? line : "hub not reachable on :4040 — start it with npm start"
        if piConnected {
            var details = ["ONLINE"]
            if let temp = piTemperatureC { details.append("\(Int(temp.rounded()))°C") }
            if let cpu = piCPUPercent { details.append("CPU \(Int(cpu.rounded()))%") }
            if let rpm = piFanRPM, rpm > 0 { details.append("fan \(rpm) rpm") }
            piStatusItem.title = "Raspberry Pi 5 · " + details.joined(separator: " · ")
            piStatusItem.toolTip = "Click to open Pi vitals"
        } else if piSimulated {
            piStatusItem.title = "Raspberry Pi 5 · simulator data"
            piStatusItem.toolTip = "Simulator data is not a live Pi connection"
        } else {
            piStatusItem.title = "Raspberry Pi 5 · not connected" + (piLastSeen == "Never" ? "" : " · last seen \(piLastSeen)")
            piStatusItem.toolTip = "Click to open the Pi setup guide"
        }
        metricsRow.localLine = localLine
        metricsRow.localUsageLine = localUsageLine
        if menuOpen || selfTesting {
            rebuildAgentMenu()
            renderTools()
            refreshMetrics()
            refreshLocalUsage()
            redrawRows()
        } else if !toolFocus.isEmpty {
            renderTools()
        }
    }
}

// `--write-iconset <dir.iconset>`: the app icon as the PNGs iconutil wants (build.sh turns them into the bundle's .icns).
if let i = CommandLine.arguments.firstIndex(of: "--write-iconset"), i + 1 < CommandLine.arguments.count {
    let dir = URL(fileURLWithPath: CommandLine.arguments[i + 1])
    try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
    for pt in [16, 32, 128, 256, 512] {
        for scale in [1, 2] {
            let px = pt * scale
            guard let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: px, pixelsHigh: px, bitsPerSample: 8, samplesPerPixel: 4,
                                             hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0) else { continue }
            NSGraphicsContext.saveGraphicsState()
            NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
            appIcon(CGFloat(px)).draw(in: NSRect(x: 0, y: 0, width: px, height: px))
            NSGraphicsContext.restoreGraphicsState()
            try? rep.representation(using: .png, properties: [:])?.write(to: dir.appendingPathComponent("icon_\(pt)x\(pt)\(scale == 2 ? "@2x" : "").png"))
        }
    }
    exit(0)
}

// `--overall-vectors <cases.json>`: run the shared spec through overallRule() and print the answers as JSON (no UI, no hub).
if let i = CommandLine.arguments.firstIndex(of: "--overall-vectors"), i + 1 < CommandLine.arguments.count {
    let spec = (try? JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: CommandLine.arguments[i + 1]))) as? [String: Any]) ?? [:]
    var out: [String: Any] = [:]
    for c in (spec["cases"] as? [[String: Any]]) ?? [] {
        let key = (c["key"] as? String) ?? "short"
        let ticked = Set((c["ticked"] as? [String]) ?? [])
        var accts: [Acct] = []
        for a in (c["accounts"] as? [[String: Any]]) ?? [] {
            var x = Acct(); x.id = a["id"] as? String ?? ""; x.label = a["label"] as? String ?? x.id
            x.short = Win(a["short"] as? [String: Any]); x.week = Win(a["week"] as? [String: Any]); accts.append(x)
        }
        let w = overallRule(accts.filter { ticked.contains($0.id) }, pick: { key == "week" ? $0.week : $0.short }, label: key == "week" ? "7d" : "5h")
        var r: [String: Any] = ["of": w.of ?? 0, "total": w.total ?? 0, "state": w.state]
        r["percent"] = w.percent.map { $0 as Any } ?? NSNull()
        r["severity"] = w.severity.map { $0 as Any } ?? NSNull()
        r["resetAccount"] = w.resetAccount.map { $0 as Any } ?? NSNull()
        r["resetsAt"] = w.resetsAt.map { isoFrac.string(from: $0) as Any } ?? NSNull()
        out[(c["name"] as? String) ?? ""] = r
    }
    FileHandle.standardOutput.write((try? JSONSerialization.data(withJSONObject: out)) ?? Data())
    exit(0)
}

// One icon only. The login item (LaunchAgent local.pi5monitor.menu, `--login`) and a copy opened by hand can both start this app; the
// second one asks the first to show its window (unless it is the login item) and quits. Only for a plain launch: the test hooks
// (--selftest, --popover, --focus=… …) must still run next to the installed app.
let plainLaunch = CommandLine.arguments.count == 1 || (CommandLine.arguments.count == 2 && CommandLine.arguments[1] == "--login")
if plainLaunch, let id = Bundle.main.bundleIdentifier,
   NSRunningApplication.runningApplications(withBundleIdentifier: id).contains(where: { $0.processIdentifier != ProcessInfo.processInfo.processIdentifier }) {
    if CommandLine.arguments.count == 1 {
        DistributedNotificationCenter.default().postNotificationName(showWindowNote, object: nil, userInfo: nil, deliverImmediately: true)
    }
    exit(0)
}

let app = NSApplication.shared
app.setActivationPolicy(.accessory)
let delegate = App()
app.delegate = delegate
app.run()
