aboutsummaryrefslogtreecommitdiff
path: root/menubar/main.swift
blob: d0a3b301e1f9ccf79c8d828fa2141b2dc1d21f32 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// dingger menu bar: live agent states from tmux pane user options
// (@agent / @agent_state), written by the dingger daemon.
//
// Visual language is herdr's agent panel, verbatim: five statuses
// (working ◐ yellow, blocked × red, done ✓ teal, idle ○ green,
// unknown · gray), priority order blocked > done > working > idle,
// and the number in the title is herdr's actionable set (done + blocked).

import AppKit

struct PaneRow {
    let paneId: String
    let target: String
    let agent: String
    let state: String
}

let red = NSColor.systemRed
let yellow = NSColor.systemYellow
let teal = NSColor.systemTeal
let green = NSColor.systemGreen
let gray = NSColor.systemGray

/// Tint a symbol image (non-template, so it keeps its color in menus).
func tinted(_ image: NSImage?, _ color: NSColor) -> NSImage? {
    guard let image = image else { return nil }
    let img = NSImage(size: image.size, flipped: false) { rect in
        image.draw(in: rect)
        color.set()
        rect.fill(using: .sourceAtop)
        return true
    }
    img.isTemplate = false
    return img
}

func symbol(_ name: String, _ color: NSColor? = nil) -> NSImage? {
    let image = NSImage(systemSymbolName: name, accessibilityDescription: nil)?
        .withSymbolConfiguration(.init(pointSize: 13, weight: .regular))
    return color.map { tinted(image, $0) } ?? image
}

/// Herdr's status_color + Symbols style, as SF Symbols.
func statusSymbol(_ status: String) -> NSImage? {
    switch status {
    case "working": return symbol("circle.dotted", yellow)
    case "blocked": return symbol("exclamationmark.circle.fill", red)
    case "done": return symbol("checkmark.circle.fill", teal)
    case "idle": return symbol("checkmark.circle", green)
    default: return symbol("questionmark.circle", gray)
    }
}

func statusPriority(_ status: String) -> Int {
    switch status {
    case "blocked": return 4
    case "done": return 3
    case "working": return 2
    case "idle": return 1
    default: return 0
    }
}

final class Menubar: NSObject, NSApplicationDelegate, NSMenuDelegate {
    private let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
    private let menu = NSMenu()
    private var panes: [PaneRow] = []
    private var queue: [String] = [] // pane ids, oldest waiting first

    func applicationDidFinishLaunching(_: Notification) {
        NSApp.setActivationPolicy(.accessory) // no Dock icon
        item.button?.image = symbol("bell", gray)
        item.button?.font = NSFont.monospacedDigitSystemFont(ofSize: 13, weight: .regular)
        item.menu = menu
        menu.delegate = self
        let timer = Timer(timeInterval: 2.0, repeats: true) { [weak self] _ in
            self?.refreshTitle()
        }
        RunLoop.main.add(timer, forMode: .common)
        refreshTitle()
    }

    // MARK: data

    private func runTmux(_ args: [String]) -> String? {
        let process = Process()
        process.executableURL = URL(fileURLWithPath: "/opt/homebrew/bin/tmux")
        process.arguments = args
        let pipe = Pipe()
        process.standardOutput = pipe
        process.standardError = FileHandle.nullDevice
        do {
            try process.run()
        } catch {
            return nil
        }
        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        process.waitUntilExit()
        guard process.terminationStatus == 0 else { return nil }
        return String(data: data, encoding: .utf8)
    }

    private func fetchPanes() -> [PaneRow] {
        let fmt = "#{pane_id}\t#{@agent}\t#{@agent_state}\t#{@dingger_ack}\t#{session_name}:#{window_name}\t#{window_panes}\t#{pane_index}"
        guard let out = runTmux(["-u", "list-panes", "-a", "-F", fmt]) else { return [] }
        return out.split(separator: "\n").compactMap { line in
            let fields = line.split(separator: "\t", omittingEmptySubsequences: false)
            guard fields.count >= 7 else { return nil }
            let agent = String(fields[1])
            let state = fields[2].isEmpty ? "unknown" : String(fields[2])
            guard !agent.isEmpty, ["working", "blocked", "done", "idle"].contains(state) else {
                return nil
            }
            // fields[4] is already `session:window-name`; add the pane index
            // only when the window is split.
            var target = String(fields[4])
            if Int(fields[5]) ?? 1 > 1 {
                target += ".\(fields[6])"
            }
            return PaneRow(paneId: String(fields[0]), target: target, agent: agent, state: state)
        }
    }

    private func fetchQueue() -> [String] {
        guard let out = runTmux(["-u", "show-option", "-gv", "@dingger_queue"]) else { return [] }
        return out.trimmingCharacters(in: .whitespacesAndNewlines)
            .split(separator: ",").map { $0.split(separator: ":").first.map(String.init) ?? "" }
    }

    private func orderedPanes() -> [PaneRow] {
        // herdr's priority: blocked > done > working > idle; FIFO within the
        // queue (oldest waiting first), target order for the rest.
        let priority = { (row: PaneRow) -> Int in statusPriority(row.state) }
        var rows = panes
        rows.sort {
            let (pa, pb) = (priority($0), priority($1))
            if pa != pb { return pa > pb }
            let (qa, qb) = (queue.firstIndex(of: $0.paneId), queue.firstIndex(of: $1.paneId))
            if let qa, let qb { return qa < qb }
            if qa != nil { return true }
            if qb != nil { return false }
            return $0.target < $1.target
        }
        return rows
    }

    // MARK: title (timer-driven; never touches the open menu)

    private func refreshTitle() {
        panes = fetchPanes()
        queue = fetchQueue()
        FileHandle.standardError.write(Data(
            "\(Date()) menubar: panes=\(panes.count) queue=\(queue.count)\n".utf8))
        redrawTitle()
    }

    private func redrawTitle() {
        let blocked = panes.filter { $0.state == "blocked" }.count
        let done = panes.filter { $0.state == "done" }.count
        let working = panes.filter { $0.state == "working" }.count

        let (image, count): (NSImage?, String)
        if blocked > 0 {
            (image, count) = (symbol("bell.fill", red), String(blocked))
        } else if done > 0 {
            (image, count) = (symbol("bell.fill", teal), String(done))
        } else if working > 0 {
            (image, count) = (symbol("bell", yellow), "")
        } else {
            (image, count) = (symbol("bell", gray), "")
        }
        item.button?.image = image
        item.button?.title = count

        var tip: [String] = []
        if blocked > 0 { tip.append("\(blocked) blocked") }
        if done > 0 { tip.append("\(done) done") }
        if working > 0 { tip.append("\(working) working") }
        let tipText = tip.isEmpty ? "No agents" : tip.joined(separator: " · ")
        item.button?.toolTip = tipText
        item.button?.setAccessibilityLabel("dingger, " + tipText)
    }

    // MARK: menu (rebuilt when opened, so rows don't reshuffle under the cursor)

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

    private func rebuildMenu() {
        menu.removeAllItems()

        let rows = orderedPanes()
        if rows.isEmpty {
            let none = NSMenuItem(title: "No agents", action: nil, keyEquivalent: "")
            none.isEnabled = false
            menu.addItem(none)
        }

        var previousPriority: Int?
        for pane in rows {
            let priority = statusPriority(pane.state)
            if let previous = previousPriority, previous != priority {
                menu.addItem(.separator())
            }
            previousPriority = priority

            let row = NSMenuItem(title: "\(pane.agent)\t\(pane.target)",
                                 action: #selector(paneClicked(_:)), keyEquivalent: "")
            row.target = self
            row.image = statusSymbol(pane.state)
            row.attributedTitle = attributedRow(agent: pane.agent, target: pane.target)
            row.toolTip = "\(pane.state) — \(pane.target)"
            row.representedObject = pane.paneId
            menu.addItem(row)
        }

        menu.addItem(.separator())
        let quit = NSMenuItem(title: "Quit dingger", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
        menu.addItem(quit)
    }

    /// Agent left, tmux target right-aligned at a computed tab stop — like a
    /// native menu's key-equivalent column.
    private func attributedRow(agent: String, target: String) -> NSAttributedString {
        let menuFont = NSFont.menuFont(ofSize: 0)
        let monoFont = NSFont.monospacedSystemFont(
            ofSize: menuFont.pointSize - 1, weight: .regular)
        let agentWidth = (agent as NSString).size(withAttributes: [.font: menuFont]).width
        let targetWidth = (target as NSString).size(withAttributes: [.font: monoFont]).width
        let tabStop = ceil(agentWidth + 40 + targetWidth)

        let paragraph = NSMutableParagraphStyle()
        paragraph.tabStops = [NSTextTab(textAlignment: .right, location: tabStop)]

        let text = NSMutableAttributedString()
        text.append(NSAttributedString(
            string: agent,
            attributes: [.font: menuFont, .paragraphStyle: paragraph]))
        text.append(NSAttributedString(string: "\t"))
        text.append(NSAttributedString(
            string: target,
            attributes: [.font: monoFont, .paragraphStyle: paragraph]))
        return text
    }

    // MARK: actions

    func printPanesForDebug() {
        panes = fetchPanes()
        queue = fetchQueue()
        let rows = orderedPanes()
        if rows.isEmpty { print("(no agents)") }
        for pane in rows {
            print("\(pane.state)  \(pane.agent)  \(pane.target)")
        }
    }

    @objc private func paneClicked(_ sender: NSMenuItem) {
        guard let paneId = sender.representedObject as? String else { return }
        // Ack like `dingger focus` does, so both counts drop together.
        _ = runTmux(["-u", "set-option", "-p", "-t", paneId, "@dingger_ack", "1"])
        let target = panes.first { $0.paneId == paneId }?.target ?? ""
        guard !target.isEmpty else { return }
        _ = runTmux(["-u", "switch-client", "-t", target])
        for bundle in ["com.mitchellh.ghostty", "org.alacritty", "com.apple.Terminal"] {
            if let app = NSRunningApplication.runningApplications(withBundleIdentifier: bundle).first {
                app.activate()
                break
            }
        }
    }
}

let app = NSApplication.shared
let delegate = Menubar()
app.delegate = delegate
app.setActivationPolicy(.accessory)

// Debug: print the rows the menu would show and exit.
if CommandLine.arguments.contains("--print") {
    delegate.printPanesForDebug()
    exit(0)
}

app.run()