@slack/radar-mcp 1.21.0 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +68 -15
  2. package/dist/mcp/api-paths.d.ts +2 -2
  3. package/dist/mcp/api-paths.js +4 -19
  4. package/dist/mcp/dashboard-identity.d.ts +6 -0
  5. package/dist/mcp/dashboard-identity.js +11 -0
  6. package/dist/mcp/index.js +117 -32
  7. package/dist/mcp/logs-result.d.ts +1 -0
  8. package/dist/mcp/logs-result.js +1 -0
  9. package/dist/mcp/radar-export-get.d.ts +30 -0
  10. package/dist/mcp/radar-export-get.js +49 -0
  11. package/dist/mcp/radar-response.d.ts +4 -1
  12. package/dist/mcp/radar-response.js +8 -3
  13. package/dist/mcp/session-backfill.js +3 -4
  14. package/dist/mcp/session-enable.d.ts +1 -0
  15. package/dist/mcp/session-enable.js +146 -15
  16. package/dist/mcp/snapshot.js +42 -26
  17. package/dist/mcp/sources-gate.js +1 -0
  18. package/dist/mcp/stale-dashboard.d.ts +23 -0
  19. package/dist/mcp/stale-dashboard.js +122 -0
  20. package/dist/mcp/switchboard-spool.d.ts +12 -0
  21. package/dist/mcp/switchboard-spool.js +107 -0
  22. package/dist/mcp/switchboard-tools.d.ts +9 -0
  23. package/dist/mcp/switchboard-tools.js +144 -6
  24. package/dist/mcp/tools.d.ts +4 -1
  25. package/dist/mcp/tools.js +60 -15
  26. package/dist/mcp/web-child-env.d.ts +4 -1
  27. package/dist/mcp/web-child-env.js +4 -1
  28. package/dist/shared/android.d.ts +43 -0
  29. package/dist/shared/android.js +227 -19
  30. package/dist/shared/constants.d.ts +9 -4
  31. package/dist/shared/constants.js +9 -4
  32. package/dist/shared/feature-flags.d.ts +1 -0
  33. package/dist/shared/feature-flags.js +1 -0
  34. package/dist/shared/ios-logs.d.ts +10 -0
  35. package/dist/shared/ios-logs.js +91 -0
  36. package/dist/shared/ios.d.ts +25 -2
  37. package/dist/shared/ios.js +157 -3
  38. package/dist/{web → shared}/log-session.d.ts +45 -31
  39. package/dist/shared/log-session.js +300 -0
  40. package/dist/shared/radar-request-raw.d.ts +7 -0
  41. package/dist/shared/radar-request-raw.js +89 -0
  42. package/dist/shared/radar-token.d.ts +25 -0
  43. package/dist/shared/radar-token.js +164 -0
  44. package/dist/shared/stream.d.ts +3 -0
  45. package/dist/shared/stream.js +107 -15
  46. package/dist/shared/switchboard-host-store.d.ts +21 -0
  47. package/dist/shared/switchboard-host-store.js +166 -0
  48. package/dist/shared/switchboard-note.d.ts +15 -0
  49. package/dist/shared/switchboard-note.js +92 -0
  50. package/dist/shared/switchboard-report-file.d.ts +5 -0
  51. package/dist/shared/switchboard-report-file.js +26 -0
  52. package/dist/shared/switchboard-report.d.ts +20 -0
  53. package/dist/shared/switchboard-report.js +406 -0
  54. package/dist/shared/switchboard.d.ts +111 -2
  55. package/dist/shared/switchboard.js +436 -3
  56. package/dist/shared/transport.d.ts +43 -3
  57. package/dist/shared/version.d.ts +2 -0
  58. package/dist/shared/version.js +18 -0
  59. package/dist/shared/wire.d.ts +14 -1
  60. package/dist/web/install-app.d.ts +57 -8
  61. package/dist/web/install-app.js +270 -60
  62. package/dist/web/macapp/RadarApp.swift +340 -22
  63. package/dist/web/public/index.html +51 -9
  64. package/dist/web/public/next/app.js +33 -18
  65. package/dist/web/public/next/feed.js +102 -15
  66. package/dist/web/public/next/flags.js +3 -0
  67. package/dist/web/public/next/inspector.js +69 -3
  68. package/dist/web/public/next/prefs.js +5 -2
  69. package/dist/web/public/next/registry.js +18 -5
  70. package/dist/web/public/next/store.js +455 -29
  71. package/dist/web/public/next/switchboard-note.js +93 -0
  72. package/dist/web/public/next/toast.js +9 -5
  73. package/dist/web/public/next/voice-model.js +215 -35
  74. package/dist/web/public/next/voice.js +173 -18
  75. package/dist/web/server.d.ts +15 -11
  76. package/dist/web/server.js +690 -168
  77. package/dist/web/spec.d.ts +2 -1
  78. package/dist/web/spec.js +2 -1
  79. package/package.json +2 -2
  80. package/dist/web/log-session.js +0 -166
@@ -33,6 +33,11 @@ let RADAR_APP_VERSION = "unknown"
33
33
 
34
34
  let radarURL = URL(string: RADAR_URL)!
35
35
 
36
+ /// The one port this app talks to, read from the baked URL rather than baked on its own, so the port
37
+ /// it probes, the port it asks to shut down and the port it tells its own server to bind cannot
38
+ /// disagree. 8100 is WEB_PORT_DEFAULT, for a URL that names no port.
39
+ let radarPort = radarURL.port ?? 8100
40
+
36
41
  // --- BEGIN LAUNCH HELPERS ---
37
42
  // Plain functions taking their inputs as parameters, so a test can compile THIS block on its own
38
43
  // and exercise the real decisions instead of a retyped copy of them.
@@ -98,6 +103,10 @@ final class LaunchStatus {
98
103
  private let lock = NSLock()
99
104
  private var state: LaunchState = .unknown
100
105
  private var attemptInFlight = false
106
+ // Counts admitted attempts, so a notice can say which attempt left it and a load which attempt it ends.
107
+ private var attemptSerial = 0
108
+ private var notice: LaunchNotice?
109
+ private var noticeAttempt = 0
101
110
 
102
111
  func set(_ value: LaunchState) {
103
112
  lock.lock()
@@ -105,6 +114,35 @@ final class LaunchStatus {
105
114
  lock.unlock()
106
115
  }
107
116
 
117
+ /// Records the notice as the current attempt's.
118
+ func setNotice(_ value: LaunchNotice?) {
119
+ lock.lock()
120
+ notice = value
121
+ noticeAttempt = attemptSerial
122
+ lock.unlock()
123
+ }
124
+
125
+ /// The notice for the page that `attempt` loaded, handed over once, so a page that reloads itself
126
+ /// does not bring back one the person dismissed. Nil for a page some other attempt loaded, which a
127
+ /// later attempt's notice would otherwise be lost to when that attempt's own load replaces it. Nil
128
+ /// while an attempt runs too: its outcome is not settled yet.
129
+ func takeNotice(attempt: Int) -> LaunchNotice? {
130
+ lock.lock()
131
+ defer { lock.unlock() }
132
+ if attemptInFlight || attempt != noticeAttempt { return nil }
133
+ let taken = notice
134
+ notice = nil
135
+ return taken
136
+ }
137
+
138
+ /// The serial of the latest admitted attempt. Read by that attempt, which holds the gate, so no other
139
+ /// attempt can move it in between.
140
+ func currentAttempt() -> Int {
141
+ lock.lock()
142
+ defer { lock.unlock() }
143
+ return attemptSerial
144
+ }
145
+
108
146
  func get() -> LaunchState {
109
147
  lock.lock()
110
148
  defer { lock.unlock() }
@@ -118,6 +156,7 @@ final class LaunchStatus {
118
156
  defer { lock.unlock() }
119
157
  if attemptInFlight { return false }
120
158
  attemptInFlight = true
159
+ attemptSerial += 1
121
160
  return true
122
161
  }
123
162
 
@@ -127,6 +166,12 @@ final class LaunchStatus {
127
166
  lock.unlock()
128
167
  }
129
168
  }
169
+
170
+ /// Which attempt a launch was, handed back to the caller that loads the window afterwards. Nil when the
171
+ /// attempt was refused. A class so the attempt can fill it in without changing what it returns.
172
+ final class LaunchTicket {
173
+ var attempt: Int?
174
+ }
130
175
  /// Which failure a finished launch attempt actually established.
131
176
  ///
132
177
  /// Pure, and inside this block, so a test can drive all four shapes rather than pattern-matching the
@@ -183,7 +228,10 @@ enum RetryAffordance {
183
228
  /// needs saying so.
184
229
  ///
185
230
  /// Pure, so the copy is testable: hand it a state and read the page back.
186
- func failurePage(state: LaunchState, url: String, webKitError: String) -> String {
231
+ ///
232
+ /// `notice` is a line from failureNoticeText, for an attempt that asked a dashboard to stop before it
233
+ /// failed. This page is the only one that attempt gets, so the cost goes here or nowhere.
234
+ func failurePage(state: LaunchState, url: String, webKitError: String, notice: String? = nil) -> String {
187
235
  // One sentence about the controls, shared by the shapes where another attempt makes sense. Both
188
236
  // controls run the same code, so describing them as two different moves would be wrong.
189
237
  let controls = "Retry starts the server and loads the dashboard. ⌘R does the same."
@@ -209,7 +257,7 @@ func failurePage(state: LaunchState, url: String, webKitError: String) -> String
209
257
  A node upgrade usually moves it.<br>
210
258
  \(logLine)
211
259
  """
212
- return failurePageHTML(body: body, retry: .none, commandLead: repairLead, command: repair)
260
+ return failurePageHTML(body: body, retry: .none, commandLead: repairLead, command: repair, notice: notice)
213
261
 
214
262
  case .serverFailed(let node, let detail):
215
263
  let body = """
@@ -222,7 +270,8 @@ func failurePage(state: LaunchState, url: String, webKitError: String) -> String
222
270
  body: body,
223
271
  retry: .accent,
224
272
  commandLead: "If it keeps failing, run this in a terminal, then quit and reopen this app.",
225
- command: repair
273
+ command: repair,
274
+ notice: notice
226
275
  )
227
276
 
228
277
  case .unconfirmed(let node, let detail):
@@ -235,7 +284,7 @@ func failurePage(state: LaunchState, url: String, webKitError: String) -> String
235
284
  \(logLine)<br><br>
236
285
  \(controls)
237
286
  """
238
- return failurePageHTML(body: body, retry: .accent, commandLead: nil, command: nil)
287
+ return failurePageHTML(body: body, retry: .accent, commandLead: nil, command: nil, notice: notice)
239
288
 
240
289
  case .unknown, .started:
241
290
  // In practice this is the .started arm: the first launch runs before the window exists, so a state
@@ -252,7 +301,7 @@ func failurePage(state: LaunchState, url: String, webKitError: String) -> String
252
301
  \(logLine)<br><br>
253
302
  \(controls)
254
303
  """
255
- return failurePageHTML(body: body, retry: .accent, commandLead: nil, command: nil)
304
+ return failurePageHTML(body: body, retry: .accent, commandLead: nil, command: nil, notice: notice)
256
305
  }
257
306
  }
258
307
 
@@ -261,7 +310,9 @@ func failurePage(state: LaunchState, url: String, webKitError: String) -> String
261
310
  /// Render order is what happened, then each control paired with the sentence that describes it: the
262
311
  /// button under the controls sentence, the command under its lead. An earlier version put the command
263
312
  /// block between a label and the button it named, so the page read label, label, thing, thing.
264
- func failurePageHTML(body: String, retry: RetryAffordance, commandLead: String?, command: String?) -> String {
313
+ func failurePageHTML(
314
+ body: String, retry: RetryAffordance, commandLead: String?, command: String?, notice: String? = nil
315
+ ) -> String {
265
316
  let retryButton = retry == .none
266
317
  ? ""
267
318
  : """
@@ -284,12 +335,19 @@ func failurePageHTML(body: String, retry: RetryAffordance, commandLead: String?,
284
335
  border-radius:6px;font:13px ui-monospace,SFMono-Regular,Menlo,monospace;color:#e8f0f8;\
285
336
  text-align:left;user-select:all;overflow-wrap:anywhere">\(htmlEscape($0))</div>
286
337
  """ } ?? ""
338
+ // Straight after what happened, since it is part of it, and escaped: it carries a version string that
339
+ // came from another process. The body ends on what Retry does, so the line opens with "Earlier" to
340
+ // read as what came before the failure rather than after the button.
341
+ let noticeLine = notice.map { """
342
+ <div style="margin-top:1em;color:#e8b86a;line-height:1.6;overflow-wrap:anywhere">\(htmlEscape($0))</div>
343
+ """ } ?? ""
287
344
  return """
288
345
  <html><body style="background:#0b0f14;color:#e8f0f8;font:14px -apple-system,sans-serif;\
289
346
  display:flex;align-items:center;justify-content:center;height:100vh;margin:0">
290
347
  <div style="max-width:34em;text-align:center">
291
348
  <div style="font-size:15px;font-weight:600;margin-bottom:.6em">Could not reach the Radar dashboard</div>
292
349
  <div style="color:#e8f0f8;line-height:1.6;overflow-wrap:anywhere">\(body)</div>
350
+ \(noticeLine)
293
351
  \(retryButton)
294
352
  \(lead)
295
353
  \(commandBlock)
@@ -515,6 +573,147 @@ func portTakeoverDecision(
515
573
  }
516
574
  }
517
575
 
576
+ /// Who held a port this app kept or took, as the page notice names them. Only the two claims a notice
577
+ /// can describe: an agent session has its own kind, and no claim at all needs no notice.
578
+ enum NoticeClaimant {
579
+ case window
580
+ case unnamed
581
+ }
582
+
583
+ /// A launch or refresh outcome the page has to explain, because the version badge did not move, or
584
+ /// moved at somebody else's expense. Each carries the version still serving, or asked to stop.
585
+ enum LaunchNotice: Equatable {
586
+ /// Kept, because an agent session is using it. A refresh does not take it either.
587
+ case sessionHolds(theirs: String)
588
+ /// Kept on launch, because someone else has it. A refresh takes it.
589
+ case otherHolds(theirs: String, who: NoticeClaimant)
590
+ /// A refresh asked it to stop although someone else had it.
591
+ case tookFromOther(theirs: String, who: NoticeClaimant)
592
+ /// Asked to stop, and still serving, so this app declined to race it.
593
+ case stillStopping(theirs: String)
594
+ /// A refresh asked it to stop although someone else had it, and then this version did not come up,
595
+ /// so nothing confirmed that it stopped.
596
+ case stopUnconfirmed(theirs: String, who: NoticeClaimant)
597
+ }
598
+
599
+ /// The claimant a take overrides, or nil when the take cost nobody anything the app knows of.
600
+ func overriddenClaimant(_ use: DashboardUse) -> NoticeClaimant? {
601
+ switch use {
602
+ case .tab: return .window
603
+ case .someoneUnnamed: return .unnamed
604
+ // An agent session is never taken (see portTakeoverDecision), and no claim is nobody to name.
605
+ case .mcp, .no, .cannotTell: return nil
606
+ }
607
+ }
608
+
609
+ /// The notice text: one sentence on what happened, one on what to do. Follows the launch log lines,
610
+ /// shorter, because the page is read at a glance and the log is where the detail lives. Worded for a
611
+ /// launch and a refresh alike, since every kind but a take can follow either.
612
+ ///
613
+ /// The claims are as strong as what the probe saw and no stronger. A session is a dashboard that
614
+ /// something with no tab wrote to in the last five minutes (a view, an /enable), or one no window has
615
+ /// opened yet (see inUseReason in server.ts). The copy names only the first: this window's own poll
616
+ /// counts as an opening, so once it loads that dashboard the second no longer holds, and "idle" is as
617
+ /// precise as the page can be about which writes count. A window is a tab that polled in the last 15
618
+ /// seconds, which can be one closed since. An unnamed claim is what an older dashboard reports for any
619
+ /// tab, this app's own window included, because it predates the header that lets a window leave
620
+ /// itself out (see portTakeoverDecision). An unconfirmed stop reaches the dashboard page only when
621
+ /// something answered after the attempt gave up, which can be the version asked to stop.
622
+ func launchNoticeText(_ notice: LaunchNotice, mine: String) -> String {
623
+ switch notice {
624
+ case .sessionHolds(let theirs):
625
+ return "This window shows Radar \(theirs), not \(mine), because an agent session is using that dashboard. Press ⌘R to try \(mine) once that session has been idle for about five minutes."
626
+ case .otherHolds(let theirs, .window):
627
+ return "This window shows Radar \(theirs), not \(mine), because another window has that dashboard open. Press ⌘R to try to take it for \(mine): that window loses its page, and both windows lose the device pin, the logcat ring and the pulled databases, since those belong to that dashboard."
628
+ case .otherHolds(let theirs, .unnamed):
629
+ // An older server with no kind header lands here too, and its holder can be an agent session with
630
+ // no page, so the cost names a session rather than a page.
631
+ return "This window shows Radar \(theirs), not \(mine), because that dashboard says someone is using it without saying who. Press ⌘R to try to take it for \(mine): whoever is using it loses that dashboard, and this window loses the device pin, the logcat ring and the pulled databases."
632
+ case .tookFromOther(let theirs, .window):
633
+ return "This refresh asked Radar \(theirs) to stop so \(mine) could serve, although a window had it open in the last 15 seconds. If that window is yours, reload it to reconnect to \(mine)."
634
+ case .tookFromOther(let theirs, .unnamed):
635
+ return "This refresh asked Radar \(theirs) to stop so \(mine) could serve, although it said someone was using it without saying who, which can be this window, since an older dashboard cannot leave it out. If someone else was using it, they can reload to reach \(mine)."
636
+ case .stillStopping(let theirs):
637
+ return "Radar \(theirs) was asked to stop so \(mine) could serve, and it is still finishing, which a long screen recording can do. Press ⌘R in a few seconds to try \(mine)."
638
+ case .stopUnconfirmed(let theirs, _):
639
+ return "This refresh asked Radar \(theirs) to stop so \(mine) could serve, and \(mine) did not answer in time, so this page may still be Radar \(theirs). Press ⌘R to try \(mine), and whoever else was using Radar \(theirs) can reload once \(mine) serves."
640
+ }
641
+ }
642
+
643
+ /// The notice line for the failure page, when an attempt that asked a dashboard to stop then could not
644
+ /// start this version. Only a take has a cost worth saying there: every other kind describes what the
645
+ /// dashboard page shows, which a failure page does not. Nil for those.
646
+ func failureNoticeText(_ notice: LaunchNotice) -> String? {
647
+ switch notice {
648
+ case .tookFromOther(let theirs, .window), .stopUnconfirmed(let theirs, .window):
649
+ return "Earlier, this app asked Radar \(theirs) to stop, although a window had it open in the last 15 seconds. If that window is yours, reload it once the dashboard is back."
650
+ case .tookFromOther(let theirs, .unnamed), .stopUnconfirmed(let theirs, .unnamed):
651
+ return "Earlier, this app asked Radar \(theirs) to stop, although it said someone was using it without saying who, which can be this window, since an older dashboard cannot leave it out. If someone else was using it, they can reload once the dashboard is back."
652
+ case .sessionHolds, .otherHolds, .stillStopping:
653
+ return nil
654
+ }
655
+ }
656
+
657
+ /// Whether a loaded page is the dashboard, by scheme, host and port. The failure page is loaded as an
658
+ /// HTML string with no base URL, so it never matches, and nothing the page contains is consulted.
659
+ func isDashboardPage(_ url: URL?, dashboard: URL) -> Bool {
660
+ guard let url = url else { return false }
661
+ return url.scheme == dashboard.scheme && url.host == dashboard.host && url.port == dashboard.port
662
+ }
663
+
664
+ /// The page side of the notice, run by the app in whatever dashboard is loaded. Self-contained because
665
+ /// every page that gets a notice is served by an older dashboard than this app, which has no code of
666
+ /// its own to call. Replaces any strip already there, so a second delivery never stacks two, and sets
667
+ /// the text with textContent, so the text is never markup. A raw string so the JS reaches the page
668
+ /// byte for byte, with no Swift escapes or interpolation in between.
669
+ let launchNoticeFunctionJS = #"""
670
+ function (text) {
671
+ var id = "radar-launch-notice";
672
+ var old = document.getElementById(id);
673
+ if (old && old.parentNode) old.parentNode.removeChild(old);
674
+ var strip = document.createElement("div");
675
+ strip.id = id;
676
+ strip.setAttribute("role", "status");
677
+ // Centred by margins on a fit-content box, so it takes the width its text needs up to the cap. A
678
+ // left:50% box with no right edge is only allowed half the viewport, and wraps the text to four lines
679
+ // at the window's minimum width. Above the page's modal (55) and below its alert banner (60), which is
680
+ // an urgent watch alert the person can dismiss and so wins while it shows. The banner is about 40px
681
+ // tall from the top edge, so while it shows it covers this strip's first lines and a longer strip
682
+ // shows only its lower part below it. That is accepted: the banner changes height and comes and goes
683
+ // on its own, and dismissing it brings the whole strip back. Colors from the page's own
684
+ // theme variables, so the text stays readable on the light theme's white surface.
685
+ strip.style.cssText = "position:fixed;top:8px;left:0;right:0;margin:0 auto;width:fit-content;z-index:58;" +
686
+ "display:flex;gap:12px;align-items:flex-start;max-width:min(720px, calc(100% - 32px));" +
687
+ "padding:10px 14px;border-radius:8px;background:var(--surface, #1f2a36);color:var(--text, #e6edf3);" +
688
+ "font:13px/1.45 -apple-system,system-ui,sans-serif;box-shadow:0 4px 16px rgba(0,0,0,.35)";
689
+ var message = document.createElement("span");
690
+ var dismiss = document.createElement("button");
691
+ dismiss.type = "button";
692
+ dismiss.setAttribute("aria-label", "Dismiss");
693
+ dismiss.textContent = "×";
694
+ dismiss.style.cssText = "background:none;border:0;color:inherit;font-size:16px;line-height:1;cursor:pointer;padding:0 2px";
695
+ dismiss.onclick = function () {
696
+ if (strip.parentNode) strip.parentNode.removeChild(strip);
697
+ };
698
+ strip.appendChild(message);
699
+ strip.appendChild(dismiss);
700
+ (document.body || document.documentElement).appendChild(strip);
701
+ // The text goes in after the status node is in the page. A live region inserted with its text already
702
+ // set is not a change, so a screen reader may never announce it.
703
+ message.textContent = text;
704
+ }
705
+ """#
706
+
707
+ /// The script that shows `text` in the page. The text goes in as a JSON string literal, an argument to
708
+ /// the function above, never spliced into its source. Nil if the text cannot be encoded, which a Swift
709
+ /// String always can; the caller then shows nothing rather than a broken script.
710
+ func launchNoticeScript(_ text: String) -> String? {
711
+ guard let data = try? JSONEncoder().encode(text), let literal = String(data: data, encoding: .utf8) else {
712
+ return nil
713
+ }
714
+ return "(\(launchNoticeFunctionJS))(\(literal));"
715
+ }
716
+
518
717
  /// How long the children get to leave on their own after being asked, before they are signalled. Short
519
718
  /// because the app holds its own quit open while this runs (see `applicationShouldTerminate`), and the
520
719
  /// person has already asked it to go away.
@@ -759,7 +958,7 @@ func appendLaunchLog(_ line: String) {
759
958
  /// The dashboard's /spec over LOOPBACK BY ADDRESS. `radarURL` stays `localhost` for the WebView, but a
760
959
  /// name has to be resolved and a proxy can be consulted, and neither belongs in a health check of a
761
960
  /// server on this machine. bin.ts's own adopt check binds and probes 127.0.0.1 for the same reason.
762
- let probeURL = URL(string: "http://127.0.0.1:\(radarURL.port ?? 8100)/spec")!
961
+ let probeURL = URL(string: "http://127.0.0.1:\(radarPort)/spec")!
763
962
 
764
963
  /// The page the window loads: the dashboard, carrying the presence id this app generated, so the page
765
964
  /// polls under an id this app can then ask the server to leave out.
@@ -846,7 +1045,7 @@ func dashboardProbe(deciding decision: InUseDecision = .take) -> DashboardProbe
846
1045
  }
847
1046
 
848
1047
  /// Same loopback-by-address reasoning as probeURL.
849
- let shutdownURL = URL(string: "http://127.0.0.1:\(radarURL.port ?? 8100)/shutdown")!
1048
+ let shutdownURL = URL(string: "http://127.0.0.1:\(radarPort)/shutdown")!
850
1049
 
851
1050
  /// How long a stale dashboard gets to go away after being asked. Its stop is graceful (it finalizes a
852
1051
  /// live screen recording before exiting), so it is not instant, and it is bounded because the fallback
@@ -933,7 +1132,7 @@ func stopStaleDashboard() -> StalePortOutcome {
933
1132
 
934
1133
  /// Start the dashboard server if it is not already up, then wait for it to answer.
935
1134
  ///
936
- /// The server auto-closes 5 minutes after its last tab closes, so on a cold Mac this is the normal
1135
+ /// The server auto-closes about 6 minutes after its last tab closes, so on a cold Mac this is the normal
937
1136
  /// path, not an edge case. Waiting (rather than sleeping a fixed guess) matters because a cold node
938
1137
  /// start ranges from ~300ms to several seconds on a loaded machine, and loading the view too early
939
1138
  /// renders a WebKit error page the user has to manually reload past.
@@ -955,11 +1154,14 @@ enum LaunchOutcome {
955
1154
  }
956
1155
 
957
1156
  @discardableResult
958
- func ensureDashboardRunning(respectInUse: Bool = true) -> LaunchOutcome {
1157
+ func ensureDashboardRunning(respectInUse: Bool = true, ticket: LaunchTicket? = nil) -> LaunchOutcome {
959
1158
  // One at a time. A second attempt would spawn a second server racing the same port, and its result
960
1159
  // would overwrite the first one's, which is what the page is about to read.
961
1160
  guard LaunchStatus.shared.beginAttempt() else { return .refused }
962
1161
  defer { LaunchStatus.shared.finishAttempt() }
1162
+ // Only the latest attempt speaks to the page, so an earlier attempt's notice goes before this one decides.
1163
+ LaunchStatus.shared.setNotice(nil)
1164
+ ticket?.attempt = LaunchStatus.shared.currentAttempt()
963
1165
 
964
1166
  // Resolved BEFORE anything is stopped, because it is what decides whether this app can put a
965
1167
  // dashboard back. Doing it after the takeover cost a user their working dashboard: on a Mac whose
@@ -968,6 +1170,31 @@ func ensureDashboardRunning(respectInUse: Bool = true) -> LaunchOutcome {
968
1170
  // offers no Retry. Taking the port is only defensible when there is something to put on it.
969
1171
  let interpreter = resolveNodePath(RADAR_NODE)
970
1172
 
1173
+ // A take whose outcome this attempt could not see, settled by whichever dashboard answers the port
1174
+ // afterwards (see settleTake below). Nil when there is nothing left to settle.
1175
+ var unsettledTake: (theirs: String, who: NoticeClaimant?)?
1176
+ // Our version answering means the take happened. The one asked to stop answering means it is still
1177
+ // serving, the stillServing arm's situation, so it gets that notice. Another version says nothing.
1178
+ // Nil is the attempt failing with nobody answering: the ask to stop still happened and may have cost
1179
+ // somebody their dashboard, so the claimant is named, but as unconfirmed, because the old version
1180
+ // can still answer this attempt's own load and must not be called gone on that page.
1181
+ func settleTake(_ probe: DashboardProbe?) {
1182
+ guard let take = unsettledTake else { return }
1183
+ switch probe {
1184
+ case .answering(let version, _)?:
1185
+ if version == RADAR_APP_VERSION {
1186
+ if let who = take.who { LaunchStatus.shared.setNotice(.tookFromOther(theirs: take.theirs, who: who)) }
1187
+ } else if version == take.theirs {
1188
+ LaunchStatus.shared.setNotice(.stillStopping(theirs: take.theirs))
1189
+ }
1190
+ case nil:
1191
+ if let who = take.who { LaunchStatus.shared.setNotice(.stopUnconfirmed(theirs: take.theirs, who: who)) }
1192
+ case .notListening?, .couldNotTell?:
1193
+ return
1194
+ }
1195
+ unsettledTake = nil
1196
+ }
1197
+
971
1198
  // No state is written on entry. Every exit below records one, so the only way to observe .unknown
972
1199
  // is before the first attempt ever ran, which is exactly what it means.
973
1200
  //
@@ -1006,12 +1233,17 @@ func ensureDashboardRunning(respectInUse: Bool = true) -> LaunchOutcome {
1006
1233
  // replacement here would be a promise another branch refuses.
1007
1234
  switch inUse {
1008
1235
  case .mcp:
1009
- appendLaunchLog("launch: the dashboard on the port is Radar \(theirs), older than this app, but an agent session (Claude Code) is using it. Leaving it alone, and a refresh will not take it either. This window shows Radar \(theirs) until that session has left the port alone for five minutes, or, if no window has ever opened that dashboard, until the session stops it.")
1236
+ appendLaunchLog("launch: the dashboard on the port is Radar \(theirs), older than this app, but an agent session (Claude Code) is using it. Leaving it alone, and a refresh will not take it either for now. This window shows Radar \(theirs). A refresh can take it once that session has been idle for about five minutes.")
1237
+ LaunchStatus.shared.setNotice(.sessionHolds(theirs: theirs))
1010
1238
  case .tab:
1011
1239
  appendLaunchLog("launch: the dashboard on the port is Radar \(theirs), older than this app, but another window has it open. Leaving it alone. A refresh tries to take it, and that costs whoever has that window their page, along with any pulled databases, the device pin and the logcat ring.")
1240
+ LaunchStatus.shared.setNotice(.otherHolds(theirs: theirs, who: .window))
1012
1241
  case .someoneUnnamed:
1013
1242
  appendLaunchLog("launch: the dashboard on the port is Radar \(theirs), older than this app, and says someone is using it without saying who. Leaving it alone. A refresh tries to take it, at the same cost to whoever that is.")
1243
+ LaunchStatus.shared.setNotice(.otherHolds(theirs: theirs, who: .unnamed))
1014
1244
  case .no, .cannotTell:
1245
+ // No notice: this combination is a bug in this app, and a page cannot offer anything to do
1246
+ // about it. The log line below is where it gets reported.
1015
1247
  // Not reachable, since keepInUse is only answered for a claim. Logged rather than skipped so
1016
1248
  // that if the decision and the claim ever disagree, the log says so instead of going quiet, and
1017
1249
  // worded so the reader knows the fault is here rather than on their machine.
@@ -1031,9 +1263,14 @@ func ensureDashboardRunning(respectInUse: Bool = true) -> LaunchOutcome {
1031
1263
  case .mcp: claim = "an agent session is using it, which should have kept it, so this is a bug in this app"
1032
1264
  }
1033
1265
  appendLaunchLog("launch: the dashboard on the port is Radar \(theirs) and this app is \(RADAR_APP_VERSION), and \(claim). Asking it to stop so this version can serve.")
1266
+ // Set when the freed arm sees the port free, and by settleTake when the couldNotTell arm could
1267
+ // not: as a take once this version answers, or as an unconfirmed stop when the attempt then
1268
+ // fails. Silent when nobody claimed the port: the badge moves and nobody known lost anything.
1269
+ let overridden = overriddenClaimant(inUse)
1034
1270
  switch stopStaleDashboard() {
1035
1271
  case .freed:
1036
1272
  appendLaunchLog("launch: Radar \(theirs) stopped and the port is free. Starting \(RADAR_APP_VERSION).")
1273
+ if let who = overridden { LaunchStatus.shared.setNotice(.tookFromOther(theirs: theirs, who: who)) }
1037
1274
  case .stillServing:
1038
1275
  // Still bound after being asked, which a long recording finalize can do, since the server
1039
1276
  // closes its listener last. Spawning into that costs the user the thing they still had: our
@@ -1042,12 +1279,16 @@ func ensureDashboardRunning(respectInUse: Bool = true) -> LaunchOutcome {
1042
1279
  // stale dashboard leaves them exactly where they were, which is worse than the upgrade and
1043
1280
  // better than a broken window.
1044
1281
  appendLaunchLog("launch: Radar \(theirs) was asked to stop and is still serving, which a long screen recording can do. Leaving it alone rather than racing it for the port.")
1282
+ LaunchStatus.shared.setNotice(.stillStopping(theirs: theirs))
1045
1283
  LaunchStatus.shared.set(.started)
1046
1284
  return .started
1047
1285
  case .couldNotTell(let why):
1048
1286
  // Not the same as still serving. The port may well be free, and the spawned child's own
1049
1287
  // EADDRINUSE path settles it either way, with the version note it already prints.
1050
1288
  appendLaunchLog("launch: Radar \(theirs) was asked to stop and this app could not tell whether it went (\(why)). Starting \(RADAR_APP_VERSION) and letting it settle who owns the port.")
1289
+ // No notice yet. Saying the take happened is only true once this version is the one serving,
1290
+ // and if the old one keeps the port the child's EADDRINUSE leaves it serving.
1291
+ unsettledTake = (theirs: theirs, who: overridden)
1051
1292
  }
1052
1293
  }
1053
1294
  }
@@ -1058,6 +1299,9 @@ func ensureDashboardRunning(respectInUse: Bool = true) -> LaunchOutcome {
1058
1299
  LaunchStatus.shared.set(.nodeMissing(baked: RADAR_NODE))
1059
1300
  appendLaunchLog("launch: node was not at the baked path \(RADAR_NODE). The dashboard was not started.")
1060
1301
  NSLog("radar: node was not at the baked path \(RADAR_NODE)")
1302
+ // A take needs an interpreter, so nothing is unsettled here today. Settled anyway, like every
1303
+ // failure below, so no failure can drop one.
1304
+ settleTake(nil)
1061
1305
  return .failed
1062
1306
  }
1063
1307
 
@@ -1065,9 +1309,12 @@ func ensureDashboardRunning(respectInUse: Bool = true) -> LaunchOutcome {
1065
1309
  task.executableURL = URL(fileURLWithPath: node)
1066
1310
  task.arguments = [RADAR_WEB_BIN]
1067
1311
  // SLACK_RADAR_NO_OPEN stops the server from opening a browser tab of its own, which would put a
1068
- // second copy of the dashboard on screen next to this window.
1312
+ // second copy of the dashboard on screen next to this window. SLACK_RADAR_WEB_PORT because a
1313
+ // Finder launch inherits none, and without it the server binds the default port while this app
1314
+ // probes the one it was installed against.
1069
1315
  var env = ProcessInfo.processInfo.environment
1070
1316
  env["SLACK_RADAR_NO_OPEN"] = "1"
1317
+ env["SLACK_RADAR_WEB_PORT"] = String(radarPort)
1071
1318
  task.environment = env
1072
1319
  // Detach stdio to a log rather than inheriting: an inherited pipe nobody drains fills its buffer
1073
1320
  // and blocks the server once it has logged enough.
@@ -1088,6 +1335,7 @@ func ensureDashboardRunning(respectInUse: Bool = true) -> LaunchOutcome {
1088
1335
  LaunchStatus.shared.set(.serverFailed(node: node, detail: error.localizedDescription))
1089
1336
  appendLaunchLog("launch: the dashboard server did not come up with \(node). \(error.localizedDescription)")
1090
1337
  NSLog("radar: the dashboard server did not come up with \(node). \(error.localizedDescription)")
1338
+ settleTake(nil)
1091
1339
  return .failed
1092
1340
  }
1093
1341
 
@@ -1100,6 +1348,7 @@ func ensureDashboardRunning(respectInUse: Bool = true) -> LaunchOutcome {
1100
1348
  while Date() < deadline {
1101
1349
  let probe = dashboardProbe()
1102
1350
  if case .answering = probe {
1351
+ settleTake(probe)
1103
1352
  LaunchStatus.shared.set(.started)
1104
1353
  return .started
1105
1354
  }
@@ -1113,6 +1362,7 @@ func ensureDashboardRunning(respectInUse: Bool = true) -> LaunchOutcome {
1113
1362
  // otherwise leave a failure recorded behind a window that loads perfectly well.
1114
1363
  let finalProbe = dashboardProbe()
1115
1364
  if case .answering = finalProbe {
1365
+ settleTake(finalProbe)
1116
1366
  LaunchStatus.shared.set(.started)
1117
1367
  return .started
1118
1368
  }
@@ -1141,6 +1391,7 @@ func ensureDashboardRunning(respectInUse: Bool = true) -> LaunchOutcome {
1141
1391
  default:
1142
1392
  break
1143
1393
  }
1394
+ settleTake(nil)
1144
1395
  return .failed
1145
1396
  }
1146
1397
 
@@ -1166,6 +1417,11 @@ func triggerSelfHealCheck() {
1166
1417
  let task = Process()
1167
1418
  task.executableURL = URL(fileURLWithPath: node)
1168
1419
  task.arguments = [RADAR_MCP_BIN, "install-app", "--self-heal-precheck"]
1420
+ // The rebuild this can trigger inherits this environment and bakes its port from it, so without
1421
+ // the baked port a Finder launch that self-heals would move a non-default install to the default.
1422
+ var env = ProcessInfo.processInfo.environment
1423
+ env["SLACK_RADAR_WEB_PORT"] = String(radarPort)
1424
+ task.environment = env
1169
1425
  // Same log file ensureDashboardRunning() writes to, so the outcome shows up next to the
1170
1426
  // dashboard's own launch log. Not inherited stdio: an unread pipe can block the child.
1171
1427
  if let handle = radarLogHandle() {
@@ -1180,9 +1436,29 @@ func triggerSelfHealCheck() {
1180
1436
  }
1181
1437
  }
1182
1438
 
1439
+ /// The launch attempt that runs before the window exists (see the bottom of this file), whose load is
1440
+ /// the window's first.
1441
+ let firstLaunch = LaunchTicket()
1442
+
1183
1443
  class AppDelegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKDownloadDelegate, WKScriptMessageHandler {
1184
1444
  var window: NSWindow!
1185
1445
  var webView: WKWebView!
1446
+ // The load that ended a launch attempt, and which attempt that was: the only navigation that
1447
+ // attempt's notice may go to. Main thread only. An older navigation can finish after a newer attempt
1448
+ // is done and before its load starts, and handing it the notice would lose it to the reload that
1449
+ // follows, so a notice goes only to a load from the attempt that left it (see takeNotice).
1450
+ private var noticeTarget: (navigation: WKNavigation, attempt: Int)?
1451
+
1452
+ /// Loads the dashboard as the end of `ticket`'s attempt.
1453
+ private func loadDashboard(after ticket: LaunchTicket) {
1454
+ let navigation = webView.load(URLRequest(url: dashboardPageURL))
1455
+ if let navigation = navigation, let attempt = ticket.attempt {
1456
+ noticeTarget = (navigation: navigation, attempt: attempt)
1457
+ } else {
1458
+ // No load to deliver to, so nothing may keep claiming the notice for the one before it.
1459
+ noticeTarget = nil
1460
+ }
1461
+ }
1186
1462
  // Whether a quit deferral has been started, and whether it has been released (see beginQuitDeferral
1187
1463
  // and releaseQuit). One lock over both, because the three things that touch them run on different
1188
1464
  // queues: a second Cmd+Q on the main thread, the stop work finishing on a background queue, and the
@@ -1255,7 +1531,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKDown
1255
1531
  // Minimum that keeps the feed's virtualized columns usable rather than clipped.
1256
1532
  window.minSize = NSSize(width: 900, height: 600)
1257
1533
 
1258
- webView.load(URLRequest(url: dashboardPageURL))
1534
+ loadDashboard(after: firstLaunch)
1259
1535
  NSApp.activate(ignoringOtherApps: true)
1260
1536
  }
1261
1537
 
@@ -1558,13 +1834,25 @@ class AppDelegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKDown
1558
1834
  /// Exception: the cancellation from diverting a response to a download also lands here, and
1559
1835
  /// that one is not a failure at all -- see pendingDownloadInterruptions above.
1560
1836
  func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
1837
+ // Before the token pop: a diversion reports its own error, not a cancel, so a cancel must not spend
1838
+ // the token that error still needs.
1839
+ if isReplacedLoad(error) { return }
1561
1840
  // Any pending token proves SOME diversion is in flight; this callback has no way to tell
1562
1841
  // which one it belongs to (see pendingDownloadInterruptions above), so popping any one token
1563
1842
  // is correct -- they are fungible signals, not identity-correlated to a specific navigation.
1564
1843
  if pendingDownloadInterruptions.popFirst() != nil {
1565
1844
  return
1566
1845
  }
1567
- showLoadFailure(error)
1846
+ showLoadFailure(error, navigation: navigation)
1847
+ }
1848
+
1849
+ /// A load cancelled because a newer one replaced it, which is how every Cmd+R and Retry ends the load
1850
+ /// before it. Not a failure: rendering the failure page for it would cancel that newer load in turn,
1851
+ /// and hand the newer attempt's notice to a failure page while its server is up. Every cancel is
1852
+ /// read this way, since nothing in this app cancels a load without starting a newer one.
1853
+ private func isReplacedLoad(_ error: Error) -> Bool {
1854
+ let nsError = error as NSError
1855
+ return nsError.domain == NSURLErrorDomain && nsError.code == NSURLErrorCancelled
1568
1856
  }
1569
1857
 
1570
1858
  func webView(
@@ -1572,17 +1860,46 @@ class AppDelegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKDown
1572
1860
  didFailProvisionalNavigation navigation: WKNavigation!,
1573
1861
  withError error: Error
1574
1862
  ) {
1863
+ if isReplacedLoad(error) { return }
1575
1864
  if pendingDownloadInterruptions.popFirst() != nil {
1576
1865
  return
1577
1866
  }
1578
- showLoadFailure(error)
1867
+ showLoadFailure(error, navigation: navigation)
1868
+ }
1869
+
1870
+ /// The latest attempt's notice, for the page `navigation` produced, or nil when that navigation is not
1871
+ /// the one the attempt started. The one place a notice is taken, so the dashboard and the failure page
1872
+ /// cannot each claim it by a different rule.
1873
+ private func claimNotice(for navigation: WKNavigation?) -> LaunchNotice? {
1874
+ guard let target = noticeTarget, let navigation = navigation, navigation === target.navigation else { return nil }
1875
+ noticeTarget = nil
1876
+ return LaunchStatus.shared.takeNotice(attempt: target.attempt)
1877
+ }
1878
+
1879
+ /// Puts the latest attempt's notice, if it left one, into the dashboard once it has loaded. This covers
1880
+ /// the first launch and every Cmd+R and Retry, since each of them ends by loading dashboardPageURL.
1881
+ func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
1882
+ guard isDashboardPage(webView.url, dashboard: radarURL),
1883
+ let notice = claimNotice(for: navigation),
1884
+ let script = launchNoticeScript(launchNoticeText(notice, mine: RADAR_APP_VERSION)) else { return }
1885
+ // The notice is the only place this outcome reaches the page, so a script that fails in it is logged
1886
+ // rather than dropped. An older dashboard's page is the one it runs in, and that is what can break it.
1887
+ webView.evaluateJavaScript(script) { _, error in
1888
+ if let error = error {
1889
+ appendLaunchLog("launch: could not show the notice in the page. \(error.localizedDescription)")
1890
+ }
1891
+ }
1579
1892
  }
1580
1893
 
1581
1894
  /// Renders whatever the last launch attempt established. The page itself is built outside this
1582
- /// class (see failurePage) so its copy can be rendered and read back by a test.
1583
- private func showLoadFailure(_ error: Error) {
1895
+ /// class (see failurePage) so its copy can be rendered and read back by a test. A take the attempt
1896
+ /// made on its way to failing goes on it too, since the failure page is not the dashboard and the
1897
+ /// notice would otherwise never be shown.
1898
+ private func showLoadFailure(_ error: Error, navigation: WKNavigation?) {
1899
+ let notice = claimNotice(for: navigation).flatMap(failureNoticeText)
1584
1900
  webView.loadHTMLString(
1585
- failurePage(state: LaunchStatus.shared.get(), url: RADAR_URL, webKitError: error.localizedDescription),
1901
+ failurePage(
1902
+ state: LaunchStatus.shared.get(), url: RADAR_URL, webKitError: error.localizedDescription, notice: notice),
1586
1903
  baseURL: nil
1587
1904
  )
1588
1905
  }
@@ -1595,6 +1912,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKDown
1595
1912
  /// app, including the control that was just used.
1596
1913
  func retryLoad() {
1597
1914
  DispatchQueue.global().async {
1915
+ let ticket = LaunchTicket()
1598
1916
  // Only a REFUSED attempt skips the reload: another one is mid-flight and will load the window
1599
1917
  // itself, and reloading now would fail against a server that is still starting and re-render the
1600
1918
  // earlier attempt's page. A failed attempt reloads, because it just learned the cause and the
@@ -1603,9 +1921,9 @@ class AppDelegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKDown
1603
1921
  // respectInUse: false, because this is the user asking. If this app adopted a stale dashboard,
1604
1922
  // its own window is the live tab that dashboard reports, so honouring the in-use guard here would
1605
1923
  // refuse the person pressing the button on behalf of the person pressing the button.
1606
- if case .refused = ensureDashboardRunning(respectInUse: false) { return }
1924
+ if case .refused = ensureDashboardRunning(respectInUse: false, ticket: ticket) { return }
1607
1925
  DispatchQueue.main.async {
1608
- self.webView.load(URLRequest(url: dashboardPageURL))
1926
+ self.loadDashboard(after: ticket)
1609
1927
  }
1610
1928
  }
1611
1929
  }
@@ -1655,8 +1973,8 @@ class ReloadingApplication: NSApplication {
1655
1973
  }
1656
1974
 
1657
1975
  // Start the server BEFORE the window exists so the first load lands on a live port instead of an
1658
- // error page the user has to reload past.
1659
- ensureDashboardRunning()
1976
+ // error page the user has to reload past. The ticket tells the window's first load which attempt it ends.
1977
+ ensureDashboardRunning(ticket: firstLaunch)
1660
1978
  // Spawned and forgotten: fixes today's staleness for the NEXT launch, never this one.
1661
1979
  triggerSelfHealCheck()
1662
1980