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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
|
// dingger menu bar: herdr's agent panel as a macOS status item, plus a
// floating always-on-top panel (panel.swift) and agent search (search.swift),
// each on a global shortcut (hotkey.swift). Rows and colors come from
// model.swift.
//
// Reads the pane options the dingger daemon writes and renders herdr's
// Symbols style with herdr's palette:
//
// blocked × red done ✓ teal working ◐ yellow idle ○ green
//
// in herdr's priority order, oldest waiting first. Clicking a row runs
// `dingger focus --pane`, the same tested code path as the tmux status-line
// click.
//
// Debug flags (used by tests/e2e.sh):
// --print print the title and rows the menu would show, then exit
// (rows: "<symbol> <status>\t<title>\t<subtitle>")
// --print-panel [--full] [--toggle]
// print what the floating panel would show, then exit
// --snapshot-panel <png> [--full]
// render the panel offscreen (after a different render, to
// catch stale content) over white and black, then exit
// --print-search <query>
// print what agent search would list for <query>, then exit
// --snapshot-search <png> <query> [<down>]
// render agent search offscreen, then exit
// --click <pane> perform a row click for <pane>, then exit
// --restore [<session>...]
// restore saved tmux sessions as the panel and menu do
// (through the login shell), then exit
// --dismiss-offer dismiss the restore offer as "Not now" does, then exit
// --selftest check the panel and search rules, then exit
import AppKit
func log(_ message: String) {
FileHandle.standardError.write(Data("\(Date()) \(message)\n".utf8))
}
/// Restore saved tmux sessions (all when `sessions` is empty) through the
/// login shell, and log the report. Blocks until done.
@discardableResult
func performRestore(sessions: [String]) -> Bool {
let args = ["restore", "--report"] + sessions.flatMap { ["--session", $0] }
let result = runDinggerInLoginShell(args)
let lines = result.output.split(separator: "\n").filter { !$0.contains("can't change option: zle") }
log("restore: \(result.ok ? "done" : "failed")\n" + lines.map { " \($0)" }.joined(separator: "\n"))
return result.ok
}
final class Menubar: NSObject, NSApplicationDelegate, NSMenuDelegate {
private let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
private let menu = NSMenu()
private var panel: PanelController!
private var searchWindow: SearchController!
private var visibility = Menubar.loadVisibility()
private var settings = Settings()
private var settingsModified: Date?
private var hotkey: Hotkey?
private var hotkeyRegistered = false
private var jumpHotkey: Hotkey?
private var jumpHotkeyRegistered = false
private var searchHotkey: Hotkey?
private var searchHotkeyRegistered = false
private var prefersFull = UserDefaults.standard.bool(forKey: "panelFull")
private var rows: [Row] = []
private var restoreOffer: RestoreOffer?
private var restoring = false
/// The panel settings; the first run after the on/off split migrates the
/// old three-way mode.
private static func loadVisibility() -> PanelVisibility {
let defaults = UserDefaults.standard
guard defaults.object(forKey: "panelEnabled") != nil else {
let migrated = PanelVisibility.migrated(fromMode: defaults.string(forKey: "panelMode") ?? "auto")
defaults.set(migrated.enabled, forKey: "panelEnabled")
defaults.set(migrated.policy.rawValue, forKey: "panelPolicy")
defaults.removeObject(forKey: "panelMode")
return migrated
}
return PanelVisibility(
enabled: defaults.bool(forKey: "panelEnabled"),
policy: PanelPolicy(rawValue: defaults.string(forKey: "panelPolicy") ?? "") ?? .whenWaiting)
}
func applicationDidFinishLaunching(_: Notification) {
menu.delegate = self
item.menu = menu
panel = PanelController(
onClick: { [weak self] paneId in self?.jump(to: paneId) },
onMarkUnread: { [weak self] paneId in self?.markUnread(paneId) },
onToggleFull: { [weak self] in self?.toggleFull() },
onRestore: { [weak self] in self?.restore(sessions: []) },
onDismissRestore: { [weak self] in self?.dismissRestore() })
searchWindow = SearchController(onJump: { [weak self] paneId in self?.jump(to: paneId) },
onMarkUnread: { [weak self] paneId in self?.markUnread(paneId) })
Settings.ensureFile()
reloadSettings()
refresh()
let timer = Timer(timeInterval: 1.0, repeats: true) { [weak self] _ in self?.refresh() }
RunLoop.main.add(timer, forMode: .common)
}
// MARK: settings and shortcut
private func reloadSettings() {
settingsModified = Settings.modified()
settings = Settings.load()
(hotkey, hotkeyRegistered) = registerShortcut(.panel, settings.hotkey, "panel") { [weak self] in
self?.togglePanel()
}
(jumpHotkey, jumpHotkeyRegistered) = registerShortcut(.jump, settings.jumpHotkey, "jump") {
[weak self] in self?.jumpToTopWaiting()
}
(searchHotkey, searchHotkeyRegistered) = registerShortcut(.search, settings.searchHotkey, "search") {
[weak self] in self?.toggleSearch()
}
}
private func registerShortcut(_ id: GlobalHotkey.Id, _ spec: String, _ name: String,
action: @escaping () -> Void) -> (Hotkey?, Bool) {
guard let parsed = Hotkey.parse(spec) else {
GlobalHotkey.unregister(id)
log("settings: invalid \(name) shortcut \"\(spec)\"")
return (nil, false)
}
let registered = GlobalHotkey.register(id, parsed, action: action)
log("settings: \(name) shortcut \(parsed.display) \(registered ? "registered" : "in use by another app")")
return (parsed, registered)
}
// MARK: refresh
private func refresh() {
if Settings.modified() != settingsModified { reloadSettings() }
rows = fetchRows()
item.button?.attributedTitle = title(for: rows)
var tip: [String] = []
for status in [Status.blocked, .done, .working, .idle] {
let count = rows.filter { $0.status == status }.count
if count > 0 { tip.append("\(count) \(status.rawValue)") }
}
let tipText = tip.isEmpty ? "No agents" : tip.joined(separator: " · ")
item.button?.toolTip = tipText
item.button?.setAccessibilityLabel("dingger, " + tipText)
visibility.anyWaiting = rows.contains(where: \.waiting)
restoreOffer = fetchRestoreOffer()
visibility.restoreOffered = restoreOffer != nil
applyPanel()
searchWindow.update(rows: rows)
}
/// The search shortcut and menu item: open agent search, or close it.
@objc private func toggleSearch() {
if searchWindow.isOpen {
searchWindow.close("shortcut")
} else {
rows = fetchRows()
searchWindow.open(rows: rows)
}
}
private var panelContent: PanelContent {
PanelContent(rows: rows,
full: panelShowsFull(policy: visibility.policy, prefersFull: prefersFull),
canToggle: visibility.policy == .always,
offer: restoreOffer, restoring: restoring)
}
private func applyPanel() {
if visibility.visible(at: Date()) {
if panel.render(panelContent) {
let content = panelContent
log("panel: render \(content.rows.filter(\.waiting).count) waiting, \(content.full ? "full" : "compact")")
}
if !panel.isVisible {
panel.show()
log("panel: shown (\(panelState))")
}
} else if panel.isVisible {
panel.hide()
log("panel: hidden (\(panelState))")
}
}
private var panelState: String {
"\(visibility.enabled ? "on" : "off"), \(visibility.policy.rawValue), "
+ (visibility.anyWaiting ? "agents waiting" : "nothing waiting")
+ (visibility.restoreOffered ? ", restore offered" : "")
}
/// The shortcut and the menu item: turn the panel on or off, persistently.
@objc private func togglePanel() {
visibility.toggle(at: Date())
UserDefaults.standard.set(visibility.enabled, forKey: "panelEnabled")
log("panel: turned \(visibility.enabled ? "on" : "off")")
applyPanel()
}
private func toggleFull() {
prefersFull.toggle()
UserDefaults.standard.set(prefersFull, forKey: "panelFull")
applyPanel()
}
/// The jump shortcut: same as clicking the tmux status line.
@objc private func jumpToTopWaiting() {
DispatchQueue.global().async {
let result = runReporting(dinggerBinary, ["focus"])
log("jump: dingger focus \(result.ok ? "ok" : "failed: \(result.output)")")
DispatchQueue.main.async { self.refresh() }
}
}
/// Restore saved tmux sessions (all when `sessions` is empty).
func restore(sessions: [String], completion: (() -> Void)? = nil) {
guard !restoring else { return }
restoring = true
applyPanel()
log("restore: \(sessions.isEmpty ? "all sessions" : sessions.joined(separator: ", "))")
DispatchQueue.global().async {
performRestore(sessions: sessions)
DispatchQueue.main.async {
self.restoring = false
self.refresh()
completion?()
}
}
}
/// "Not now": stop offering this saved layout.
@objc private func dismissRestore() {
let result = runReporting(dinggerBinary, ["restore", "--dismiss"])
log("restore: dismissed (\(result.ok ? "ok" : result.output))")
refresh()
}
@objc private func restoreFromMenu(_ sender: NSMenuItem) {
restore(sessions: (sender.representedObject as? String).map { [$0] } ?? [])
}
@objc private func selectPolicy(_ sender: NSMenuItem) {
guard let raw = sender.representedObject as? String, let policy = PanelPolicy(rawValue: raw) else { return }
visibility.policy = policy
UserDefaults.standard.set(policy.rawValue, forKey: "panelPolicy")
applyPanel()
}
@objc private func openSettings() {
Settings.ensureFile()
_ = run("/usr/bin/open", ["-t", Settings.path])
}
private func jump(to paneId: String) {
log("jump: to \(paneId)")
DispatchQueue.global().async {
focus(paneId)
DispatchQueue.main.async { self.refresh() }
}
}
private func markUnread(_ paneId: String) {
log("unread: \(paneId)")
DispatchQueue.global().async {
markAgentUnread(paneId)
DispatchQueue.main.async { self.refresh() }
}
}
// MARK: menu (rebuilt from fresh data every time it opens)
func menuNeedsUpdate(_ menu: NSMenu) {
menu.removeAllItems()
rows = fetchRows()
restoreOffer = fetchRestoreOffer()
if let offer = restoreOffer {
let item = NSMenuItem(title: restoring ? "Restoring tmux Sessions…" : "↺ \(offer.title)",
action: nil, keyEquivalent: "")
if !restoring {
let submenu = NSMenu()
let all = NSMenuItem(title: "Restore All", action: #selector(restoreFromMenu(_:)), keyEquivalent: "")
all.target = self
submenu.addItem(all)
submenu.addItem(.separator())
for session in offer.sessions {
var detail = "\(session.windows) \(session.windows == 1 ? "window" : "windows")"
if session.agents > 0 { detail += ", \(session.agents) \(session.agents == 1 ? "agent" : "agents")" }
let one = NSMenuItem(title: session.name, action: #selector(restoreFromMenu(_:)), keyEquivalent: "")
one.subtitle = detail
one.target = self
one.representedObject = session.name
submenu.addItem(one)
}
submenu.addItem(.separator())
let later = NSMenuItem(title: "Not Now", action: #selector(dismissRestore), keyEquivalent: "")
later.target = self
submenu.addItem(later)
item.submenu = submenu
} else {
item.isEnabled = false
}
item.subtitle = offer.detail
menu.addItem(item)
menu.addItem(.separator())
}
if rows.isEmpty {
let none = NSMenuItem(title: "No agents", action: nil, keyEquivalent: "")
none.isEnabled = false
menu.addItem(none)
}
for (index, row) in rows.enumerated() {
// One separator between the agents waiting for you and the rest.
if index > 0, rows[index - 1].waiting, !row.waiting {
menu.addItem(.separator())
}
let entry = NSMenuItem(title: row.label, action: #selector(rowClicked(_:)), keyEquivalent: "")
entry.target = self
entry.attributedTitle = rowTitle(row)
entry.subtitle = row.subtitle
entry.toolTip = row.name.isEmpty ? nil : row.name
entry.representedObject = row.paneId
menu.addItem(entry)
}
menu.addItem(.separator())
let toggle = NSMenuItem(title: "Show Panel", action: #selector(togglePanel), keyEquivalent: "")
toggle.target = self
toggle.state = visibility.enabled ? .on : .off
if let hotkey, hotkeyRegistered {
toggle.keyEquivalent = hotkey.key.count == 1 ? hotkey.key : ""
toggle.keyEquivalentModifierMask = hotkey.modifierFlags
}
menu.addItem(toggle)
let jumpItem = NSMenuItem(title: "Jump to Waiting Agent", action: #selector(jumpToTopWaiting),
keyEquivalent: "")
jumpItem.target = self
jumpItem.isEnabled = rows.contains(where: \.waiting)
if let jumpHotkey, jumpHotkeyRegistered {
jumpItem.keyEquivalent = jumpHotkey.key.count == 1 ? jumpHotkey.key : ""
jumpItem.keyEquivalentModifierMask = jumpHotkey.modifierFlags
}
menu.addItem(jumpItem)
let searchItem = NSMenuItem(title: "Search Agents…", action: #selector(toggleSearch), keyEquivalent: "")
searchItem.target = self
searchItem.isEnabled = !rows.isEmpty
if let searchHotkey, searchHotkeyRegistered {
searchItem.keyEquivalent = searchHotkey.key.count == 1 ? searchHotkey.key : ""
searchItem.keyEquivalentModifierMask = searchHotkey.modifierFlags
}
menu.addItem(searchItem)
let policyMenu = NSMenu()
for policy in PanelPolicy.allCases {
let option = NSMenuItem(title: policy.label, action: #selector(selectPolicy(_:)), keyEquivalent: "")
option.target = self
option.representedObject = policy.rawValue
option.state = visibility.policy == policy ? .on : .off
policyMenu.addItem(option)
}
let policyItem = NSMenuItem(title: "Panel Shows", action: nil, keyEquivalent: "")
policyItem.submenu = policyMenu
menu.addItem(policyItem)
for (shortcut, registered, spec) in [(hotkey, hotkeyRegistered, settings.hotkey),
(jumpHotkey, jumpHotkeyRegistered, settings.jumpHotkey),
(searchHotkey, searchHotkeyRegistered, settings.searchHotkey)] {
guard !registered else { continue }
let problem = shortcut.map { "Shortcut \($0.display) is used by another app" }
?? "Shortcut \"\(spec)\" is not valid"
let item = NSMenuItem(title: problem, action: nil, keyEquivalent: "")
item.isEnabled = false
menu.addItem(item)
}
let settingsItem = NSMenuItem(title: "Settings…", action: #selector(openSettings), keyEquivalent: ",")
settingsItem.target = self
menu.addItem(settingsItem)
menu.addItem(.separator())
menu.addItem(NSMenuItem(title: "Quit dingger", action: #selector(NSApplication.terminate(_:)),
keyEquivalent: "q"))
}
@objc private func rowClicked(_ sender: NSMenuItem) {
guard let paneId = sender.representedObject as? String else { return }
jump(to: paneId)
}
}
let arguments = CommandLine.arguments
if arguments.contains("--selftest") {
var failures = panelSelftest() + searchSelftest()
if Hotkey.parse("ctrl+opt+cmd+e")?.display != "⌃⌥⌘E" { failures.append("hotkey: parse ctrl+opt+cmd+e") }
if Hotkey.parse("e") != nil { failures.append("hotkey: a key without modifiers is rejected") }
if Hotkey.parse("ctrl+opt+bogus") != nil { failures.append("hotkey: unknown keys are rejected") }
if Hotkey.parse("cmd+shift+f12")?.display != "⇧⌘F12" { failures.append("hotkey: parse cmd+shift+f12") }
if Hotkey.parse(Settings().jumpHotkey)?.display != "⌃⌥⌘U" { failures.append("hotkey: default jump is ⌃⌥⌘U") }
if Hotkey.parse(Settings().searchHotkey)?.display != "⌃⌥⇧⌘U" { failures.append("hotkey: default search is ⌃⌥⇧⌘U") }
let order: [(String, Status, Int)] = [
("idle old", .idle, 10), ("done new", .done, 90), ("idle unknown", .idle, Int.max),
("working old", .working, 20), ("idle new", .idle, 80), ("done old", .done, 30),
("blocked", .blocked, 99), ("working new", .working, 70),
]
let listed = order.map { Row(paneId: $0.0, agent: "pi", name: $0.0, status: $0.1, session: "s", window: "w",
since: $0.2, path: "~") }.sorted(by: listedBefore).map(\.name)
let expected = ["blocked", "done old", "done new", "working new", "working old", "idle new", "idle old", "idle unknown"]
if listed != expected { failures.append("order: waiting oldest first, the rest most recent first: \(listed)") }
let byImportance: [(String, Status, Importance, Int)] = [
("done old", .done, .normal, 10), ("done new high", .done, .high, 90), ("done older low", .done, .low, 5),
("blocked low", .blocked, .low, 99), ("working high", .working, .high, 1), ("working new", .working, .normal, 80),
]
let importanceListed = byImportance.map { Row(paneId: $0.0, agent: "pi", name: $0.0, status: $0.1, session: "s",
window: "w", since: $0.3, path: "~", importance: $0.2) }
.sorted(by: listedBefore).map(\.name)
let importanceExpected = ["blocked low", "done new high", "done old", "done older low", "working high", "working new"]
if importanceListed != importanceExpected {
failures.append("order: status first, then importance, then time: \(importanceListed)")
}
if isDrag(from: .zero, to: NSPoint(x: 2, y: 3)) { failures.append("click: a few points of jitter is a click") }
if !isDrag(from: .zero, to: NSPoint(x: 0, y: 5)) { failures.append("click: moving 5 points is a drag") }
let high = Row(paneId: "%1", agent: "pi", name: "Fix it", status: .done, session: "s", window: "w", since: 1, importance: .high)
if rowTitle(high).string != "✓ ! Fix it" || rowTitlePrefix(high) != "✓ ! " {
failures.append("title: a high agent is marked: \(rowTitle(high).string)")
}
let markColor = rowTitle(high).attribute(.foregroundColor, at: rowTitlePrefix(high).utf16.count - 2,
effectiveRange: nil) as? NSColor
if markColor != herdrPeach { failures.append("title: the ! is peach") }
let normal = Row(paneId: "%2", agent: "pi", name: "Fix it", status: .done, session: "s", window: "w", since: 1)
if rowTitle(normal).string != "✓ Fix it" || rowTitlePrefix(normal).count != rowTitlePrefix(high).count {
failures.append("title: names line up with or without the mark: '\(rowTitle(normal).string)'")
}
let low = Row(paneId: "%3", agent: "pi", name: "Fix it", status: .done, session: "s", window: "w", since: 1,
importance: .low)
let lowColor = rowTitle(low).attribute(.foregroundColor, at: rowTitlePrefix(low).utf16.count,
effectiveRange: nil) as? NSColor
if lowColor?.alphaComponent != lowImportanceAlpha { failures.append("title: a low agent's name is dimmed") }
failures.forEach { print("FAIL \($0)") }
print(failures.isEmpty ? "selftest ok" : "selftest: \(failures.count) failed")
exit(failures.isEmpty ? 0 : 1)
}
if arguments.contains("--print") {
let rows = fetchRows()
print("title: \(plainTitle(for: rows))")
for row in rows {
print("\(row.status.symbol) \(row.status.rawValue)\t\(row.markedLabel)\t\(row.subtitle)")
}
exit(0)
}
if arguments.contains("--print-panel") {
let full = arguments.contains("--full")
print(PanelContent(rows: fetchRows(), full: full, canToggle: full || arguments.contains("--toggle"),
offer: fetchRestoreOffer()).plainText)
exit(0)
}
if let index = arguments.firstIndex(of: "--restore") {
exit(performRestore(sessions: Array(arguments[(index + 1)...])) ? 0 : 1)
}
if arguments.contains("--dismiss-offer") {
let result = runReporting(dinggerBinary, ["restore", "--dismiss"])
print(result.output)
exit(result.ok ? 0 : 1)
}
if let index = arguments.firstIndex(of: "--snapshot-panel"), index + 1 < arguments.count {
_ = NSApplication.shared
let controller = PanelController(persistFrame: false, onClick: { _ in }, onToggleFull: {})
// First render something else, so stale views would show in the image.
controller.render(PanelContent(rows: [Row(
paneId: "%stale", agent: "pi", name: "STALE ROW FROM A PREVIOUS RENDER", status: .blocked,
session: "old", window: "old", since: 0)]))
let full = arguments.contains("--full")
controller.render(PanelContent(rows: fetchRows(), full: full, canToggle: full, offer: fetchRestoreOffer()))
exit(controller.snapshot(to: arguments[index + 1]) ? 0 : 1)
}
if let index = arguments.firstIndex(of: "--print-search") {
var state = SearchState(rows: fetchRows())
state.setQuery(index + 1 < arguments.count ? arguments[index + 1] : "")
print(state.plainText)
exit(0)
}
if let index = arguments.firstIndex(of: "--snapshot-search"), index + 2 < arguments.count {
_ = NSApplication.shared
let controller = SearchController(onJump: { _ in })
let down = index + 3 < arguments.count ? Int(arguments[index + 3]) ?? 0 : 0
exit(controller.snapshot(rows: fetchRows(), query: arguments[index + 2], down: down,
to: arguments[index + 1]) ? 0 : 1)
}
if let index = arguments.firstIndex(of: "--click"), index + 1 < arguments.count {
focus(arguments[index + 1])
exit(0)
}
let app = NSApplication.shared
let delegate = Menubar()
app.delegate = delegate
app.setActivationPolicy(.accessory)
app.run()
|