@join-pantheon/cli 0.35.0 → 0.35.1-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/agent-outage.js +156 -36
  2. package/dist/agent-token.js +5 -3
  3. package/dist/approvals-list.js +87 -0
  4. package/dist/board.js +472 -87
  5. package/dist/brief.js +17 -0
  6. package/dist/cli.js +687 -95
  7. package/dist/client.js +159 -19
  8. package/dist/config.js +3 -2
  9. package/dist/continued.js +56 -1
  10. package/dist/decision-ui.js +5 -3
  11. package/dist/doctor.js +81 -15
  12. package/dist/file-lock.js +39 -4
  13. package/dist/flow-stats.js +18 -1
  14. package/dist/home-guard.js +317 -54
  15. package/dist/home-safety.js +2 -0
  16. package/dist/hud-queue.js +91 -0
  17. package/dist/install.js +15 -1
  18. package/dist/mcp-instructions.js +55 -20
  19. package/dist/mcp.js +114 -24
  20. package/dist/notice-linux.js +15 -4
  21. package/dist/notice-windows.js +2 -2
  22. package/dist/notifier.js +2 -1
  23. package/dist/notify.js +8 -4
  24. package/dist/open-in.js +4 -3
  25. package/dist/pickup.js +17 -0
  26. package/dist/plain.js +139 -3
  27. package/dist/profile.js +12 -8
  28. package/dist/protocol.js +1 -1
  29. package/dist/question-goal.js +74 -0
  30. package/dist/readiness-alert.js +24 -3
  31. package/dist/refusal.js +2 -2
  32. package/dist/relay.js +142 -28
  33. package/dist/removed.js +4 -4
  34. package/dist/run-control.js +4 -3
  35. package/dist/run-failure.js +67 -10
  36. package/dist/setup-changes.js +7 -6
  37. package/dist/signed-out.js +144 -21
  38. package/dist/spend.js +2 -2
  39. package/dist/tray.js +24 -6
  40. package/dist/update-check.js +2 -1
  41. package/dist/uri-handler.js +10 -2
  42. package/dist/which.js +2 -0
  43. package/dist/worker-policy.js +212 -10
  44. package/dist/worker.js +847 -114
  45. package/dist/worklist.js +31 -1
  46. package/helper/macos/main.swift +42 -3
  47. package/helper/macos/menubar.swift +482 -87
  48. package/helper/macos/prebuilt/manifest.json +5 -5
  49. package/helper/macos/prebuilt/pantheon-hud +0 -0
  50. package/helper/macos/prebuilt/pantheon-tray +0 -0
  51. package/package.json +1 -1
@@ -194,6 +194,11 @@ struct Item {
194
194
  /// Run a command with a hard timeout. The menu bar must never beachball
195
195
  /// because a laptop's relay is asleep — tray-status has its own network
196
196
  /// timeouts, this bounds the whole process as the backstop.
197
+ /// How long a panel waits for `explain --queued` to say how an action went: longer than the CLI's own
198
+ /// deadline plus Node's start (hud-queue.ts QUEUED_SEND_DEADLINE_MS 40 s, QUEUED_SURFACE_WAIT_MS 55 s),
199
+ /// so its verdict — "unconfirmed" included — is always heard (0.35.1 review, item 6).
200
+ let QUEUED_WAIT_S: Double = 55
201
+
197
202
  func run(_ launchPath: String, _ args: [String], timeout: Double = 10) -> (out: String, code: Int32)? {
198
203
  let p = Process()
199
204
  p.executableURL = URL(fileURLWithPath: launchPath)
@@ -958,6 +963,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
958
963
 
959
964
  func applicationDidFinishLaunching(_ note: Notification) {
960
965
  NSApp.setActivationPolicy(.accessory)
966
+ loadDrafts()
961
967
  item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
962
968
  // (After the item exists: the board reads its button for placement.)
963
969
  if let out = renderTo { renderBoard(to: out); exit(0) }
@@ -996,6 +1002,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
996
1002
  missedChecks = next.reachable ? 0 : missedChecks + 1
997
1003
  state = next
998
1004
  hasLoaded = true
1005
+ followMoved()
999
1006
  paint()
1000
1007
  if !menuOpen, let menu = item.menu { menuNeedsUpdate(menu) }
1001
1008
  // The board redraws only when what it shows has changed, so a poll never
@@ -1430,6 +1437,27 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
1430
1437
  info(error)
1431
1438
  }
1432
1439
 
1440
+ // Words typed on things that have left the menu: to copy, or discard (round four).
1441
+ let unsent = unsentDrafts()
1442
+ if !unsent.isEmpty {
1443
+ let top = NSMenuItem(title: "Not sent (\(unsent.count))", action: nil, keyEquivalent: "")
1444
+ let list = NSMenu()
1445
+ for u in unsent {
1446
+ let snippet = u.text.replacingOccurrences(of: "\n", with: " ")
1447
+ let row = NSMenuItem(title: "\(u.name.prefix(60)) — \(snippet.prefix(60))\(snippet.count > 60 ? "…" : "")", action: nil, keyEquivalent: "")
1448
+ let actions = NSMenu()
1449
+ let copy = makeItem("Copy the words", #selector(copyUnsent(_:)))
1450
+ copy.representedObject = u.key
1451
+ let discard = makeItem("Discard", #selector(discardUnsent(_:)))
1452
+ discard.representedObject = u.key
1453
+ actions.addItem(copy)
1454
+ actions.addItem(discard)
1455
+ row.submenu = actions
1456
+ list.addItem(row)
1457
+ }
1458
+ top.submenu = list
1459
+ menu.addItem(top)
1460
+ }
1433
1461
  let details = NSMenuItem(title: "Diagnostics", action: nil, keyEquivalent: "")
1434
1462
  let submenu = NSMenu()
1435
1463
  for text in ["Version \(state.version)", "Alerts: \(state.notifierRunning ? "running" : "off")", "Wake hook: \(state.hookOn ? "installed" : "off")"] {
@@ -1480,15 +1508,170 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
1480
1508
  private var panelRetract: NSButton? // the undo, for a minute after a send
1481
1509
  // Per decision (#79): a send that finishes after the person opened another decision never
1482
1510
  // writes into that one — its box, its "Answered", its Retract — and unsent words survive closing.
1483
- private var panelDrafts: [String: (text: String, kind: String)] = [:] // the words, and the kind of reply chosen for them
1511
+ private var panelDrafts: [String: (text: String, kind: String)] = [:] { // the words, and the kind of reply chosen for them
1512
+ didSet {
1513
+ // When each draft last changed, so the oldest go first past the limit (round four).
1514
+ let now = Date().timeIntervalSince1970
1515
+ for (k, v) in panelDrafts where oldValue[k]?.text != v.text { panelDraftAt[k] = now }
1516
+ for k in panelDraftAt.keys where panelDrafts[k] == nil { panelDraftAt.removeValue(forKey: k); panelDraftName.removeValue(forKey: k) }
1517
+ if !loadingDrafts { persistDrafts() }
1518
+ }
1519
+ }
1520
+ private var panelDraftAt: [String: Double] = [:]
1521
+ /// What each draft was typed on, for the "Not sent" list once it has left the menu (round four).
1522
+ private var panelDraftName: [String: String] = [:]
1523
+ private let draftsKept = 200
1524
+ // Kept in bin/.panel-drafts.json, owner-only, so a relaunch (a self-upgrade restarts this helper)
1525
+ // never loses words typed and not sent (round three of the 0.35.1 review, F9).
1526
+ private var loadingDrafts = false
1527
+ /// Drafts read back at launch, not typed in this run: said so when their panel opens.
1528
+ private var restoredDrafts: Set<String> = []
1529
+ private func draftsFile() -> URL { URL(fileURLWithPath: binDir()).appendingPathComponent(".panel-drafts.json") }
1530
+ private func persistDrafts() {
1531
+ // The newest first, and no more than draftsKept: past the limit the oldest go, never a random few.
1532
+ let rows = panelDrafts.filter { !$0.value.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
1533
+ .sorted { (panelDraftAt[$0.key] ?? 0) > (panelDraftAt[$1.key] ?? 0) }
1534
+ .prefix(draftsKept)
1535
+ .map { ["key": $0.key, "text": $0.value.text, "kind": $0.value.kind, "name": panelDraftName[$0.key] ?? "", "at": panelDraftAt[$0.key] ?? 0] as [String: Any] }
1536
+ let f = draftsFile()
1537
+ if rows.isEmpty { try? FileManager.default.removeItem(at: f); return }
1538
+ guard let data = try? JSONSerialization.data(withJSONObject: rows) else { return }
1539
+ if (try? data.write(to: f, options: .atomic)) != nil { try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: f.path) }
1540
+ }
1541
+ private func loadDrafts() {
1542
+ guard let data = try? Data(contentsOf: draftsFile()),
1543
+ let rows = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else { return }
1544
+ loadingDrafts = true
1545
+ defer { loadingDrafts = false }
1546
+ // The newest first: past the limit the oldest are the ones left behind (round four).
1547
+ let newest = rows.sorted { (($0["at"] as? Double) ?? 0) > (($1["at"] as? Double) ?? 0) }
1548
+ for r in newest.prefix(draftsKept) {
1549
+ guard let k = r["key"] as? String, k.count <= 200, let t = r["text"] as? String, t.count <= 20_000,
1550
+ !t.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { continue }
1551
+ // Read back from disk: what a woken run could have written there. Never offered as an Answer —
1552
+ // shown as restored text, as a Note, to check before sending (round four).
1553
+ panelDrafts[k] = (text: t, kind: "Note")
1554
+ if let n = r["name"] as? String, !n.isEmpty { panelDraftName[k] = String(n.prefix(200)) }
1555
+ if let at = r["at"] as? Double { panelDraftAt[k] = at }
1556
+ restoredDrafts.insert(k)
1557
+ }
1558
+ }
1484
1559
  private var panelSent: [String: (act: String, space: String, until: Date)] = [:]
1560
+ // A send in flight belongs to its decision (#105): Send stays off for that one, also when its panel
1561
+ // is closed and opened again, so the same words never go twice. Other decisions can still be answered.
1562
+ private var panelInFlight: Set<String> = []
1563
+ // Decisions settled by a button while another panel was open, with words typed on them: each opens,
1564
+ // with its words and what happened, once the panel the person is on is closed (round three, F8).
1565
+ private var panelUnsentQueue: [Item] = []
1566
+ private var panelOpening = false
1567
+ /// Whether the person opened the panel showing now (a panel that opened by itself never takes the keyboard).
1568
+ private var panelByPerson = true
1569
+ // Decisions answered from here: a second Send as an Answer would be refused (ALREADY_ANSWERED); the rest goes as a Note (F10).
1570
+ private var panelAnsweredHere: Set<String> = []
1571
+ // Was every edit to the box since a send just typing at its end (round two, item 2a)? Only then are the
1572
+ // sent words taken off the front of what is there when it lands; otherwise it is kept whole.
1573
+ private var panelAppendOnly: [String: Bool] = [:]
1574
+ // Words just sent, still at the front of the box: a Send of them again asks once first.
1575
+ private var panelResendGuard: [String: String] = [:]
1576
+ private var panelResendAsked: Set<String> = []
1577
+ fileprivate func noteEdit(_ textView: NSTextView, _ range: NSRange) {
1578
+ guard textView === panelReply, let i = panelItem else { return }
1579
+ let k = panelKey(i)
1580
+ guard panelAppendOnly[k] != nil else { return }
1581
+ let length = (textView.string as NSString).length
1582
+ if !(range.location == length && range.length == 0) { panelAppendOnly[k] = false }
1583
+ }
1584
+ private var panelRetracting: Set<String> = []
1585
+ // How something went, for a decision whose panel is not the open one (#110): told when it opens
1586
+ // next, never written into the panel of another decision.
1587
+ private var panelNotes: [String: String] = [:]
1588
+ private var panelGen = 0 // which opening of the panel a late detail belongs to
1485
1589
  private func panelKey(_ i: Item) -> String { "\(i.space)|\(i.id)" }
1590
+ private func isOpen(_ k: String) -> Bool { panelItem.map { panelKey($0) } == k }
1591
+ /// Tell the decision `k` how it went: its own panel when open, else when it opens next.
1592
+ private func say(_ k: String, _ msg: String) {
1593
+ if isOpen(k) { setStatus(msg) } else { panelNotes[k] = msg }
1594
+ }
1595
+ /// Settled by a button (a choice, an option, Done): typed words on it were not sent, and go with it — said.
1596
+ /// Settled by a button (a choice, an option, Done) while words were typed on it — before the click or
1597
+ /// while it went: the words stay in sight, in its panel (opened again if it was closed), never dropped
1598
+ /// (round two of the 0.35.1 review). Returns what to add to the outcome.
1599
+ /**
1600
+ * A decision put back under a new id (a Retract settles the old obligation and the relay opens a new
1601
+ * one for the same request): the open panel follows it — its item, drafts and notes move to the new
1602
+ * key — so what is sent from it goes to the decision as it is now (round four).
1603
+ */
1604
+ private func followMoved() {
1605
+ // Only a decision this panel retracted an answer on, and only onto the row the relay puts back for
1606
+ // it: the same request, team, kind and person (final round — any row with the same request moved
1607
+ // words and Send onto another person's row). Anything else is not followed: its words stay under Not sent.
1608
+ guard let cur = panelItem, !cur.ref.isEmpty else { return }
1609
+ let k = panelKey(cur)
1610
+ guard panelRetractedHere.contains(k) else { return }
1611
+ if state.items.contains(where: { panelKey($0) == k }) { return }
1612
+ guard let next = state.items.first(where: { panelKey($0) != k && $0.ref == cur.ref && $0.space == cur.space && $0.kind == cur.kind && $0.who == cur.who }) else { return }
1613
+ let k2 = panelKey(next)
1614
+ panelRetractedHere.remove(k)
1615
+ saveDraft()
1616
+ if let d = panelDrafts.removeValue(forKey: k), panelDrafts[k2] == nil { panelDraftName[k2] = next.headline; panelDrafts[k2] = d }
1617
+ if let n = panelNotes.removeValue(forKey: k), panelNotes[k2] == nil { panelNotes[k2] = n }
1618
+ panelAnsweredHere.remove(k); panelAnsweredHere.remove(k2)
1619
+ // Drawn again for the new row, so its buttons act on it — without taking the keyboard.
1620
+ panelItem = next
1621
+ showDetail(next, byPerson: false)
1622
+ }
1623
+ /// Decisions this panel retracted an answer on: the only ones followMoved follows.
1624
+ private var panelRetractedHere: Set<String> = []
1625
+
1626
+ // MARK: "Not sent" — words typed on things no longer in the menu (round four)
1627
+
1628
+ /// Drafts whose decision has left the menu: only when every team was read (a team out of reach is not news).
1629
+ private func unsentDrafts() -> [(key: String, name: String, text: String)] {
1630
+ guard state.decisionsOk, state.unavailableSpaces.isEmpty else { return [] }
1631
+ let here = Set(state.items.map { panelKey($0) })
1632
+ let open = panelItem.map { panelKey($0) }
1633
+ return panelDrafts.filter { !here.contains($0.key) && $0.key != open && !$0.value.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
1634
+ .sorted { (panelDraftAt[$0.key] ?? 0) > (panelDraftAt[$1.key] ?? 0) }
1635
+ .map { (key: $0.key, name: panelDraftName[$0.key] ?? "Something no longer in the menu", text: $0.value.text) }
1636
+ }
1637
+ @objc private func copyUnsent(_ sender: NSMenuItem) {
1638
+ guard let k = sender.representedObject as? String, let d = panelDrafts[k] else { return }
1639
+ let pb = NSPasteboard.general
1640
+ pb.clearContents()
1641
+ pb.setString(d.text, forType: .string)
1642
+ }
1643
+ @objc private func discardUnsent(_ sender: NSMenuItem) {
1644
+ guard let k = sender.representedObject as? String else { return }
1645
+ panelDrafts.removeValue(forKey: k)
1646
+ panelNotes.removeValue(forKey: k)
1647
+ }
1648
+
1649
+ private func settledNote(_ k: String, _ item: Item) -> String {
1650
+ let inBox = isOpen(k) ? (panelReply?.string ?? "") : ""
1651
+ let words = !inBox.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? inBox : (panelDrafts[k]?.text ?? "")
1652
+ guard !words.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return "" }
1653
+ // Text read back after a restart, not yet looked at, is never called the person's own (final round).
1654
+ if inBox.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, restoredDrafts.contains(k) {
1655
+ return " The restored text kept on it was not sent — check it before you use it; it is under Not sent."
1656
+ }
1657
+ if panelItem != nil && !isOpen(k) {
1658
+ // Another decision's panel is open, maybe being typed in (round three, F8): never switched away
1659
+ // from. The words are kept on this one, and its panel opens when that one is closed.
1660
+ panelDraftName[k] = item.headline
1661
+ panelDrafts[k] = (text: words, kind: panelDrafts[k]?.kind ?? "")
1662
+ if !panelUnsentQueue.contains(where: { panelKey($0) == k }) { panelUnsentQueue.append(item) }
1663
+ return " What you typed on it was not sent — it is kept, and opens here when you close the one you are on."
1664
+ }
1665
+ if !isOpen(k) { panelDraftName[k] = item.headline; panelDrafts[k] = (text: words, kind: panelDrafts[k]?.kind ?? ""); showDetail(item, byPerson: false) }
1666
+ if let box = panelReply, box.string.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { box.string = words }
1667
+ return " What you typed on it was not sent — copy it if you still need it."
1668
+ }
1486
1669
  /// The open decision's typed words, kept for it (or forgotten when the box is empty).
1487
1670
  private func saveDraft() {
1488
1671
  guard let i = panelItem, let tv = panelReply else { return }
1489
1672
  let t = tv.string
1490
1673
  if t.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { panelDrafts.removeValue(forKey: panelKey(i)) }
1491
- else { panelDrafts[panelKey(i)] = (text: t, kind: panelReplyKind?.titleOfSelectedItem ?? "") }
1674
+ else { panelDraftName[panelKey(i)] = i.headline; panelDrafts[panelKey(i)] = (text: t, kind: panelReplyKind?.titleOfSelectedItem ?? "") }
1492
1675
  }
1493
1676
 
1494
1677
  private func label(_ text: String, size: CGFloat, weight: NSFont.Weight, color: NSColor, width: CGFloat) -> NSTextField {
@@ -1600,6 +1783,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
1600
1783
  */
1601
1784
  private func loadDetail(_ item: Item, width: CGFloat) {
1602
1785
  guard !item.ref.isEmpty else { return }
1786
+ let gen = panelGen
1603
1787
  DispatchQueue.global().async {
1604
1788
  // The item's own team, so a decision in another team is found and shown whole.
1605
1789
  let r = run(pantheonBin, ["tray-detail", item.ref] + (item.space.isEmpty ? [] : ["--space", item.space]), timeout: 20)
@@ -1617,7 +1801,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
1617
1801
  return (key: k, text: t)
1618
1802
  }
1619
1803
  DispatchQueue.main.async {
1620
- guard self.panelItem?.id == item.id else { return }
1804
+ // Only the opening that asked, and only its own team's item (#110).
1805
+ guard gen == self.panelGen, self.isOpen(self.panelKey(item)) else { return }
1621
1806
  // Who is asking, said plainly: "from your worker", never "sid escalated" to sid.
1622
1807
  if !asker.isEmpty, let eye = self.panelEyebrow, !eye.stringValue.contains("FROM ") { eye.stringValue += " · FROM " + asker.uppercased() }
1623
1808
  if item.isDecision && item.choices.isEmpty && options.count >= 2, let box = self.panelOptions {
@@ -1664,10 +1849,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
1664
1849
  * actions that settle it. The menu answers "is anything waiting"; this answers
1665
1850
  * "what is it, and what do I do about it" without a terminal.
1666
1851
  */
1667
- func showDetail(_ item: Item) {
1852
+ /// byPerson: false for a panel that opens by itself (a settled decision's words, the queue after a
1853
+ /// close) — it is shown, but never activates the app or takes the keyboard: keystrokes meant for
1854
+ /// another app must not land in its box, and Enter must not send (round four).
1855
+ func showDetail(_ item: Item, byPerson: Bool = true) {
1668
1856
  saveDraft()
1857
+ panelOpening = true
1669
1858
  detailPanel?.close()
1859
+ panelOpening = false
1670
1860
  panelItem = item
1861
+ panelGen += 1
1671
1862
  let width: CGFloat = 620
1672
1863
  let inner = width - 52
1673
1864
  let panel = NSPanel(contentRect: NSRect(x: 0, y: 0, width: width, height: 470),
@@ -1678,6 +1869,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
1678
1869
  panel.level = .floating
1679
1870
  panel.isReleasedWhenClosed = false
1680
1871
  panel.hidesOnDeactivate = false
1872
+ // However it is closed — Close, the title bar's ✕, Later, another decision opening — the same close
1873
+ // runs (round two, item 2c): its draft is kept and nothing later lands "here" in a window that is gone.
1874
+ panel.delegate = self
1681
1875
 
1682
1876
  let effect = NSVisualEffectView(frame: NSRect(x: 0, y: 0, width: width, height: 470))
1683
1877
  effect.material = .popover
@@ -1970,18 +2164,38 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
1970
2164
  panel.setContentSize(NSSize(width: width, height: height))
1971
2165
  panel.center()
1972
2166
  detailPanel = panel
1973
- NSApp.activate(ignoringOtherApps: true)
1974
- panel.makeKeyAndOrderFront(nil)
2167
+ panelByPerson = byPerson
2168
+ if byPerson {
2169
+ NSApp.activate(ignoringOtherApps: true)
2170
+ panel.makeKeyAndOrderFront(nil)
2171
+ } else {
2172
+ panel.orderFrontRegardless()
2173
+ }
1975
2174
  panelRendered = nil
1976
2175
  panelRaw = ""
1977
2176
  panelShowingRaw = false
1978
2177
  loadDetail(item, width: inner)
1979
2178
  // Words typed here before: back in the box, the box open. A send still undoable: its Retract.
1980
- if let dr = panelDrafts[panelKey(item)], !dr.text.isEmpty {
2179
+ // Text read back after a restart is not opened into the box by itself: it is offered, as a Note,
2180
+ // to check first (round four) — the person chooses Reply manually to see it.
2181
+ let restored = restoredDrafts.contains(panelKey(item))
2182
+ if let dr = panelDrafts[panelKey(item)], !dr.text.isEmpty, !restored {
1981
2183
  if !dr.kind.isEmpty, panelReplyKind?.itemTitles.contains(dr.kind) == true { panelReplyKind?.selectItem(withTitle: dr.kind) }
1982
- panelReplyManually()
2184
+ enterReplyMode(focus: byPerson)
2185
+ } else if restored, panelReplyKind?.itemTitles.contains("Note") == true {
2186
+ panelReplyKind?.selectItem(withTitle: "Note")
2187
+ }
2188
+ let k = panelKey(item)
2189
+ if let s = panelSent[k], s.until > Date() { panelRetract?.isHidden = false; panelRetract?.isEnabled = !panelRetracting.contains(k); panelStatusRow?.isHidden = false; refitPanel() }
2190
+ // Its reply still on the way: Send stays off here, and says why (#105).
2191
+ if panelInFlight.contains(k) {
2192
+ panelSendButton?.isEnabled = false
2193
+ setStatus("Still sending your last answer to this — Send works again once it lands.")
2194
+ } else if let note = panelNotes.removeValue(forKey: k) {
2195
+ setStatus(note)
2196
+ } else if restored, panelDrafts[k] != nil {
2197
+ setStatus("There is restored text for this, kept from before the menu bar restarted — choose Reply manually to check it before sending.")
1983
2198
  }
1984
- if let s = panelSent[panelKey(item)], s.until > Date() { panelRetract?.isHidden = false; panelStatusRow?.isHidden = false; refitPanel() }
1985
2199
  }
1986
2200
 
1987
2201
  private func setStatus(_ text: String) {
@@ -1992,8 +2206,19 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
1992
2206
  }
1993
2207
 
1994
2208
  @objc private func panelClose() {
2209
+ let p = detailPanel
2210
+ p?.close() // its delegate runs panelDidClose
2211
+ if p == nil || detailPanel === p { panelDidClose() } // none open, or a close that did not reach the delegate
2212
+ }
2213
+ /// What closing the detail panel does, however it was closed (windowWillClose and panelClose).
2214
+ fileprivate func panelDidClose() {
1995
2215
  saveDraft()
1996
- detailPanel?.close()
2216
+ // Closed by the person (not by another panel opening): a decision settled meanwhile with words
2217
+ // typed on it opens now, with them.
2218
+ if !panelOpening, !panelUnsentQueue.isEmpty {
2219
+ let next = panelUnsentQueue.removeFirst()
2220
+ DispatchQueue.main.async { [weak self] in self?.showDetail(next, byPerson: false) }
2221
+ }
1997
2222
  detailPanel = nil
1998
2223
  panelText = nil
1999
2224
  panelBodyHeight = nil
@@ -2029,7 +2254,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
2029
2254
 
2030
2255
  /// Reply mode: the buttons step aside and only the box remains, with Cancel to
2031
2256
  /// bring them back. The body gives up a little height so the panel stays put.
2032
- @objc private func panelReplyManually() {
2257
+ @objc private func panelReplyManually() { enterReplyMode(focus: true) }
2258
+ /// The box shown; the keyboard put in it only when the person opened this panel or asked to reply.
2259
+ private func enterReplyMode(focus: Bool) {
2033
2260
  panelButtons?.isHidden = true
2034
2261
  panelReplyButton?.isHidden = true
2035
2262
  panelReplyButton?.keyEquivalent = ""
@@ -2038,7 +2265,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
2038
2265
  if let c = panelBodyHeight, c.constant > 140 { c.constant -= 20 }
2039
2266
  panelRetract?.isHidden = true
2040
2267
  setStatus("") // refits
2041
- if let tv = panelReply { detailPanel?.makeFirstResponder(tv) }
2268
+ if let i = panelItem, restoredDrafts.remove(panelKey(i)) != nil {
2269
+ setStatus("Restored text, kept from before the menu bar restarted — check it before sending. It goes as a Note.")
2270
+ }
2271
+ if focus, let tv = panelReply { detailPanel?.makeFirstResponder(tv) }
2042
2272
  }
2043
2273
  @objc private func panelCancelReply() { exitReplyMode() }
2044
2274
  private func exitReplyMode() {
@@ -2065,22 +2295,27 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
2065
2295
  @objc private func panelChoose(_ sender: NSButton) {
2066
2296
  guard let item = panelItem, sender.tag >= 0, sender.tag < item.choices.count else { return }
2067
2297
  let c = item.choices[sender.tag]
2298
+ let k = panelKey(item)
2299
+ if busyHere(k) { return }
2068
2300
  var payload: [String: Any] = ["action": "reply", "kind": "ANSWER", "body": c.answer, "goal": item.goal, "space": item.space, "decision": item.id]
2069
2301
  if !item.ref.isEmpty { payload["act"] = item.ref }
2070
- guard writeAction(payload) else { setStatus("Could not write the action. Use Show the thread instead."); return }
2302
+ guard let aid = queueAction(payload) else { setStatus("Could not write the action. Use Show the thread instead."); return }
2071
2303
  setStatus("Answering…")
2304
+ panelInFlight.insert(k)
2305
+ panelSendButton?.isEnabled = false
2072
2306
  sender.isEnabled = false
2073
2307
  DispatchQueue.global().async {
2074
- let r = run(pantheonBin, ["explain", "--queued"], timeout: 25)
2308
+ let r = run(pantheonBin, ["explain", "--queued", "--only-action", "--action-id", aid], timeout: QUEUED_WAIT_S)
2075
2309
  DispatchQueue.main.async {
2310
+ self.panelInFlight.remove(k)
2311
+ if self.isOpen(k) { self.panelSendButton?.isEnabled = true }
2076
2312
  sender.isEnabled = true
2077
- let here = self.panelItem.map { self.panelKey($0) } == self.panelKey(item)
2078
- let out = (r?.out ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
2079
- if r?.code == 0 {
2080
- if here { self.setStatus("\(c.label) — done.") }
2313
+ let v = self.queuedVerdict(r, aid)
2314
+ if v.ok {
2315
+ self.say(k, "\(c.label) — done." + self.settledNote(k, item))
2081
2316
  self.refresh()
2082
- } else if here {
2083
- self.setStatus(out.hasPrefix("not sent: ") ? String(out.dropFirst("not sent: ".count)) : "the relay could not be reached")
2317
+ } else {
2318
+ self.say(k, "\(c.label): " + v.why)
2084
2319
  }
2085
2320
  }
2086
2321
  }
@@ -2090,19 +2325,23 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
2090
2325
  @objc private func panelChange(_ sender: NSButton) {
2091
2326
  guard let item = panelItem, item.kind == "change" else { return }
2092
2327
  let answer = sender.tag == 0 ? "approve" : "keep"
2093
- guard writeAction(["action": "change", "change": item.id, "answer": answer, "by": "tray"]) else { setStatus("Could not write the action. In a terminal: pantheon changes"); return }
2328
+ let k = panelKey(item)
2329
+ if busyHere(k) { return }
2330
+ guard let aid = queueAction(["action": "change", "change": item.id, "answer": answer, "by": "tray"]) else { setStatus("Could not write the action. In a terminal: pantheon changes"); return }
2094
2331
  setStatus(answer == "approve" ? "Approving…" : "Keeping it as it is…")
2332
+ panelInFlight.insert(k)
2095
2333
  sender.isEnabled = false
2096
2334
  DispatchQueue.global().async {
2097
- let r = run(pantheonBin, ["explain", "--queued"], timeout: 60)
2335
+ let r = run(pantheonBin, ["explain", "--queued", "--only-action", "--action-id", aid], timeout: max(60, QUEUED_WAIT_S))
2098
2336
  DispatchQueue.main.async {
2337
+ self.panelInFlight.remove(k)
2099
2338
  sender.isEnabled = true
2100
- let out = (r?.out ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
2101
- if r?.code == 0 {
2102
- self.setStatus(answer == "approve" ? "Approved — your setup is changed." : "Kept as it is — nothing changed.")
2339
+ let v = self.queuedVerdict(r, aid)
2340
+ if v.ok {
2341
+ self.say(k, answer == "approve" ? "Approved — your setup is changed." : "Kept as it is — nothing changed.")
2103
2342
  self.refresh()
2104
2343
  } else {
2105
- self.setStatus(out.hasPrefix("not sent: ") ? String(out.dropFirst("not sent: ".count)) : "Could not answer it — in a terminal: pantheon changes")
2344
+ self.say(k, v.unsure || self.actionOutcome(r?.out).hasPrefix("not sent: ") ? v.why : "Could not answer it — in a terminal: pantheon changes")
2106
2345
  }
2107
2346
  }
2108
2347
  }
@@ -2116,19 +2355,23 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
2116
2355
  // Always with its team: on one team the item carries none, so the status's own team is it (review round 3).
2117
2356
  let team = item.space.isEmpty ? state.space : item.space
2118
2357
  if !team.isEmpty { payload["space"] = team }
2119
- guard writeAction(payload) else { setStatus("Could not write the action. Use Show the thread instead."); return }
2358
+ let k = panelKey(item)
2359
+ if busyHere(k) { return }
2360
+ guard let aid = queueAction(payload) else { setStatus("Could not write the action. Use Show the thread instead."); return }
2120
2361
  setStatus(how == "takeover" ? "Taking it over…" : "Stopping…")
2362
+ panelInFlight.insert(k)
2121
2363
  sender.isEnabled = false
2122
2364
  DispatchQueue.global().async {
2123
- let r = run(pantheonBin, ["explain", "--queued"], timeout: 25)
2365
+ let r = run(pantheonBin, ["explain", "--queued", "--only-action", "--action-id", aid], timeout: QUEUED_WAIT_S)
2124
2366
  DispatchQueue.main.async {
2367
+ self.panelInFlight.remove(k)
2125
2368
  sender.isEnabled = true
2126
- let out = (r?.out ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
2127
- if r?.code == 0 {
2128
- self.setStatus(how == "takeover" ? "It's yours now — your teammate is told you're handling it." : "Stopped — your agent won't pick it up again.")
2369
+ let v = self.queuedVerdict(r, aid)
2370
+ if v.ok {
2371
+ self.say(k, how == "takeover" ? "It's yours now — your teammate is told you're handling it." : "Stopped — your agent won't pick it up again.")
2129
2372
  self.refresh()
2130
2373
  } else {
2131
- self.setStatus(out.hasPrefix("not sent: ") ? String(out.dropFirst("not sent: ".count)) : "Could not stop it — try again")
2374
+ self.say(k, v.unsure || self.actionOutcome(r?.out).hasPrefix("not sent: ") ? v.why : "Could not stop it — try again")
2132
2375
  }
2133
2376
  }
2134
2377
  }
@@ -2138,82 +2381,145 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
2138
2381
  @objc private func panelChooseOption(_ sender: NSButton) {
2139
2382
  guard let item = panelItem, sender.tag >= 0, sender.tag < panelOptionList.count else { return }
2140
2383
  let o = panelOptionList[sender.tag]
2384
+ let k = panelKey(item)
2385
+ if busyHere(k) { return }
2141
2386
  var payload: [String: Any] = ["action": "reply", "kind": "ANSWER", "body": "(\(o.key)) \(o.text)", "goal": item.goal, "space": item.space, "decision": item.id]
2142
2387
  if !item.ref.isEmpty { payload["act"] = item.ref }
2143
- guard writeAction(payload) else { setStatus("Could not write the action. Use Reply manually instead."); return }
2388
+ guard let aid = queueAction(payload) else { setStatus("Could not write the action. Use Reply manually instead."); return }
2144
2389
  setStatus("Answering…")
2390
+ panelInFlight.insert(k)
2391
+ panelSendButton?.isEnabled = false
2145
2392
  panelOptions?.arrangedSubviews.forEach { ($0 as? NSButton)?.isEnabled = false }
2146
2393
  DispatchQueue.global().async {
2147
- let r = run(pantheonBin, ["explain", "--queued"], timeout: 25)
2394
+ let r = run(pantheonBin, ["explain", "--queued", "--only-action", "--action-id", aid], timeout: QUEUED_WAIT_S)
2148
2395
  DispatchQueue.main.async {
2149
- // Only the panel it was chosen on hears how it went (#79).
2150
- let here = self.panelItem.map { self.panelKey($0) } == self.panelKey(item)
2151
- let out = (r?.out ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
2152
- if r?.code == 0 {
2153
- if here { self.setStatus("Answered (\(o.key)) — it is no longer waiting on you.") }
2396
+ self.panelInFlight.remove(k)
2397
+ // Only the panel it was chosen on hears how it went (#79); another one is told when it opens (#110).
2398
+ let here = self.isOpen(k)
2399
+ if here { self.panelSendButton?.isEnabled = true }
2400
+ let v = self.queuedVerdict(r, aid)
2401
+ if v.ok {
2402
+ self.say(k, "Answered (\(o.key)) — it is no longer waiting on you." + self.settledNote(k, item))
2154
2403
  self.refresh()
2155
- } else if here {
2156
- self.panelOptions?.arrangedSubviews.forEach { ($0 as? NSButton)?.isEnabled = true }
2157
- self.setStatus(out.hasPrefix("not sent: ") ? String(out.dropFirst("not sent: ".count)) : "the relay could not be reached")
2404
+ } else {
2405
+ if here { self.panelOptions?.arrangedSubviews.forEach { ($0 as? NSButton)?.isEnabled = true } }
2406
+ self.say(k, "(\(o.key)): " + v.why)
2158
2407
  }
2159
2408
  }
2160
2409
  }
2161
2410
  }
2162
2411
 
2163
2412
  /// Send the words in the box as the chosen act. The CLI does the sending and
2164
- /// prints "sent KIND id=… seq=…" or "not sent: why" on stdout; both are shown.
2413
+ /// prints "sent KIND id=… seq=…", "not sent: why", or "unconfirmed: why" (the relay's
2414
+ /// answer was lost and the reply is not found yet — it may have landed) on stdout; all are shown.
2165
2415
  @objc private func panelSend(_ sender: Any?) {
2166
2416
  guard let item = panelItem, let tv = panelReply else { return }
2167
- // Return is the send key: a second press while the first send is still in
2168
- // flight must not send the same words twice.
2169
- if panelSendButton?.isEnabled == false { return }
2417
+ let k = panelKey(item)
2418
+ // Return is the send key, and the panel can be closed and opened again: while this
2419
+ // decision's reply is in flight, nothing sends the same words twice (#105) — and it says why.
2420
+ if panelInFlight.contains(k) { setStatus("Still sending your last answer to this — Send works again once it lands."); return }
2170
2421
  let text = tv.string.trimmingCharacters(in: .whitespacesAndNewlines)
2171
2422
  if text.isEmpty { setStatus("Type your reply first."); return }
2423
+ if kindCode(panelReplyKind?.titleOfSelectedItem) == "ANSWER", panelAnsweredHere.contains(k) {
2424
+ setStatus("This is already answered — switch to Note to send the rest.")
2425
+ return
2426
+ }
2427
+ if let again = panelResendGuard[k], text.hasPrefix(again), !panelResendAsked.contains(k) {
2428
+ panelResendAsked.insert(k)
2429
+ setStatus("This starts with words you already sent. Press Send again to send it all as it is, or take them out first.")
2430
+ return
2431
+ }
2432
+ panelResendGuard.removeValue(forKey: k); panelResendAsked.remove(k)
2172
2433
  let kind = kindCode(panelReplyKind?.titleOfSelectedItem)
2173
2434
  var payload: [String: Any] = ["action": "reply", "kind": kind, "body": text, "goal": item.goal, "space": item.space]
2174
- if item.isDecision { payload["decision"] = item.id }
2435
+ // The row's own obligation, always (round four): "Waiting on sam" asks sam, never the first owner found.
2436
+ payload["decision"] = item.id
2175
2437
  if !item.ref.isEmpty { payload["act"] = item.ref }
2176
- guard writeAction(payload) else { setStatus("Could not write the action. Use Show the thread instead."); return }
2438
+ guard let aid = queueAction(payload) else { setStatus("Could not write the action. Use Show the thread instead."); return }
2177
2439
  setStatus("Sending…")
2440
+ panelInFlight.insert(k)
2441
+ panelAppendOnly[k] = true
2178
2442
  panelSendButton?.isEnabled = false
2179
2443
  // In flight, the words are not a draft: reopening this decision meanwhile does not show them as unsent.
2180
2444
  let kindTitle = panelReplyKind?.titleOfSelectedItem ?? ""
2181
- panelDrafts.removeValue(forKey: panelKey(item))
2445
+ panelDrafts.removeValue(forKey: k)
2182
2446
  DispatchQueue.global().async {
2183
- let r = run(pantheonBin, ["explain", "--queued"], timeout: 25)
2447
+ let r = run(pantheonBin, ["explain", "--queued", "--only-action", "--action-id", aid], timeout: QUEUED_WAIT_S)
2184
2448
  DispatchQueue.main.async {
2185
- let k = self.panelKey(item)
2449
+ self.panelInFlight.remove(k)
2450
+ let appendOnly = self.panelAppendOnly.removeValue(forKey: k) ?? false
2186
2451
  // Still the decision this was sent from? Only then is the open panel touched.
2187
- let here = self.panelItem.map { self.panelKey($0) } == k
2452
+ let here = self.isOpen(k)
2188
2453
  if here { self.panelSendButton?.isEnabled = true }
2189
- let out = (r?.out ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
2454
+ let out = self.actionOutcome(r?.out)
2190
2455
  if r?.code == 0, let idTok = out.split(separator: " ").first(where: { $0.hasPrefix("id=") }) {
2191
- self.panelSent[k] = (act: String(idTok.dropFirst(3)), space: item.space, until: Date().addingTimeInterval(60))
2192
- self.panelDrafts.removeValue(forKey: k)
2456
+ let act = String(idTok.dropFirst(3))
2457
+ self.panelSent[k] = (act: act, space: item.space, until: Date().addingTimeInterval(60))
2458
+ // Only the words that were sent are cleared (#105). A follow-up typed onto them loses them from
2459
+ // its front (0.35.1 review, item 7) — only when every edit since the send was typing at the end
2460
+ // (round two: a retyped or pasted "OK, but…" lost the person's words). Otherwise kept whole.
2461
+ let cut = { (v: String) -> String in appendOnly ? self.afterSent(v, text) : (v.trimmingCharacters(in: .whitespacesAndNewlines) == text ? "" : v) }
2462
+ let startsWithSent = { (v: String) -> Bool in !v.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && v.drop(while: { $0.isWhitespace }).hasPrefix(text) }
2463
+ if let dr = self.panelDrafts[k] {
2464
+ let rest = cut(dr.text)
2465
+ if rest.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { self.panelDrafts.removeValue(forKey: k) } else { self.panelDrafts[k] = (text: rest, kind: dr.kind) }
2466
+ if startsWithSent(rest) { self.panelResendGuard[k] = text }
2467
+ }
2468
+ var what = kind == "ANSWER" ? "Answered — it is no longer waiting on you." : kind == "ASK" ? "Asked — the agent that raised this owes you a reply." : "Noted — it stays waiting."
2469
+ // An answer settles the decision; a second one is refused (ALREADY_ANSWERED). What is left goes as a Note (F10).
2470
+ if kind == "ANSWER" { self.panelAnsweredHere.insert(k) }
2193
2471
  if here {
2194
- self.panelReply?.string = "" // the box open now, which may be a reopened one, not the captured view
2195
- let what = kind == "ANSWER" ? "Answered — it is no longer waiting on you." : kind == "ASK" ? "Asked — the agent that raised this owes you a reply." : "Noted — it stays waiting."
2196
- self.setStatus(what)
2197
- self.exitReplyMode()
2198
- self.panelRetract?.isHidden = false
2199
- self.panelStatusRow?.isHidden = false
2200
- self.refitPanel()
2472
+ let box = self.panelReply // the box open now, which may be a reopened one, not the captured view
2473
+ let rest = cut(box?.string ?? "")
2474
+ if startsWithSent(rest) {
2475
+ self.panelResendGuard[k] = text
2476
+ what += kind == "ANSWER"
2477
+ ? " The box still starts with what you just sent — take that out, then switch to Note to send the rest."
2478
+ : " The box still starts with what you just sent — take that out, or press Send again to send it all as it is."
2479
+ }
2480
+ if rest.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
2481
+ box?.string = ""
2482
+ self.setStatus(what)
2483
+ self.exitReplyMode()
2484
+ self.panelRetract?.isHidden = false
2485
+ self.panelStatusRow?.isHidden = false
2486
+ self.refitPanel()
2487
+ } else {
2488
+ box?.string = rest
2489
+ self.setStatus(self.panelResendGuard[k] != nil ? what : what + (kind == "ANSWER" ? " The rest is still in the box — switch to Note to send it." : " Your newer words are still in the box."))
2490
+ }
2491
+ } else {
2492
+ self.panelNotes[k] = self.panelResendGuard[k] != nil ? what + " Your box still starts with what you just sent — take that out before sending again." : what
2201
2493
  }
2202
2494
  DispatchQueue.main.asyncAfter(deadline: .now() + 60) { [weak self] in
2203
2495
  guard let self = self else { return }
2496
+ // This send's own minute: a newer send on the same decision keeps its Retract (#110).
2497
+ guard self.panelSent[k]?.act == act else { return }
2204
2498
  self.panelSent.removeValue(forKey: k)
2205
- guard self.panelItem.map({ self.panelKey($0) }) == k else { return }
2499
+ guard self.isOpen(k) else { return }
2206
2500
  self.panelRetract?.isHidden = true
2207
2501
  self.panelStatusRow?.isHidden = (self.panelStatus?.stringValue.isEmpty ?? true)
2208
2502
  self.refitPanel()
2209
2503
  }
2210
2504
  self.refresh()
2211
2505
  } else {
2212
- // Not sent: the words stay with their decision, whichever is open now.
2213
- if self.panelDrafts[k] == nil { self.panelDrafts[k] = (text: text, kind: kindTitle) }
2214
- if here, let box = self.panelReply, box.string.isEmpty { box.string = text }
2215
- let why = out.hasPrefix("not sent: ") ? String(out.dropFirst("not sent: ".count)) : "the relay could not be reached"
2216
- if here { self.setStatus("Not sent — \(why) Your words are still in the box.") }
2506
+ // Not sent: the words stay with their decision, whichever is open now; anything typed since stays after
2507
+ // them — unless it already starts with them, so they are never in the box twice (0.35.1 review, item 7).
2508
+ let startsWithSent = { (v: String) in v.drop(while: { $0.isWhitespace }).hasPrefix(text) }
2509
+ if let dr = self.panelDrafts[k], !dr.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
2510
+ if !startsWithSent(dr.text) { self.panelDrafts[k] = (text: text + "\n\n" + dr.text, kind: dr.kind.isEmpty ? kindTitle : dr.kind) }
2511
+ } else {
2512
+ self.panelDrafts[k] = (text: text, kind: kindTitle)
2513
+ }
2514
+ if here, let box = self.panelReply {
2515
+ let v = box.string.trimmingCharacters(in: .whitespacesAndNewlines)
2516
+ if v.isEmpty { box.string = text } else if !startsWithSent(box.string) { box.string = text + "\n\n" + box.string }
2517
+ }
2518
+ // "Not confirmed": the relay's answer was lost and the reply is not found yet, or the CLI stopped after
2519
+ // taking it — it may have landed (#107; item 6).
2520
+ let verdict = self.queuedVerdict(r, aid)
2521
+ let why = verdict.ok ? "Not confirmed — Pantheon did not say it was sent. Check the thread before sending again." : verdict.why
2522
+ self.say(k, why + " Your words are still in the box.")
2217
2523
  }
2218
2524
  }
2219
2525
  }
@@ -2222,28 +2528,42 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
2222
2528
  /// The undo. RETRACT withdraws the act; the record keeps it as retracted.
2223
2529
  @objc private func panelRetractAction() {
2224
2530
  // The open decision's own send, never another's (#79).
2225
- guard let i = panelItem, let s = panelSent[panelKey(i)], s.until > Date() else { return }
2531
+ guard let i = panelItem else { return }
2226
2532
  let k = panelKey(i)
2533
+ // Past its minute: said, and the button goes — never a click that does nothing (#110).
2534
+ guard let s = panelSent[k], s.until > Date() else {
2535
+ panelSent.removeValue(forKey: k)
2536
+ panelRetract?.isHidden = true
2537
+ setStatus("Too late to retract — a reply can be withdrawn only in its first minute.")
2538
+ return
2539
+ }
2540
+ if panelRetracting.contains(k) { return }
2227
2541
  let id = s.act
2228
2542
  var payload: [String: Any] = ["action": "retract", "act": id]
2229
2543
  if !s.space.isEmpty { payload["space"] = s.space }
2230
- guard writeAction(payload) else { setStatus("Could not write the action."); return }
2544
+ guard let aid = queueAction(payload) else { setStatus("Could not write the action."); return }
2231
2545
  setStatus("Retracting…")
2546
+ panelRetracting.insert(k)
2232
2547
  panelRetract?.isEnabled = false
2233
2548
  DispatchQueue.global().async {
2234
- let r = run(pantheonBin, ["explain", "--queued"], timeout: 25)
2549
+ let r = run(pantheonBin, ["explain", "--queued", "--only-action", "--action-id", aid], timeout: QUEUED_WAIT_S)
2235
2550
  DispatchQueue.main.async {
2236
- self.panelRetract?.isEnabled = true
2551
+ self.panelRetracting.remove(k)
2552
+ if self.isOpen(k) { self.panelRetract?.isEnabled = true }
2237
2553
  if r?.code == 0 {
2238
- self.panelSent.removeValue(forKey: k)
2239
- if self.panelItem.map({ self.panelKey($0) }) == k {
2240
- self.panelRetract?.isHidden = true
2241
- self.setStatus("Retracted.") // refits
2242
- }
2554
+ if self.panelSent[k]?.act == id { self.panelSent.removeValue(forKey: k) }
2555
+ if self.isOpen(k) { self.panelRetract?.isHidden = true }
2556
+ // The answer is taken back: the decision waits again (under a new id, which the next status
2557
+ // follows), so a corrected Answer is allowed again (round four).
2558
+ self.panelAnsweredHere.remove(k)
2559
+ self.panelResendGuard.removeValue(forKey: k); self.panelResendAsked.remove(k)
2560
+ self.panelRetractedHere.insert(k)
2561
+ self.say(k, "Retracted — you can answer it again.") // refits
2243
2562
  self.refresh()
2244
2563
  } else {
2245
- let out = (r?.out ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
2246
- self.setStatus("Could not retract — \(out.hasPrefix("not sent: ") ? String(out.dropFirst("not sent: ".count)) : "the relay could not be reached")")
2564
+ // Told on the decision it was about (#110): its own panel, or when it opens next.
2565
+ let v = self.queuedVerdict(r, aid)
2566
+ self.say(k, v.unsure ? v.why : "Could not retract — " + v.why.replacingOccurrences(of: "Not sent — ", with: ""))
2247
2567
  }
2248
2568
  }
2249
2569
  }
@@ -2268,19 +2588,27 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
2268
2588
 
2269
2589
  @objc private func panelDone() {
2270
2590
  guard let item = panelItem, item.isDecision else { return }
2591
+ if busyHere(panelKey(item)) { return }
2271
2592
  setStatus("Marking it done…")
2272
2593
  var payload: [String: Any] = ["action": "done", "decision": item.id, "space": item.space]
2273
2594
  if !item.ref.isEmpty { payload["act"] = item.ref }
2274
- guard writeAction(payload) else {
2595
+ guard let aid = queueAction(payload) else {
2275
2596
  setStatus("Could not write the action. Use Show the thread instead.")
2276
2597
  return
2277
2598
  }
2599
+ let k = panelKey(item)
2600
+ panelInFlight.insert(k)
2601
+ panelSendButton?.isEnabled = false
2278
2602
  DispatchQueue.global().async {
2279
- let r = run(pantheonBin, ["explain", "--queued"], timeout: 25)
2603
+ let r = run(pantheonBin, ["explain", "--queued", "--only-action", "--action-id", aid], timeout: QUEUED_WAIT_S)
2280
2604
  DispatchQueue.main.async {
2281
- self.setStatus(r?.code == 0
2282
- ? "Done — it is no longer waiting on you."
2283
- : "Could not mark it done. Use Show the thread instead.")
2605
+ self.panelInFlight.remove(k)
2606
+ if self.isOpen(k) { self.panelSendButton?.isEnabled = true }
2607
+ // On the decision it was about (#110): never "Done" on another decision opened since.
2608
+ let v = self.queuedVerdict(r, aid)
2609
+ self.say(k, v.ok
2610
+ ? "Done — it is no longer waiting on you." + self.settledNote(k, item)
2611
+ : v.unsure || self.actionOutcome(r?.out).hasPrefix("not sent: ") ? v.why : "Could not mark it done. Use Show the thread instead.")
2284
2612
  self.refresh()
2285
2613
  }
2286
2614
  }
@@ -2292,11 +2620,67 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
2292
2620
  (Bundle.main.executablePath as NSString?)?.deletingLastPathComponent
2293
2621
  ?? URL(fileURLWithPath: CommandLine.arguments[0]).deletingLastPathComponent().path
2294
2622
  }
2295
- /// What `pantheon explain --queued` reads. Same file the desktop alert writes.
2623
+ /// What `pantheon explain --queued` reads when it is given no action id: the single file the
2624
+ /// desktop alert writes too. Only for the Terminal paths (a .command cannot carry an id).
2296
2625
  private func writeAction(_ payload: [String: Any]) -> Bool {
2297
2626
  guard let data = try? JSONSerialization.data(withJSONObject: payload) else { return false }
2298
2627
  return (try? data.write(to: URL(fileURLWithPath: binDir() + "/.hud-action.json"), options: .atomic)) != nil
2299
2628
  }
2629
+ /**
2630
+ * Queue one action for `pantheon explain --queued --only-action --action-id <id>` (0.35.1, #110):
2631
+ * a file of its own in bin/.hud-actions, named by its id, written whole and renamed into place.
2632
+ * Two clicks in quick succession each have their own file, so neither can replace the other,
2633
+ * and the CLI takes each exactly once (hud-queue.ts). The id rides in it as its nonce.
2634
+ */
2635
+ private func queueAction(_ payload: [String: Any]) -> String? {
2636
+ let id = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased()
2637
+ var p = payload
2638
+ p["nonce"] = id
2639
+ let dir = URL(fileURLWithPath: binDir()).appendingPathComponent(".hud-actions")
2640
+ do {
2641
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
2642
+ let data = try JSONSerialization.data(withJSONObject: p)
2643
+ let file = dir.appendingPathComponent("\(id).json")
2644
+ try data.write(to: file, options: .atomic) // written aside, then renamed into place
2645
+ try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: file.path)
2646
+ return id
2647
+ } catch { return nil }
2648
+ }
2649
+ /// The CLI's answer for a person: its first line names the action it took ("action <id>"), which is not news.
2650
+ private func actionOutcome(_ out: String?) -> String {
2651
+ (out ?? "").split(separator: "\n", omittingEmptySubsequences: false)
2652
+ .filter { !$0.hasPrefix("action ") }
2653
+ .joined(separator: "\n")
2654
+ .trimmingCharacters(in: .whitespacesAndNewlines)
2655
+ }
2656
+ /**
2657
+ * How one queued action went, for a person: done, "Not sent — why", or "Not confirmed — why"
2658
+ * when it may have gone (#107). A CLI that took the action ("action <id>") and then stopped
2659
+ * without a verdict — killed at the limit, crashed — is never "not sent" (0.35.1 review, item 6).
2660
+ */
2661
+ private func queuedVerdict(_ r: (out: String, code: Int32)?, _ aid: String) -> (ok: Bool, unsure: Bool, why: String) {
2662
+ let raw = r?.out ?? ""
2663
+ let out = actionOutcome(raw)
2664
+ if r?.code == 0 { return (true, false, "") }
2665
+ if out.hasPrefix("not sent: ") { return (false, false, "Not sent — " + out.dropFirst("not sent: ".count)) }
2666
+ if out.hasPrefix("unconfirmed: ") { return (false, true, "Not confirmed — " + out.dropFirst("unconfirmed: ".count)) }
2667
+ if raw.split(separator: "\n").contains(where: { $0 == "action \(aid)" }) {
2668
+ return (false, true, "Not confirmed — Pantheon stopped before it said whether this went through. Check the thread before trying again.")
2669
+ }
2670
+ return (false, false, "Not sent — the relay could not be reached.")
2671
+ }
2672
+ /// v without the words that were sent at its front: a follow-up typed onto them (0.35.1 review, item 7).
2673
+ private func afterSent(_ v: String, _ text: String) -> String {
2674
+ let t = String(v.drop(while: { $0.isWhitespace }))
2675
+ guard t.hasPrefix(text) else { return v }
2676
+ return String(t.dropFirst(text.count).drop(while: { $0.isWhitespace }))
2677
+ }
2678
+ /// One action per decision at a time, for every button on its panel (0.35.1 review, item 5): said, never a second answer.
2679
+ private func busyHere(_ k: String) -> Bool {
2680
+ guard panelInFlight.contains(k) else { return false }
2681
+ setStatus("Still sending your last answer to this — wait for it to land.")
2682
+ return true
2683
+ }
2300
2684
  func copyPrompt(_ item: Item) {
2301
2685
  let pb = NSPasteboard.general
2302
2686
  pb.clearContents()
@@ -2335,9 +2719,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
2335
2719
  /// Write the action and run `pantheon explain --queued --silent` with no Terminal. Where the
2336
2720
  /// Claude app will not open, the CLI opens Terminal itself; only a failure of both is said here.
2337
2721
  private func quietExplain(_ payload: [String: Any], failing: String) {
2338
- guard writeAction(payload) else { reportFailure(failing); return }
2722
+ guard let aid = queueAction(payload) else { reportFailure(failing); return }
2339
2723
  DispatchQueue.global().async {
2340
- let r = run(pantheonBin, ["explain", "--queued", "--silent"], timeout: 60)
2724
+ let r = run(pantheonBin, ["explain", "--queued", "--silent", "--only-action", "--action-id", aid], timeout: 60)
2341
2725
  DispatchQueue.main.async { if r?.code != 0 { self.reportFailure(failing) } }
2342
2726
  }
2343
2727
  }
@@ -2538,7 +2922,18 @@ let delegate = AppDelegate()
2538
2922
  app.delegate = delegate
2539
2923
  app.run()
2540
2924
 
2925
+ extension AppDelegate: NSWindowDelegate {
2926
+ func windowWillClose(_ notification: Notification) {
2927
+ guard let w = notification.object as? NSWindow, w === detailPanel else { return }
2928
+ panelDidClose()
2929
+ }
2930
+ }
2931
+
2541
2932
  extension AppDelegate: NSTextViewDelegate {
2933
+ func textView(_ textView: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, replacementString: String?) -> Bool {
2934
+ noteEdit(textView, affectedCharRange)
2935
+ return true
2936
+ }
2542
2937
  func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
2543
2938
  guard textView === panelReply, commandSelector == #selector(NSResponder.insertNewline(_:)) else { return false }
2544
2939
  if NSApp.currentEvent?.modifierFlags.contains(.shift) == true { return false }