@slack/radar-mcp 1.19.0 → 1.20.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.
@@ -23,27 +23,912 @@ import WebKit
23
23
  let RADAR_URL = "http://localhost:8100"
24
24
  let RADAR_NODE = "/usr/bin/env"
25
25
  let RADAR_WEB_BIN = "node"
26
- let RADAR_NPX = "/usr/bin/env"
27
26
  let RADAR_MCP_BIN = "node"
27
+ // The version this app was built from, used to tell a stale dashboard on the port from a current one.
28
+ // "unknown" is the honest default for a copy compiled straight from the repo: it has no published
29
+ // version to claim, and an unparseable version is treated as "cannot tell", so such a build never
30
+ // decides another dashboard is out of date.
31
+ let RADAR_APP_VERSION = "unknown"
28
32
  // --- END INSTALL CONFIG ---
29
33
 
30
34
  let radarURL = URL(string: RADAR_URL)!
31
35
 
32
- /// Best-effort check that the dashboard is listening. /spec is instant (no device round-trip) and
33
- /// unique to Radar, the same fingerprint the shell launcher and bin.ts's adopt path use.
34
- func dashboardAlive() -> Bool {
35
- var request = URLRequest(url: radarURL.appendingPathComponent("spec"))
36
+ // --- BEGIN LAUNCH HELPERS ---
37
+ // Plain functions taking their inputs as parameters, so a test can compile THIS block on its own
38
+ // and exercise the real decisions instead of a retyped copy of them.
39
+
40
+ /// The baked interpreter, when it is really there and really a file. nil means it is gone, which is a
41
+ /// launch failure worth naming rather than a dashboard that silently never starts.
42
+ ///
43
+ /// A directory is skipped explicitly, because isExecutableFile reports true for one (a directory's
44
+ /// execute bit means searchable) and launching it would fail with a far more confusing error.
45
+ func resolveNodePath(_ baked: String) -> String? {
46
+ let fm = FileManager.default
47
+ var isDirectory: ObjCBool = false
48
+ guard fm.fileExists(atPath: baked, isDirectory: &isDirectory), !isDirectory.boolValue else { return nil }
49
+ return fm.isExecutableFile(atPath: baked) ? baked : nil
50
+ }
51
+
52
+ /// Escape text for the failure page. Its reasons carry filesystem paths, and a path may contain `<`
53
+ /// or `&`, which would otherwise reach the page as markup rather than as characters. Quotes are
54
+ /// escaped too: nothing path-derived lands in an attribute today, and the page template mixes
55
+ /// element and attribute contexts closely enough that it should not need re-auditing to stay safe.
56
+ func htmlEscape(_ text: String) -> String {
57
+ var out = text.replacingOccurrences(of: "&", with: "&amp;")
58
+ out = out.replacingOccurrences(of: "<", with: "&lt;")
59
+ out = out.replacingOccurrences(of: ">", with: "&gt;")
60
+ out = out.replacingOccurrences(of: "\"", with: "&quot;")
61
+ out = out.replacingOccurrences(of: "'", with: "&#39;")
62
+ return out
63
+ }
64
+
65
+ /// What the last attempt to start the dashboard established.
66
+ ///
67
+ /// The window's own error page can only ever say the URL did not answer, which is the symptom of
68
+ /// every cause. This carries the cause when there is one, so a missing interpreter reads as a
69
+ /// missing interpreter and names the command that repairs it.
70
+ ///
71
+ /// Three states rather than two: an attempt that has not finished yet knows nothing, and that is not
72
+ /// the same as knowing nothing went wrong. Collapsing the two would let a page rendered mid-attempt
73
+ /// present "no cause found" as fact.
74
+ enum LaunchState {
75
+ /// No attempt has completed since this one started, so any failure now has an unknown cause.
76
+ case unknown
77
+ /// The dashboard answered, either because it was already up or because this launch started it.
78
+ case started
79
+ /// Node was not usable at the path baked into this app. Carries that path, which is the one both
80
+ /// the page and the log name.
81
+ case nodeMissing(baked: String)
82
+ /// An interpreter was there, and the dashboard still did not come up under it.
83
+ case serverFailed(node: String, detail: String)
84
+ /// A server was started and this window could not reach it, without being able to tell why. Not the
85
+ /// same as a failure: blaming the interpreter here would be a guess (see the probe below).
86
+ case unconfirmed(node: String, detail: String)
87
+ }
88
+
89
+ /// Holds the state above, and admits one launch attempt at a time.
90
+ ///
91
+ /// ensureDashboardRunning() writes the state from a background queue on the retry path while the page
92
+ /// reads it on the main thread, so the value goes through a lock rather than sitting in a bare
93
+ /// global. The lock alone protects the field, not the operation: two overlapping attempts would each
94
+ /// finish and each write, and the loser's result would be what the page reads. Retry and Cmd+R can
95
+ /// both start one, and a held Cmd+R can queue several, so entry is gated too.
96
+ final class LaunchStatus {
97
+ static let shared = LaunchStatus()
98
+ private let lock = NSLock()
99
+ private var state: LaunchState = .unknown
100
+ private var attemptInFlight = false
101
+
102
+ func set(_ value: LaunchState) {
103
+ lock.lock()
104
+ state = value
105
+ lock.unlock()
106
+ }
107
+
108
+ func get() -> LaunchState {
109
+ lock.lock()
110
+ defer { lock.unlock() }
111
+ return state
112
+ }
113
+
114
+ /// True when the caller owns the attempt and must call finishAttempt() when done. False means one
115
+ /// is already running, and a second would only race it to the same port.
116
+ func beginAttempt() -> Bool {
117
+ lock.lock()
118
+ defer { lock.unlock() }
119
+ if attemptInFlight { return false }
120
+ attemptInFlight = true
121
+ return true
122
+ }
123
+
124
+ func finishAttempt() {
125
+ lock.lock()
126
+ attemptInFlight = false
127
+ lock.unlock()
128
+ }
129
+ }
130
+ /// Which failure a finished launch attempt actually established.
131
+ ///
132
+ /// Pure, and inside this block, so a test can drive all four shapes rather than pattern-matching the
133
+ /// source. `lastInconclusive` non-nil is the deciding input and it outranks everything about the child:
134
+ /// the probe never established that the port is empty, so something may be holding it that this window
135
+ /// cannot read, and naming the interpreter as the fault would be a guess whether or not our own child
136
+ /// is still alive.
137
+ ///
138
+ /// `terminationStatus` and `signaled` are only read when `childRunning` is false. Foundation does not
139
+ /// promise a meaningful exit status for a process that has not exited, so the caller reads them behind
140
+ /// the same check rather than eagerly.
141
+ func launchFailureState(
142
+ node: String,
143
+ lastInconclusive: String?,
144
+ childRunning: Bool,
145
+ terminationStatus: Int32,
146
+ signaled: Bool,
147
+ elapsedSeconds: Int
148
+ ) -> LaunchState {
149
+ if let why = lastInconclusive {
150
+ let fate = childRunning
151
+ ? "The server this app started is still running."
152
+ : "The server this app started exited with status \(terminationStatus)."
153
+ return .unconfirmed(node: node, detail: "\(why) \(fate)")
154
+ }
155
+ let detail: String
156
+ if childRunning {
157
+ // Measured, not the constant: each probe can add up to 2s of its own, so the wait overshoots the
158
+ // deadline and a fixed "10 seconds" would be a number this attempt never observed.
159
+ detail = "It is running and has not answered in \(elapsedSeconds) seconds."
160
+ } else if signaled {
161
+ // Not an exit code. A server killed by the OOM reaper reports 9 here, and "exited with status 9"
162
+ // would read as a decision the server made.
163
+ detail = "It was killed by signal \(terminationStatus)."
164
+ } else {
165
+ detail = "It exited with status \(terminationStatus)."
166
+ }
167
+ return .serverFailed(node: node, detail: detail)
168
+ }
169
+
170
+ /// Whether the failure page offers a Retry button at all.
171
+ ///
172
+ /// `.none` is for the page where trying again is provably useless: it renders no button, so the only
173
+ /// actionable element is the command block, which is the thing that does work.
174
+ enum RetryAffordance {
175
+ case none
176
+ case accent
177
+ }
178
+
179
+ /// The page shown when the window cannot load the dashboard. Four shapes, because four situations
180
+ /// need different things from the reader: a missing interpreter is repaired in a terminal and no
181
+ /// control here can help, a server that did not come up is worth another attempt, a server that IS up
182
+ /// and unreachable is neither of those, and a dashboard that went away mid-session is routine and
183
+ /// needs saying so.
184
+ ///
185
+ /// 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 {
187
+ // One sentence about the controls, shared by the shapes where another attempt makes sense. Both
188
+ // controls run the same code, so describing them as two different moves would be wrong.
189
+ let controls = "Retry starts the server and loads the dashboard. &#8984;R does the same."
190
+ let logLine = "The full log is at ~/Library/Logs/slack-radar-dashboard.log"
191
+ let repair = "npx -y @slack/radar-mcp@latest install-app"
192
+ let repairLead = "Run this in a terminal, then quit and reopen this app."
193
+
194
+ switch state {
195
+ case .nodeMissing(let baked):
196
+ // No URL line, no controls sentence, and NO BUTTON. The server was never started, and the baked
197
+ // path is fixed in this binary, so any control here would re-run the same lookup and re-render
198
+ // this same page. The repair writes a NEW app, which this process only
199
+ // picks up once it is relaunched, so the command and the relaunch ARE the affordance. Cmd+R still
200
+ // re-runs the check and would recover if the path came back mid-upgrade, which is a quiet way to
201
+ // keep that escape without a button that invites the wrong move.
202
+ //
203
+ // The path ends its line rather than carrying a period: it is the payload the reader came for,
204
+ // and a path may contain spaces, so a glued period reads as part of it.
205
+ let body = """
206
+ This app cannot run the node it was built with.<br>
207
+ <span style="font:13px ui-monospace,SFMono-Regular,Menlo,monospace;color:#8aa0b4;\
208
+ overflow-wrap:anywhere">\(htmlEscape(baked))</span><br>
209
+ A node upgrade usually moves it.<br>
210
+ \(logLine)
211
+ """
212
+ return failurePageHTML(body: body, retry: .none, commandLead: repairLead, command: repair)
213
+
214
+ case .serverFailed(let node, let detail):
215
+ let body = """
216
+ \(htmlEscape(url)) did not respond.<br>
217
+ The dashboard server did not come up with \(htmlEscape(node)). \(htmlEscape(detail))<br>
218
+ \(logLine)<br><br>
219
+ \(controls)
220
+ """
221
+ return failurePageHTML(
222
+ body: body,
223
+ retry: .accent,
224
+ commandLead: "If it keeps failing, run this in a terminal, then quit and reopen this app.",
225
+ command: repair
226
+ )
227
+
228
+ case .unconfirmed(let node, let detail):
229
+ // Something may be answering on that URL and this window could not read it, and the probe could
230
+ // not say why. Naming the interpreter as the culprit would be a guess, and the repair command
231
+ // cannot fix a proxy, so this shape reports what is true and offers another attempt.
232
+ let body = """
233
+ This window could not tell what is on \(htmlEscape(url)), using \(htmlEscape(node)). \
234
+ \(htmlEscape(detail))<br>
235
+ \(logLine)<br><br>
236
+ \(controls)
237
+ """
238
+ return failurePageHTML(body: body, retry: .accent, commandLead: nil, command: nil)
239
+
240
+ case .unknown, .started:
241
+ // In practice this is the .started arm: the first launch runs before the window exists, so a state
242
+ // is always recorded before a load can fail. Two situations reach it, and only one is the routine
243
+ // auto-close: the other is a probe that answered on 127.0.0.1 while the WebView could not load
244
+ // localhost, which is reachable through a proxy this probe deliberately bypasses or a hosts file
245
+ // without a loopback entry. So the auto-close reads as "usually" rather than as what happened, and
246
+ // the network layer gets named, since that is the only thing a reader can act on in the second
247
+ // case.
248
+ let body = """
249
+ \(htmlEscape(url)) did not respond. \(htmlEscape(webKitError))<br>
250
+ The dashboard server usually closes itself a few minutes after the last window stops using it.<br>
251
+ If it is reachable in a browser and not here, a proxy or a hosts entry is blocking this window.<br>
252
+ \(logLine)<br><br>
253
+ \(controls)
254
+ """
255
+ return failurePageHTML(body: body, retry: .accent, commandLead: nil, command: nil)
256
+ }
257
+ }
258
+
259
+ /// The shared shell for those pages.
260
+ ///
261
+ /// Render order is what happened, then each control paired with the sentence that describes it: the
262
+ /// button under the controls sentence, the command under its lead. An earlier version put the command
263
+ /// 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 {
265
+ let retryButton = retry == .none
266
+ ? ""
267
+ : """
268
+ <button onclick="window.webkit.messageHandlers.radarRetry.postMessage('retry')"
269
+ style="margin-top:1em;padding:.5em 1.2em;font:14px -apple-system,sans-serif;\
270
+ background:#39d98a;color:#0b0f14;border:none;border-radius:6px;cursor:pointer">
271
+ Retry</button>
272
+ """
273
+ // Escaped like the command below it. Both callers pass literals today, so nothing is exposed, but
274
+ // htmlEscape's own note says this template should not need re-auditing to stay safe, and an
275
+ // unescaped String parameter is exactly what would force that audit the first time a lead carries
276
+ // a path.
277
+ let lead = commandLead.map { """
278
+ <div style="margin-top:1.2em;line-height:1.6">\(htmlEscape($0))</div>
279
+ """ } ?? ""
280
+ // Selectable in one click, because it exists to be copied, and carrying the brighter of the two
281
+ // borders since it is the element the reader is meant to act on.
282
+ let commandBlock = command.map { """
283
+ <div style="margin-top:.6em;padding:.7em .9em;background:#111823;border:1px solid #3a4a5c;\
284
+ border-radius:6px;font:13px ui-monospace,SFMono-Regular,Menlo,monospace;color:#e8f0f8;\
285
+ text-align:left;user-select:all;overflow-wrap:anywhere">\(htmlEscape($0))</div>
286
+ """ } ?? ""
287
+ return """
288
+ <html><body style="background:#0b0f14;color:#e8f0f8;font:14px -apple-system,sans-serif;\
289
+ display:flex;align-items:center;justify-content:center;height:100vh;margin:0">
290
+ <div style="max-width:34em;text-align:center">
291
+ <div style="font-size:15px;font-weight:600;margin-bottom:.6em">Could not reach the Radar dashboard</div>
292
+ <div style="color:#e8f0f8;line-height:1.6;overflow-wrap:anywhere">\(body)</div>
293
+ \(retryButton)
294
+ \(lead)
295
+ \(commandBlock)
296
+ </div></body></html>
297
+ """
298
+ }
299
+
300
+ /// Whether the dashboard already holding the port predates this app.
301
+ ///
302
+ /// Three cases, not a Bool, for the reason every probe here has three: the version arrives from
303
+ /// another process over HTTP and can be absent (an older dashboard that predates the header) or a
304
+ /// shape this cannot read. Neither of those is "current", and neither is "stale" either. Only
305
+ /// `.older` is a confirmed answer, and only a confirmed answer is allowed to end another process.
306
+ enum StaleDashboardVerdict {
307
+ case older
308
+ case notOlder
309
+ case cannotTell
310
+ }
311
+
312
+ /// [major, minor, patch] when all three read as plain numbers, nil otherwise.
313
+ ///
314
+ /// Deliberately strict. A prerelease like `1.20.0-rc.1` returns nil rather than guessing at an
315
+ /// ordering for it, and nil means cannotTell, which adopts. Being wrong in that direction shows
316
+ /// someone a version badge they did not expect; being wrong in the other direction stops a
317
+ /// dashboard that was never stale.
318
+ func radarVersionParts(_ version: String) -> [Int]? {
319
+ let fields = version.split(separator: ".", omittingEmptySubsequences: false)
320
+ guard fields.count == 3 else { return nil }
321
+ var parts: [Int] = []
322
+ for field in fields {
323
+ guard !field.isEmpty, field.allSatisfy({ $0.isNumber }), let value = Int(field) else { return nil }
324
+ parts.append(value)
325
+ }
326
+ return parts
327
+ }
328
+
329
+ /// What a liveness probe established. Three states, because this probe cannot always tell: a system
330
+ /// HTTP proxy with no loopback bypass, a hijacked resolver or a stalled network stack all fail in a
331
+ /// way that looks exactly like "nothing is listening" from here.
332
+ ///
333
+ /// That distinction earns its keep now. This probe used to decide one thing (load the window anyway),
334
+ /// and it now decides three: when to stop waiting on an interpreter, which one to blame, and whether
335
+ /// to print a repair command. Collapsing "could not tell" into "not listening" would put a confident,
336
+ /// wrong cause on screen with an instruction that cannot help.
337
+ enum DashboardProbe {
338
+ /// Carries what the answering dashboard said about itself: its X-Radar-Version, nil when it sent
339
+ /// none, and whether anyone is using it. A dashboard old enough to predate either header is exactly
340
+ /// the kind this app wants to notice, so an absence is kept rather than flattened into a default.
341
+ case answering(version: String?, inUse: DashboardUse)
342
+ case notListening
343
+ case couldNotTell(String)
344
+ }
345
+
346
+ /// What a probe result contributes to "has anything established that the port is empty".
347
+ ///
348
+ /// nil means the question is settled in the negative: either the port answered, or it reported nothing
349
+ /// listening. A reason means it is NOT settled, and the caller must not blame the interpreter.
350
+ ///
351
+ /// Extracted for one reason: the two arms that produce nil and non-nil sat next to each other in the
352
+ /// polling loop, and swapping them compiled, kept every source-text assertion green, and made the page
353
+ /// blame the interpreter for a proxy while printing a repair command that cannot help. Here, swapping
354
+ /// them fails a test.
355
+ func inconclusiveReason(_ probe: DashboardProbe) -> String? {
356
+ switch probe {
357
+ case .answering:
358
+ // The caller returns .started before asking, so this is only reachable if that ever changes. An
359
+ // answering port is the strongest possible "nothing is wrong", so nil is right either way.
360
+ return nil
361
+ case .notListening:
362
+ return nil
363
+ case .couldNotTell(let why):
364
+ return why
365
+ }
366
+ }
367
+
368
+ /// Which decision an in-use answer is being asked to inform. Sent on the probe, and the server gives the
369
+ /// two different answers: see its InUseDecision. Inside the harness block so a test can pin the two wire
370
+ /// values rather than trusting a string literal at the call site.
371
+ enum InUseDecision: String {
372
+ /// Deciding whether to take a port this app does not own. The launch path.
373
+ case take
374
+ /// Deciding whether to stop a server this app started itself. The quit path.
375
+ case stop
376
+ }
377
+
378
+ /// This app's own presence id, generated once per launch.
379
+ ///
380
+ /// The window this app opens polls the dashboard with this id, and the probe sends the same id back as
381
+ /// the one to leave out of the in-use answer. That is what turns "is anyone using this dashboard" into
382
+ /// the question this app actually has, which is "is anyone OTHER than my own window using it".
383
+ ///
384
+ /// Generated HERE rather than by the page, which used to mint its own: the app has to know the id
385
+ /// before the page exists, since it is what the app then asks about.
386
+ let appTabId = UUID().uuidString
387
+
388
+ /// Whether the dashboard on the port says anyone is using it, and who.
389
+ ///
390
+ /// Five states because the answer arrives over HTTP from another process, and there are three
391
+ /// different ways that can be short of a usable answer: no in-use header at all (a dashboard published
392
+ /// before any of this), a claim with no attribution (one published before the exclusion), and a claim
393
+ /// attributed to a kind this app does not know yet.
394
+ ///
395
+ /// A bare absence is `cannotTell`, never `no`: reading "no header" as "nobody is using it" would take
396
+ /// the port from live sessions on every older dashboard, which is most of them right after this ships.
397
+ enum DashboardUse {
398
+ /// A window that is not this app's own, as far as the wire can establish it: the server echoed back the
399
+ /// id it was asked to leave out, which proves it UNDERSTOOD the exclusion. It does not prove that id
400
+ /// belonged to a live window of ours, because the echo is unconditional, so a window of ours that died
401
+ /// without closing its page still reads this way until its presence entry goes stale. Taking this
402
+ /// server's port costs somebody a page they were reading, and the browser fallback in the README makes
403
+ /// that a real configuration rather than a hypothetical one.
404
+ case tab
405
+ /// An agent session driving this dashboard. Taking its port costs the session's pulled databases,
406
+ /// its device pin and its logcat ring, and it cannot get any of them back.
407
+ case mcp
408
+ /// Somebody claims it and the answer does not say who well enough to act on. Either the server is too
409
+ /// old to leave this app's window out (so the claim may BE this app's window), or the kind it named is
410
+ /// one this app has never heard of. Distinct from `cannotTell`, which is no answer at all: here there
411
+ /// is a claim, and the only thing missing is whose it is.
412
+ case someoneUnnamed
413
+ case no
414
+ case cannotTell
415
+ }
416
+
417
+ /// Read the in-use headers. `X-Radar-In-Use` carries whether, `X-Radar-In-Use-By` carries which, and
418
+ /// `X-Radar-In-Use-Excludes` carries the id the server left out, which is the only proof that a tab
419
+ /// claim is not this app's own window.
420
+ ///
421
+ /// Strict on purpose: a proxy or a foreign program is free to put whatever it likes in a header, and
422
+ /// "1" is a cheap thing to guess.
423
+ ///
424
+ /// A tab claim from a server that did not echo this app's id is `someoneUnnamed`, not `tab`. The echo
425
+ /// cannot be assumed, because the dashboards this decision is aimed at are OLDER ones, which is exactly
426
+ /// where the request header is not understood.
427
+ ///
428
+ /// An unrecognised kind is `someoneUnnamed` too, and so is a claim with no kind at all. Both mean a
429
+ /// newer or an older server told us somebody is there, and treating that as no answer at all was
430
+ /// measurably less safe than the single-bit version this replaced: that one kept an in-use dashboard on
431
+ /// a cold launch, and reading its "1" with no kind as "cannot tell" took the port instead.
432
+ func readDashboardUse(
433
+ _ inUse: String?,
434
+ by kind: String?,
435
+ excluding excluded: String?,
436
+ ours: String
437
+ ) -> DashboardUse {
438
+ switch inUse {
439
+ case "1":
440
+ switch kind {
441
+ // The comparison, not merely the presence of the header: a server that echoes a DIFFERENT id has
442
+ // answered about somebody else's exclusion, and this app's window is still in that count.
443
+ case "tab": return excluded == ours ? .tab : .someoneUnnamed
444
+ case "mcp": return .mcp
445
+ default: return .someoneUnnamed
446
+ }
447
+ case "0": return .no
448
+ default: return .cannotTell
449
+ }
450
+ }
451
+
452
+ /// What to do about the dashboard already on the port.
453
+ ///
454
+ /// Pure, and inside the marker block on purpose. This decision used to sit inline in
455
+ /// ensureDashboardRunning, below the block a test can compile, so the only thing guarding it was regex
456
+ /// over source text. That is not enough: swapping the two switch arm labels while leaving their bodies
457
+ /// in place still compiles, still matches every source-text assertion, and inverts the feature, adopting
458
+ /// stale dashboards and taking the port from current ones. A pure function can just be called.
459
+ ///
460
+ /// Each refusal is its own case rather than a bare false, because the log line the user has to
461
+ /// understand later differs for every one of them.
462
+ enum PortTakeover {
463
+ /// Stop it and serve this version instead.
464
+ case take
465
+ /// It is current, or its version could not be read. Nothing to do.
466
+ case keepNotOlder
467
+ /// It is older, but this app has no interpreter to start a replacement with, so stopping it would
468
+ /// leave nothing at all.
469
+ case keepNoInterpreter
470
+ /// It is older, but it says someone is using it. An out-of-date dashboard is a smaller problem than
471
+ /// pulling a live session out from under someone.
472
+ case keepInUse
473
+ }
474
+
475
+ func portTakeoverDecision(
476
+ verdict: StaleDashboardVerdict,
477
+ haveInterpreter: Bool,
478
+ inUse: DashboardUse,
479
+ respectInUse: Bool
480
+ ) -> PortTakeover {
481
+ guard case .older = verdict else { return .keepNotOlder }
482
+ guard haveInterpreter else { return .keepNoInterpreter }
483
+ switch inUse {
484
+ case .tab, .someoneUnnamed:
485
+ // Somebody has a window on it, or claims something this app cannot attribute. A launch leaves both
486
+ // alone; a Retry overrides both, and that is deliberate rather than left over.
487
+ //
488
+ // Why a Retry may take a window's port. The person pressing it is asking for their dashboard back,
489
+ // and two of the ways they can arrive here are a window that no longer exists: an app killed without
490
+ // closing its page leaves a presence entry that stays fresh for TAB_IN_USE_MS, and a server too old
491
+ // to honour the exclusion answers about this app's own window. Refusing on those would leave the
492
+ // person pressing the button no way out short of stopping the server by hand. The cost when the
493
+ // window IS somebody else's is a page they were reading, which is the same trade #154 already made
494
+ // here and disclosed.
495
+ //
496
+ // The QUIT path does not make this trade. Nobody presses anything there, so a confirmed foreign
497
+ // window keeps its server (see stopIfOurs). That asymmetry is the point: an explicit request may
498
+ // cost somebody a page, an implicit one may not.
499
+ return respectInUse ? .keepInUse : .take
500
+ case .mcp:
501
+ // An agent session, and the override does NOT reach it. Retry is bound to Cmd+R as well as the
502
+ // failure page's button, so an ordinary refresh of a dashboard that is working fine used to stop
503
+ // a session and drop its pulled databases, its device pin and its logcat ring. A stale version
504
+ // badge is worth less than any of those, which is the same trade this whole path already makes in
505
+ // the other direction.
506
+ return .keepInUse
507
+ case .no, .cannotTell:
508
+ // Named rather than defaulted. cannotTell proceeds, which is the permissive reading and the one
509
+ // the type's own doc comment warns about: a dashboard too old to send any in-use header at all
510
+ // reads this way, so a live session on one of those is stopped without a signal. It is the
511
+ // deliberate cost of fixing the reported bug at all, and the PR body says so rather than hiding it
512
+ // here. The narrower case, a dashboard that answers "someone" without saying who, is no longer
513
+ // part of that cost: it is someoneUnnamed above and it is protected on a cold launch.
514
+ return .take
515
+ }
516
+ }
517
+
518
+ /// How long the children get to leave on their own after being asked, before they are signalled. Short
519
+ /// because the app holds its own quit open while this runs (see `applicationShouldTerminate`), and the
520
+ /// person has already asked it to go away.
521
+ ///
522
+ /// Deliberately shorter than the longest graceful stop, which can reach about ten seconds when ffmpeg
523
+ /// is finalizing a recording. Waiting that out would buy nothing: the exit handler deletes the capture
524
+ /// either way, so what the request is worth here is a clean server.close and no half-written file, not
525
+ /// a surviving clip. A finalize that outruns this gets signalled, and that is the right trade against
526
+ /// holding a quit open for ten seconds.
527
+ let quitShutdownDeadlineSeconds = 3.0
528
+
529
+ /// How long the graceful request itself may hold the quit, ahead of the poll above.
530
+ ///
531
+ /// Small because the request's reply settles nothing, so this only has to be long enough for the bytes
532
+ /// to leave. With the default wait instead, the two stacked and the real bound was about twice what
533
+ /// quitShutdownDeadlineSeconds advertises, on a path that reasons explicitly about the user waiting
534
+ /// for the app to go away.
535
+ let quitShutdownRequestWaitSeconds = 0.5
536
+
537
+ /// The outer bound on a deferred quit: how long the app may stay alive waiting for its own stop work
538
+ /// before it gives up and goes.
539
+ ///
540
+ /// Longer than that work's own worst case (about 5.5s: a 2s claim probe, a 0.5s request, a 3s poll), so
541
+ /// it never cuts short a stop that is merely slow. It exists for the case the bounds above do not cover,
542
+ /// which is one of them failing to hold.
543
+ let quitDeferralDeadlineSeconds = 8.0
544
+
545
+ /// The outer bound on one dashboardProbe(), and the third term in the quit's worst case.
546
+ ///
547
+ /// Named rather than left inline at the semaphore because the quit's deadline has to be longer than the
548
+ /// work it backstops, and a bare literal cannot be added up: with this term missing, a deadline of four
549
+ /// seconds looked correct against a sum of three and a half while the real worst case was five and a half.
550
+ /// A little above the 1.5s request timeout it bounds, so a request that times out normally reports that
551
+ /// rather than tripping this.
552
+ let dashboardProbeDeadlineSeconds = 2.0
553
+
554
+ /// What quitting did about the dashboard this app started. Five outcomes, not a Bool: each one is a
555
+ /// different thing to have happened, and the log line a person reads later is chosen from it.
556
+ enum QuitStopOutcome {
557
+ /// Nothing this app spawned was running, so there was nothing to stop. The usual case for a window
558
+ /// that adopted a dashboard someone else started.
559
+ case nothingOurs
560
+ /// It went away after being asked, which is the graceful path doing its job.
561
+ case left
562
+ /// It was still running when the wait ran out, so it was signalled.
563
+ case signalled
564
+ /// This app spawned it, but an agent session is driving it, so it was left running on purpose. The
565
+ /// asymmetry this closes: the launch path already refuses to take a port from a session, and this
566
+ /// path used to stop one of its own without asking.
567
+ case leftForSession
568
+ /// This app spawned it, but a window that is not this app's has it open, so it was left running. Its
569
+ /// own case rather than sharing the one above because the log line a person reads later differs, and
570
+ /// because the two are found by different evidence: a session is named by the server, and a foreign
571
+ /// window is what is left after this app's own window is excluded by id.
572
+ case leftForWindow
573
+ /// This app spawned it, and the server said somebody is using it without saying who, so it was left
574
+ /// running. On the quit side that answer can only come from a server newer than this binary (a
575
+ /// server this app spawned runs RADAR_WEB_BIN, which self-heal moves ahead of the compiled app), and
576
+ /// the wire contract says a new kind is to be expected. Stopping a server whose newer answer said
577
+ /// somebody was on it would be the implicit path costing somebody a page, which is the trade the launch
578
+ /// arm reserves for an explicit request. The cost is one orphaned server, which the launch path reclaims.
579
+ case leftUnattributed
580
+ }
581
+
582
+ /// The dashboard servers this app started.
583
+ ///
584
+ /// Only processes this app spawned belong here. A dashboard that was already on the port when this app
585
+ /// launched was started by something else, often a Claude Code session, and stopping that on quit
586
+ /// would take away a server this app never owned.
587
+ ///
588
+ /// A LIST, not one slot. A single slot held "the last thing launched", which is not the same as "the
589
+ /// thing serving the port": an attempt whose probe came back inconclusive leaves a live child, and the
590
+ /// next Retry spawns another and overwrote the reference to it. The second child then loses the port
591
+ /// and exits, so quit found a dead process, logged nothing, and left the first one serving. That is
592
+ /// the exact leak this type exists to prevent, reachable from the failure page's own Retry button.
593
+ final class SpawnedDashboard {
594
+ static let shared = SpawnedDashboard()
595
+ private let lock = NSLock()
596
+ private var tasks: [Process] = []
597
+
598
+ /// Set once the quit has taken the list. A launch attempt runs on a background queue, so a spawn can
599
+ /// finish AFTER the quit path has already read and cleared it, and storing that child would hand it to
600
+ /// nobody: the app exits and the child keeps the port. Trigger is ordinary, since Retry starts an
601
+ /// attempt and Cmd+Q lands during the seconds it spends probing.
602
+ private var terminating = false
603
+
604
+ func record(_ started: Process) {
605
+ lock.lock()
606
+ let tooLate = terminating
607
+ if !tooLate { tasks.append(started) }
608
+ lock.unlock()
609
+ guard tooLate else { return }
610
+ // Nothing will come back for this one, so it is dealt with here. No graceful request: the app is
611
+ // already going away, and this child has not had time to serve anything.
612
+ if started.isRunning { started.terminate() }
613
+ }
614
+
615
+ /// Stop whatever this app started, reporting what actually happened.
616
+ ///
617
+ /// An outcome, not a Bool, for the same reason everything else here has more than two states: "it left
618
+ /// when asked" and "it ignored the request and had to be signalled" are worth telling apart in the log,
619
+ /// because the second is the one that says the graceful path did not work, and the two refusals are
620
+ /// worth telling apart from both.
621
+ ///
622
+ /// `askToStop` is the graceful request, injected rather than called directly so this whole type stays
623
+ /// inside the block a test can compile on its own. It runs FIRST and it is the one that matters: it
624
+ /// reaches the server's own shutdown, which is a path that finalizes a screen recording in progress.
625
+ ///
626
+ /// terminate() is the fallback, and it sends SIGTERM. Worth being exact about why that is second
627
+ /// choice rather than the plan: bin.ts does register a graceful SIGTERM handler, but log-session
628
+ /// registers its own at server module load and that one exits synchronously, so the graceful handler
629
+ /// never runs. Both files say so where they register. SIGKILL would be worse again, so SIGTERM stays
630
+ /// as the thing that guarantees a child which ignored the request does not outlive the app.
631
+ ///
632
+ /// The list is cleared as it is taken, so a second call is a no-op rather than a second signal.
633
+ @discardableResult
634
+ func stopIfOurs(
635
+ askToStop: () -> Void = {},
636
+ inUse: () -> DashboardUse = { .cannotTell },
637
+ note: (String) -> Void = { _ in }
638
+ ) -> QuitStopOutcome {
639
+ lock.lock()
640
+ let owned = tasks
641
+ tasks = []
642
+ terminating = true
643
+ lock.unlock()
644
+ let live = owned.filter { $0.isRunning }
645
+ guard !live.isEmpty else { return .nothingOurs }
646
+ // Having spawned it is not the same as nobody else needing it. An agent session can be driving
647
+ // the very server this app started, which is the ordinary shape of asking Claude Code for
648
+ // open_radar_dashboard, and closing the last window is enough to quit this app and take that
649
+ // session's pulled databases, its device pin and its logcat ring with it.
650
+ //
651
+ // An mcp claim stops us, and so does a tab claim the server confirmed is not this app's own
652
+ // window. That second one is the reason the exclusion exists: the README documents opening the
653
+ // dashboard in a browser, so a real Chrome tab and this app can share a port, and quitting the app
654
+ // used to kill the server that tab was reading.
655
+ //
656
+ // someoneUnnamed keeps the server too, and the route in matters. A server THIS app spawned runs
657
+ // RADAR_WEB_BIN, which is this app's version or a NEWER one (self-heal updates the package under the
658
+ // app, see triggerSelfHealCheck), so it understands the exclusion and never produces the OLD-server
659
+ // route into someoneUnnamed. The route it can produce is a kind this binary has not heard of, which
660
+ // is exactly what the wire contract says to expect when the server is ahead, and that answer says
661
+ // somebody is there. A quit is nobody asking, so it may not cost that somebody a page; the launch
662
+ // arm makes the opposite trade for an explicit Retry and says so.
663
+ //
664
+ // cannotTell proceeds, and for a child of ours it only ever arrives one way: the probe got no answer
665
+ // it could read. The call site folds both non-answering probe results into it, an empty port
666
+ // (notListening) and a timeout, a non-200 from /spec or an unreadable reply (couldNotTell). Both
667
+ // stop, on purpose. A child that cannot answer /spec on loopback inside the probe deadline is not
668
+ // serving a page or a session either, and left alone it keeps the port, so the next launch adopts a
669
+ // wedged server, which is the trap this path exists to close. The graceful request still goes first,
670
+ // so a server that was merely slow gets its deadline before the signal. DashboardProbe keeps the
671
+ // two apart, so if they ever need to differ the call site is where to split them. The other route
672
+ // into cannotTell, an answer with no header, means a server older than the header, and that cannot
673
+ // be a child of ours.
674
+ //
675
+ // The mcp arm means a session, and it means that now because the probe asks as a stop decision: the
676
+ // server's "no window has ever opened this" guess is scoped to callers deciding about a port they do
677
+ // not own, so it can no longer answer "a session" about a child of ours whose window never loaded.
678
+ //
679
+ // An exhaustive switch rather than two `if case` tests, so a new claim kind cannot arrive without
680
+ // this decision being made about it. It is the one place where getting it wrong either orphans a
681
+ // server or takes a page away from somebody.
682
+ switch inUse() {
683
+ case .mcp: return keepOwning(owned, .leftForSession)
684
+ case .tab: return keepOwning(owned, .leftForWindow)
685
+ case .someoneUnnamed: return keepOwning(owned, .leftUnattributed)
686
+ case .no, .cannotTell: break
687
+ }
688
+ // Logged before the slow part. Every outcome line is written once this returns, up to a few seconds
689
+ // later, so a reader of the log can tell a stop that is merely slow from one that never finished.
690
+ // Nothing hangs while it runs, since the whole block is off the main thread, and the in-use probe
691
+ // above has already taken its own share of the time.
692
+ //
693
+ // Injected rather than called, like askToStop and inUse above, because this block is compiled on
694
+ // its own by the tests and appendLaunchLog lives outside it.
695
+ note("quit: stopping the dashboard this app started.")
696
+ askToStop()
697
+ // Give them the chance the request bought them. Polling rather than waitUntilExit() because a
698
+ // child that never honours the request must not hold the quit open indefinitely.
699
+ let deadline = Date().addingTimeInterval(quitShutdownDeadlineSeconds)
700
+ while Date() < deadline, live.contains(where: { $0.isRunning }) {
701
+ Thread.sleep(forTimeInterval: 0.1)
702
+ }
703
+ let stubborn = live.filter { $0.isRunning }
704
+ for child in stubborn { child.terminate() }
705
+ return stubborn.isEmpty ? .left : .signalled
706
+ }
707
+
708
+ /// Hand the list back and report why nothing was stopped.
709
+ ///
710
+ /// Its own function because there are now two reasons to decline, the restore is three ordered
711
+ /// statements under a lock, and a hand-inlined second copy is exactly how one of them quietly stops
712
+ /// restoring ownership. Without the restore the server this app started outlives it with nothing
713
+ /// tracking it, which is the leak the list exists to prevent.
714
+ private func keepOwning(_ owned: [Process], _ outcome: QuitStopOutcome) -> QuitStopOutcome {
715
+ lock.lock()
716
+ tasks = owned
717
+ terminating = false
718
+ lock.unlock()
719
+ return outcome
720
+ }
721
+ }
722
+
723
+ func staleDashboardVerdict(running: String?, mine: String) -> StaleDashboardVerdict {
724
+ guard let running, let theirs = radarVersionParts(running), let ours = radarVersionParts(mine) else {
725
+ return .cannotTell
726
+ }
727
+ for (theirPart, ourPart) in zip(theirs, ours) where theirPart != ourPart {
728
+ return theirPart < ourPart ? .older : .notOlder
729
+ }
730
+ return .notOlder
731
+ }
732
+ // --- END LAUNCH HELPERS ---
733
+
734
+ /// The dashboard's log, written by the server it starts, the self-heal spawn, and the notes here.
735
+ let radarLogPath = ("~/Library/Logs/slack-radar-dashboard.log" as NSString).expandingTildeInPath
736
+
737
+ /// A handle onto that log in APPEND mode, or nil when it cannot be opened.
738
+ ///
739
+ /// O_APPEND, not open-then-seek: seeking sets one offset on one descriptor, and the dashboard child
740
+ /// holds its own. A line written here while that child is alive would land at the child's stale
741
+ /// offset and be overwritten by its next write, eating the timestamp first. Append makes every write
742
+ /// land at the end of the file no matter who else holds it open.
743
+ func radarLogHandle() -> FileHandle? {
744
+ let fd = open(radarLogPath, O_WRONLY | O_APPEND | O_CREAT, 0o644)
745
+ guard fd >= 0 else { return nil }
746
+ return FileHandle(fileDescriptor: fd, closeOnDealloc: true)
747
+ }
748
+
749
+ /// One line into that log, for what happens before (or instead of) a child process. Stamped the way
750
+ /// the self-heal lines already in this file are, so a reader can place it in time.
751
+ func appendLaunchLog(_ line: String) {
752
+ guard let handle = radarLogHandle() else { return }
753
+ let stamp = ISO8601DateFormatter().string(from: Date())
754
+ handle.write(Data("\(stamp) \(line)\n".utf8))
755
+ try? handle.close()
756
+ }
757
+
758
+
759
+ /// The dashboard's /spec over LOOPBACK BY ADDRESS. `radarURL` stays `localhost` for the WebView, but a
760
+ /// name has to be resolved and a proxy can be consulted, and neither belongs in a health check of a
761
+ /// 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")!
763
+
764
+ /// The page the window loads: the dashboard, carrying the presence id this app generated, so the page
765
+ /// polls under an id this app can then ask the server to leave out.
766
+ ///
767
+ /// URLComponents rather than string concatenation because RADAR_URL is baked at install time and a
768
+ /// query already on it would turn this into a second `?`. The fallback to the bare URL costs more than
769
+ /// the exclusion, so it is worth naming: the page would mint an id this app cannot name, the probe would
770
+ /// still ask for its own id to be left out, and the app's own window would come back as a foreign one.
771
+ /// Unreachable in practice, since URLComponents does not fail on an already-parsed URL.
772
+ ///
773
+ /// `presence`, not `tab`: the dashboard's own tabs (Live, Network, Clogs) are what `?tab=` would read
774
+ /// as to anyone looking at this URL, and this is not one of those.
775
+ let dashboardPageURL: URL = {
776
+ guard var parts = URLComponents(url: radarURL, resolvingAgainstBaseURL: false) else { return radarURL }
777
+ parts.queryItems = (parts.queryItems ?? []) + [URLQueryItem(name: "presence", value: appTabId)]
778
+ return parts.url ?? radarURL
779
+ }()
780
+
781
+ /// /spec is instant (no device round-trip) and unique to Radar, the same fingerprint the shell
782
+ /// launcher and bin.ts's adopt path use.
783
+ func dashboardProbe(deciding decision: InUseDecision = .take) -> DashboardProbe {
784
+ var request = URLRequest(url: probeURL)
36
785
  request.timeoutInterval = 1.5
786
+ // Which decision this answer is for. The launch path is deciding whether to TAKE a port it does not
787
+ // own; the quit path is deciding whether to STOP a server it started. The server answers those
788
+ // differently on purpose, and the wrong one either kills a page somebody is reading or leaves a server
789
+ // running under a session that does not exist. A server too old to know this header answers the take
790
+ // question, which is the cautious one of the two.
791
+ request.setValue(decision.rawValue, forHTTPHeaderField: "X-Radar-In-Use-For")
792
+ // Ask about everyone EXCEPT the window this app owns. Without this the answer counts our own window,
793
+ // so it reports that somebody is using the dashboard whenever the dashboard is working, and the app
794
+ // can neither replace a stale one nor stop the one it started. A server too old to know this header
795
+ // just answers the wider question, which readDashboardUse detects by the echo being absent.
796
+ request.setValue(appTabId, forHTTPHeaderField: "X-Radar-Ignore-Tab")
797
+ // Direct connection: a proxy configured for this Mac has no business standing between a window and
798
+ // the server it just started, and honoring one is how this probe reported a live server as dead.
799
+ let config = URLSessionConfiguration.ephemeral
800
+ config.connectionProxyDictionary = [:]
801
+ config.timeoutIntervalForRequest = 1.5
802
+ let session = URLSession(configuration: config)
37
803
  // A synchronous probe on a background queue: this runs before the window exists, so there is no
38
804
  // UI to block, and the sequential start-then-wait reads far clearer than nested callbacks.
39
805
  let semaphore = DispatchSemaphore(value: 0)
40
- var ok = false
41
- URLSession.shared.dataTask(with: request) { _, response, _ in
42
- ok = (response as? HTTPURLResponse)?.statusCode == 200
806
+ // Locked, not bare: on the timeout path this function returns while the task's completion handler
807
+ // can still run, so both sides can write this box. The payload is a String, which makes an unguarded
808
+ // write a race on a reference count rather than merely a lost value.
809
+ let outcomeLock = NSLock()
810
+ var outcome = DashboardProbe.couldNotTell("the probe did not finish")
811
+ let record = { (value: DashboardProbe) in
812
+ outcomeLock.lock()
813
+ outcome = value
814
+ outcomeLock.unlock()
815
+ }
816
+ session.dataTask(with: request) { _, response, error in
817
+ if let http = response as? HTTPURLResponse {
818
+ record(http.statusCode == 200
819
+ ? .answering(
820
+ version: http.value(forHTTPHeaderField: "X-Radar-Version"),
821
+ inUse: readDashboardUse(
822
+ http.value(forHTTPHeaderField: "X-Radar-In-Use"),
823
+ by: http.value(forHTTPHeaderField: "X-Radar-In-Use-By"),
824
+ excluding: http.value(forHTTPHeaderField: "X-Radar-In-Use-Excludes"),
825
+ ours: appTabId))
826
+ : .couldNotTell("HTTP \(http.statusCode)"))
827
+ } else if let error = error as NSError? {
828
+ // Only this one means "nothing is listening here". Measured on loopback: an empty port gives
829
+ // -1004 (cannotConnectToHost), while a port that accepts and then drops gives -1005
830
+ // (networkConnectionLost), which is something LISTENING and failing. Everything else -- a
831
+ // timeout, a proxy refusing, a resolver failing -- is inconclusive and must not read as an
832
+ // answer.
833
+ record(error.code == NSURLErrorCannotConnectToHost
834
+ ? .notListening
835
+ : .couldNotTell(error.localizedDescription))
836
+ }
43
837
  semaphore.signal()
44
838
  }.resume()
45
- _ = semaphore.wait(timeout: .now() + 2)
46
- return ok
839
+ if semaphore.wait(timeout: .now() + dashboardProbeDeadlineSeconds) == .timedOut {
840
+ record(.couldNotTell("the probe timed out"))
841
+ }
842
+ session.finishTasksAndInvalidate()
843
+ outcomeLock.lock()
844
+ defer { outcomeLock.unlock() }
845
+ return outcome
846
+ }
847
+
848
+ /// Same loopback-by-address reasoning as probeURL.
849
+ let shutdownURL = URL(string: "http://127.0.0.1:\(radarURL.port ?? 8100)/shutdown")!
850
+
851
+ /// How long a stale dashboard gets to go away after being asked. Its stop is graceful (it finalizes a
852
+ /// live screen recording before exiting), so it is not instant, and it is bounded because the fallback
853
+ /// costs the user nothing worse than the version badge they already had.
854
+ let staleShutdownDeadlineSeconds = 5.0
855
+
856
+ /// What asking a stale dashboard to stop actually established.
857
+ ///
858
+ /// Three states, not a Bool, for the reason every probe in this file has three: the poll that decides
859
+ /// this runs against another process over HTTP, and "I could not reach it" is not "it is still there".
860
+ /// The first version returned false for both and the caller logged "is still holding the port" as
861
+ /// fact, which collapses "could not tell" into "no", the one reading a probe over HTTP never gets to make here.
862
+ enum StalePortOutcome {
863
+ /// The port answered "nothing listening", so the old dashboard is gone.
864
+ case freed
865
+ /// It is still serving. A graceful stop finalizes a screen recording first, and that has no upper
866
+ /// bound, so this is a normal answer rather than a broken one.
867
+ case stillServing
868
+ /// The poll never established either. Carries what got in the way, so the log can say so.
869
+ case couldNotTell(String)
870
+ }
871
+
872
+ /// POST /shutdown at whatever holds the port, and return once the request has been answered or has
873
+ /// given up. Shared by the launch path (taking the port from a stale dashboard) and the quit path
874
+ /// (stopping the server this app started), because both want the same thing: the server's own graceful
875
+ /// stop rather than a signal.
876
+ ///
877
+ /// This ASKS. The request carries the `X-Radar-Dashboard` header the /shutdown route requires, so the
878
+ /// only thing that can act on it is a Radar dashboard. Killing by port is what this deliberately does
879
+ /// not do: `lsof -ti` on 8100 could be a browser, a teammate's server, or anything else, and the
880
+ /// launcher refuses to do it for exactly that reason.
881
+ ///
882
+ /// The proxy bypass matters as much here as on the probe. A system HTTP proxy standing between this app
883
+ /// and a server on this machine is how the probe once reported a live server as dead, and a proxy
884
+ /// swallowing this request would silently turn a graceful stop into a SIGTERM.
885
+ /// `waitSeconds` is how long to hold this thread for the reply, and the quit path passes a much
886
+ /// smaller number than the default on purpose.
887
+ ///
888
+ /// The reply is never the answer here: a dashboard answers /shutdown before it has finished stopping,
889
+ /// and the caller that cares settles it by watching the port instead. So on a quit this only has to
890
+ /// stay alive long enough for the request to leave, and waiting the full default stacked that wait in
891
+ /// front of the poll's own deadline. The visible bound is what matters, since the person is watching
892
+ /// an app refuse to go away.
893
+ func postDashboardShutdown(waitSeconds: Double = 3) {
894
+ var request = URLRequest(url: shutdownURL)
895
+ request.httpMethod = "POST"
896
+ request.setValue("1", forHTTPHeaderField: "X-Radar-Dashboard")
897
+ request.timeoutInterval = 2
898
+ let config = URLSessionConfiguration.ephemeral
899
+ config.connectionProxyDictionary = [:]
900
+ config.timeoutIntervalForRequest = 2
901
+ let session = URLSession(configuration: config)
902
+ let semaphore = DispatchSemaphore(value: 0)
903
+ session.dataTask(with: request) { _, _, _ in semaphore.signal() }.resume()
904
+ _ = semaphore.wait(timeout: .now() + waitSeconds)
905
+ session.finishTasksAndInvalidate()
906
+ }
907
+
908
+ /// Ask the dashboard holding the port to stop, then report what the port itself then said. The request
909
+ /// is the shared one above; what this adds is the waiting and the reading of the result.
910
+ func stopStaleDashboard() -> StalePortOutcome {
911
+ postDashboardShutdown()
912
+ // The reply is not the answer, so it is not read. A dashboard answers /shutdown before it has
913
+ // finished stopping, and a request that reported a transport failure may still have been delivered.
914
+ // The port is the only thing that settles it.
915
+ let deadline = Date().addingTimeInterval(staleShutdownDeadlineSeconds)
916
+ var lastInconclusive: String?
917
+ while Date() < deadline {
918
+ switch dashboardProbe() {
919
+ case .notListening:
920
+ return .freed
921
+ case .answering:
922
+ lastInconclusive = nil
923
+ case .couldNotTell(let why):
924
+ lastInconclusive = why
925
+ }
926
+ Thread.sleep(forTimeInterval: 0.2)
927
+ }
928
+ // Whatever the LAST look said. An inconclusive final probe outranks an earlier clean "still
929
+ // serving", because the earlier one is no longer a statement about now.
930
+ if let lastInconclusive { return .couldNotTell(lastInconclusive) }
931
+ return .stillServing
47
932
  }
48
933
 
49
934
  /// Start the dashboard server if it is not already up, then wait for it to answer.
@@ -52,11 +937,132 @@ func dashboardAlive() -> Bool {
52
937
  /// path, not an edge case. Waiting (rather than sleeping a fixed guess) matters because a cold node
53
938
  /// start ranges from ~300ms to several seconds on a loaded machine, and loading the view too early
54
939
  /// renders a WebKit error page the user has to manually reload past.
55
- func ensureDashboardRunning() {
56
- if dashboardAlive() { return }
940
+ /// How long the interpreter gets to bring the dashboard up. A cold node start is ~300ms on a fast Mac
941
+ /// and multiple seconds on a loaded one, so this is generous; an interpreter that cannot run the dist
942
+ /// at all exits in well under a second and is not waited out.
943
+ let startupDeadlineSeconds = 10.0
944
+
945
+ /// What a launch attempt did, for the caller deciding whether to reload the window.
946
+ ///
947
+ /// Three cases, not a Bool. `refused` means another attempt is already running and will load the
948
+ /// window itself; `failed` means this attempt learned something new, so the window SHOULD reload and
949
+ /// show it. An earlier version returned false for both and the window kept showing a stale page after
950
+ /// the user pressed Retry.
951
+ enum LaunchOutcome {
952
+ case refused
953
+ case started
954
+ case failed
955
+ }
956
+
957
+ @discardableResult
958
+ func ensureDashboardRunning(respectInUse: Bool = true) -> LaunchOutcome {
959
+ // One at a time. A second attempt would spawn a second server racing the same port, and its result
960
+ // would overwrite the first one's, which is what the page is about to read.
961
+ guard LaunchStatus.shared.beginAttempt() else { return .refused }
962
+ defer { LaunchStatus.shared.finishAttempt() }
963
+
964
+ // Resolved BEFORE anything is stopped, because it is what decides whether this app can put a
965
+ // dashboard back. Doing it after the takeover cost a user their working dashboard: on a Mac whose
966
+ // baked path a node upgrade had moved, the app stopped a perfectly good older dashboard, then
967
+ // discovered it could not start a replacement, and rendered the one failure page that deliberately
968
+ // offers no Retry. Taking the port is only defensible when there is something to put on it.
969
+ let interpreter = resolveNodePath(RADAR_NODE)
970
+
971
+ // No state is written on entry. Every exit below records one, so the only way to observe .unknown
972
+ // is before the first attempt ever ran, which is exactly what it means.
973
+ //
974
+ // A dashboard on the port is normally this app's answer: use it. The exception is one that is
975
+ // OLDER than this app, which an upgrade leaves behind whenever the old app was killed rather than
976
+ // quit, or when the dashboard belongs to a launcher or a Claude Code session running older code.
977
+ // Adopting that server shows the previous version's dashboard indefinitely, and the badge reports
978
+ // the process serving the port, so the app looks like the install never happened.
979
+ if case .answering(let runningVersion, let inUse) = dashboardProbe() {
980
+ // Read by every arm that logs. Only reachable with a version that parsed once the verdict is
981
+ // .older, so the fallback text is unreachable in practice and exists so this cannot become a
982
+ // force-unwrap later.
983
+ let theirs = runningVersion ?? "an unreadable version"
984
+ let decision = portTakeoverDecision(
985
+ verdict: staleDashboardVerdict(running: runningVersion, mine: RADAR_APP_VERSION),
986
+ haveInterpreter: interpreter != nil,
987
+ inUse: inUse,
988
+ respectInUse: respectInUse)
989
+ switch decision {
990
+ case .keepNotOlder:
991
+ LaunchStatus.shared.set(.started)
992
+ return .started
993
+ case .keepNoInterpreter:
994
+ // The node-missing page comes later and says the useful thing. Stopping a working dashboard on
995
+ // the way to it would only take away the one thing still functioning.
996
+ appendLaunchLog("launch: the dashboard on the port is Radar \(theirs), older than this app, but this app cannot start a replacement. Leaving it alone.")
997
+ LaunchStatus.shared.set(.started)
998
+ return .started
999
+ case .keepInUse:
1000
+ // Named by KIND. The whole point of reading the kind is that a stray window and a live agent
1001
+ // session are different reasons to leave a stale dashboard alone, and this line is the one
1002
+ // place a person goes to find out why the app did not upgrade itself.
1003
+ // Each arm names what a person can do next, because this log is the only place they can find out
1004
+ // why the version badge did not move. "Tries to take it" rather than "takes it": a refresh reaches
1005
+ // stopStaleDashboard, whose still-serving arm declines on purpose (see below), so promising a
1006
+ // replacement here would be a promise another branch refuses.
1007
+ switch inUse {
1008
+ 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.")
1010
+ case .tab:
1011
+ 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.")
1012
+ case .someoneUnnamed:
1013
+ 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.")
1014
+ case .no, .cannotTell:
1015
+ // Not reachable, since keepInUse is only answered for a claim. Logged rather than skipped so
1016
+ // that if the decision and the claim ever disagree, the log says so instead of going quiet, and
1017
+ // worded so the reader knows the fault is here rather than on their machine.
1018
+ appendLaunchLog("launch: the dashboard on the port is Radar \(theirs), older than this app, and was left alone with nothing claiming it. That combination should not happen, so it is a bug in this app.")
1019
+ }
1020
+ LaunchStatus.shared.set(.started)
1021
+ return .started
1022
+ case .take:
1023
+ // Name the claim. This is the one line written when somebody may be about to lose their server, so
1024
+ // it says whether anyone was there and, when someone was, that a refresh is what overrode them.
1025
+ let claim: String
1026
+ switch inUse {
1027
+ case .no: claim = "nobody is using it"
1028
+ case .cannotTell: claim = "it could not say whether anyone is using it"
1029
+ case .tab: claim = "another window has it open, which this refresh overrides"
1030
+ case .someoneUnnamed: claim = "it says someone is using it without saying who, which this refresh overrides"
1031
+ case .mcp: claim = "an agent session is using it, which should have kept it, so this is a bug in this app"
1032
+ }
1033
+ 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.")
1034
+ switch stopStaleDashboard() {
1035
+ case .freed:
1036
+ appendLaunchLog("launch: Radar \(theirs) stopped and the port is free. Starting \(RADAR_APP_VERSION).")
1037
+ case .stillServing:
1038
+ // Still bound after being asked, which a long recording finalize can do, since the server
1039
+ // closes its listener last. Spawning into that costs the user the thing they still had: our
1040
+ // child loses the bind, adopts the dying server, and the window loads it just before it exits,
1041
+ // ending on the page that blames idle auto-close for something this app caused. Keeping the
1042
+ // stale dashboard leaves them exactly where they were, which is worse than the upgrade and
1043
+ // better than a broken window.
1044
+ 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.")
1045
+ LaunchStatus.shared.set(.started)
1046
+ return .started
1047
+ case .couldNotTell(let why):
1048
+ // Not the same as still serving. The port may well be free, and the spawned child's own
1049
+ // EADDRINUSE path settles it either way, with the version note it already prints.
1050
+ 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.")
1051
+ }
1052
+ }
1053
+ }
1054
+
1055
+ guard let node = interpreter else {
1056
+ // The one failure the window could never explain on its own, and the only one where trying again
1057
+ // cannot help: the path is fixed at compile time, so the page has to name the repair instead.
1058
+ LaunchStatus.shared.set(.nodeMissing(baked: RADAR_NODE))
1059
+ appendLaunchLog("launch: node was not at the baked path \(RADAR_NODE). The dashboard was not started.")
1060
+ NSLog("radar: node was not at the baked path \(RADAR_NODE)")
1061
+ return .failed
1062
+ }
57
1063
 
58
1064
  let task = Process()
59
- task.executableURL = URL(fileURLWithPath: RADAR_NODE)
1065
+ task.executableURL = URL(fileURLWithPath: node)
60
1066
  task.arguments = [RADAR_WEB_BIN]
61
1067
  // SLACK_RADAR_NO_OPEN stops the server from opening a browser tab of its own, which would put a
62
1068
  // second copy of the dashboard on screen next to this window.
@@ -65,28 +1071,77 @@ func ensureDashboardRunning() {
65
1071
  task.environment = env
66
1072
  // Detach stdio to a log rather than inheriting: an inherited pipe nobody drains fills its buffer
67
1073
  // and blocks the server once it has logged enough.
68
- let logPath = ("~/Library/Logs/slack-radar-dashboard.log" as NSString).expandingTildeInPath
69
- FileManager.default.createFile(atPath: logPath, contents: nil)
70
- if let handle = FileHandle(forWritingAtPath: logPath) {
71
- handle.seekToEndOfFile()
1074
+ if let handle = radarLogHandle() {
72
1075
  task.standardOutput = handle
73
1076
  task.standardError = handle
74
1077
  }
75
1078
  do {
76
1079
  try task.run()
1080
+ // Recorded the moment the spawn succeeds, not after the probe confirms the server answers: this
1081
+ // app started the process either way, and one that came up but could not be reached from here is
1082
+ // still this app's to stop on quit.
1083
+ SpawnedDashboard.shared.record(task)
77
1084
  } catch {
78
- // Nothing to do but continue: the window will show a connection error, which is the honest
79
- // signal. A modal dialog here would be worse, since the usual cause is a port already taken
80
- // by a healthy dashboard this probe merely failed to reach.
81
- NSLog("radar: could not start the dashboard server: \(error)")
82
- return
1085
+ // Recorded rather than raised: a modal dialog would be worse, since one cause is a port already
1086
+ // held by a healthy dashboard this probe merely failed to reach. If the window then loads, nobody
1087
+ // ever sees this; if it does not, the page carries the cause rather than the symptom.
1088
+ LaunchStatus.shared.set(.serverFailed(node: node, detail: error.localizedDescription))
1089
+ appendLaunchLog("launch: the dashboard server did not come up with \(node). \(error.localizedDescription)")
1090
+ NSLog("radar: the dashboard server did not come up with \(node). \(error.localizedDescription)")
1091
+ return .failed
83
1092
  }
84
1093
 
85
- // ~10s ceiling, then load anyway so a merely-slow server still gets a window.
86
- for _ in 0..<50 {
87
- if dashboardAlive() { return }
1094
+ // A wall-clock deadline, not a count of sleeps: each probe can itself wait up to 2s against a port
1095
+ // that accepts and never answers, so a fixed iteration count would mean one wait in the normal case
1096
+ // and a much longer one there.
1097
+ let attemptStarted = Date()
1098
+ let deadline = attemptStarted.addingTimeInterval(startupDeadlineSeconds)
1099
+ var lastInconclusive: String?
1100
+ while Date() < deadline {
1101
+ let probe = dashboardProbe()
1102
+ if case .answering = probe {
1103
+ LaunchStatus.shared.set(.started)
1104
+ return .started
1105
+ }
1106
+ lastInconclusive = inconclusiveReason(probe)
1107
+ // An interpreter that cannot run the dist is done in milliseconds, and waiting out the full
1108
+ // deadline for a process that has already gone is time the user spends looking at nothing.
1109
+ if !task.isRunning { break }
88
1110
  Thread.sleep(forTimeInterval: 0.2)
89
1111
  }
1112
+ // One last look before calling it a failure: a server that answers just past the deadline would
1113
+ // otherwise leave a failure recorded behind a window that loads perfectly well.
1114
+ let finalProbe = dashboardProbe()
1115
+ if case .answering = finalProbe {
1116
+ LaunchStatus.shared.set(.started)
1117
+ return .started
1118
+ }
1119
+ lastInconclusive = inconclusiveReason(finalProbe)
1120
+
1121
+ // Read once, and the exit fields only when the child has actually gone: Foundation does not promise
1122
+ // a meaningful status for a process that is still running.
1123
+ let childRunning = task.isRunning
1124
+ let status: Int32 = childRunning ? 0 : task.terminationStatus
1125
+ let signaled = childRunning ? false : task.terminationReason == .uncaughtSignal
1126
+ let state = launchFailureState(
1127
+ node: node,
1128
+ lastInconclusive: lastInconclusive,
1129
+ childRunning: childRunning,
1130
+ terminationStatus: status,
1131
+ signaled: signaled,
1132
+ elapsedSeconds: Int(Date().timeIntervalSince(attemptStarted).rounded()))
1133
+ LaunchStatus.shared.set(state)
1134
+ // The log line is derived from the state rather than recomputed, so what the log says and what the
1135
+ // page says cannot drift apart.
1136
+ switch state {
1137
+ case .unconfirmed(_, let detail):
1138
+ appendLaunchLog("launch: this window could not reach \(RADAR_URL) and could not tell why. \(detail)")
1139
+ case .serverFailed(_, let detail):
1140
+ appendLaunchLog("launch: the dashboard server did not come up with \(node). \(detail)")
1141
+ default:
1142
+ break
1143
+ }
1144
+ return .failed
90
1145
  }
91
1146
 
92
1147
  /// Fire-and-forget check that a newer Radar is available, so a dock app that install-app baked
@@ -100,15 +1155,20 @@ func ensureDashboardRunning() {
100
1155
  /// installed mcp/index.js is guaranteed to be from THIS build, so it knows to check the registry
101
1156
  /// itself before ever touching npx -- see install-app.ts's runSelfHealPrecheck().
102
1157
  func triggerSelfHealCheck() {
1158
+ // Existence-checked, like the dashboard start. It used to be spawned under the baked path whatever
1159
+ // state that path was in, so a node upgrade took the repair path down with it silently. Running is
1160
+ // not repairing, though: the check rebuilds only when a newer version is published.
1161
+ guard let node = resolveNodePath(RADAR_NODE) else {
1162
+ appendLaunchLog("launch: node was not at the baked path \(RADAR_NODE), skipping the self-heal check.")
1163
+ NSLog("radar: no node found, skipping the self-heal check")
1164
+ return
1165
+ }
103
1166
  let task = Process()
104
- task.executableURL = URL(fileURLWithPath: RADAR_NODE)
1167
+ task.executableURL = URL(fileURLWithPath: node)
105
1168
  task.arguments = [RADAR_MCP_BIN, "install-app", "--self-heal-precheck"]
106
1169
  // Same log file ensureDashboardRunning() writes to, so the outcome shows up next to the
107
1170
  // dashboard's own launch log. Not inherited stdio: an unread pipe can block the child.
108
- let logPath = ("~/Library/Logs/slack-radar-dashboard.log" as NSString).expandingTildeInPath
109
- FileManager.default.createFile(atPath: logPath, contents: nil)
110
- if let handle = FileHandle(forWritingAtPath: logPath) {
111
- handle.seekToEndOfFile()
1171
+ if let handle = radarLogHandle() {
112
1172
  task.standardOutput = handle
113
1173
  task.standardError = handle
114
1174
  }
@@ -120,18 +1180,16 @@ func triggerSelfHealCheck() {
120
1180
  }
121
1181
  }
122
1182
 
123
- extension FileManager {
124
- /// Create the file only if it does not exist, so an existing log is appended to, not truncated.
125
- func createFile(atPath path: String, contents: Data?) {
126
- if !fileExists(atPath: path) {
127
- createFile(atPath: path, contents: contents, attributes: nil)
128
- }
129
- }
130
- }
131
-
132
1183
  class AppDelegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKDownloadDelegate, WKScriptMessageHandler {
133
1184
  var window: NSWindow!
134
1185
  var webView: WKWebView!
1186
+ // Whether a quit deferral has been started, and whether it has been released (see beginQuitDeferral
1187
+ // and releaseQuit). One lock over both, because the three things that touch them run on different
1188
+ // queues: a second Cmd+Q on the main thread, the stop work finishing on a background queue, and the
1189
+ // deadline block on a background queue.
1190
+ private let quitReplyLock = NSLock()
1191
+ private var quitDeferralStarted = false
1192
+ private var quitReplied = false
135
1193
  // Diverting a main-frame navigation response to a download cancels the frame load underneath
136
1194
  // it, and WebKit reports that cancellation to didFail/didFailProvisionalNavigation exactly like
137
1195
  // a real connection failure ("Frame load interrupted"). A token recorded just before that
@@ -197,7 +1255,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKDown
197
1255
  // Minimum that keeps the feed's virtualized columns usable rather than clipped.
198
1256
  window.minSize = NSSize(width: 900, height: 600)
199
1257
 
200
- webView.load(URLRequest(url: radarURL))
1258
+ webView.load(URLRequest(url: dashboardPageURL))
201
1259
  NSApp.activate(ignoringOtherApps: true)
202
1260
  }
203
1261
 
@@ -207,6 +1265,157 @@ class AppDelegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKDown
207
1265
  return true
208
1266
  }
209
1267
 
1268
+ /// Stop the dashboard this app started, on the way out.
1269
+ ///
1270
+ /// A spawned child is not killed when its parent exits, so quitting left the server running on the
1271
+ /// port with nothing on screen to suggest it. That is what made an upgrade look like it did not
1272
+ /// take: the next launch found the old server still there and served it. Quitting now means the
1273
+ /// port is free for whatever runs next.
1274
+ ///
1275
+ /// Only the process this app spawned. A dashboard that was already up when this app launched
1276
+ /// belongs to something else and is left running.
1277
+ ///
1278
+ /// WHY THIS HOOK AND NOT applicationWillTerminate. The stop is network work with a bound of about
1279
+ /// five and a half seconds (a 2s claim probe, a 0.5s shutdown request, a 3s poll of the port).
1280
+ /// applicationWillTerminate runs on the main thread and AppKit gives it no way to say "not yet", so
1281
+ /// all of that was spent frozen, with a beachball on the way out. A person who force-quits through
1282
+ /// that inflicts the exact orphaned server this path exists to prevent, so the fix was provoking the
1283
+ /// bug. applicationShouldTerminate can defer: `.terminateLater` keeps the app alive, the work runs on
1284
+ /// a background queue where it blocks nothing, and `reply(toApplicationShouldTerminate:)` releases the
1285
+ /// quit when it is done.
1286
+ ///
1287
+ /// Honest limit, unchanged: this runs on an ordinary quit (the menu item, Cmd+Q, the last window
1288
+ /// closing). A crash or a SIGKILL never reaches it, and leaves the server up exactly as before.
1289
+ func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
1290
+ // Belt and braces, and measured to be exactly that rather than a live path. A second quit during the
1291
+ // deferral does NOT reach here: AppKit swallows a second menu quit and a window close while it is
1292
+ // waiting for a reply, so this guard never returns false through anything the app wires. It stays
1293
+ // because the one way to re-enter is a bare `NSApp.terminate` call, which today would abandon the
1294
+ // in-flight stop and exit with the child un-signalled, and because a guard is cheaper than the next
1295
+ // reader having to rediscover that. If it ever does fire, the second caller waits on the first rather
1296
+ // than starting a second stop against a list the first one already took.
1297
+ guard beginQuitDeferral() else { return .terminateLater }
1298
+ DispatchQueue.global().async {
1299
+ let outcome = SpawnedDashboard.shared.stopIfOurs(
1300
+ askToStop: { postDashboardShutdown(waitSeconds: quitShutdownRequestWaitSeconds) },
1301
+ inUse: {
1302
+ // One probe, and only when there is something of ours still running. Reading the claim from
1303
+ // /spec rather than from the shutdown reply, because a dashboard answers /shutdown before it
1304
+ // has stopped, so by then the answer is about a server already on its way out.
1305
+ //
1306
+ // Asked as a STOP decision. That is what widens the tab window to the one sized for a throttled
1307
+ // background tab, and what stops the server guessing "an agent session" about a process this app
1308
+ // spawned and no window has opened yet.
1309
+ //
1310
+ // Both non-answering results (notListening, couldNotTell) fold into cannotTell here, and
1311
+ // stopIfOurs stops on it; the reasoning lives there. Split them here if that ever changes.
1312
+ if case .answering(_, let use) = dashboardProbe(deciding: .stop) { return use }
1313
+ return .cannotTell
1314
+ },
1315
+ note: appendLaunchLog
1316
+ )
1317
+ switch outcome {
1318
+ case .nothingOurs:
1319
+ break
1320
+ case .leftForSession:
1321
+ appendLaunchLog("quit: the dashboard this app started is being driven by an agent session (Claude Code), so it was left running.")
1322
+ case .leftForWindow:
1323
+ appendLaunchLog("quit: the dashboard this app started is open in another window, so it was left running.")
1324
+ case .leftUnattributed:
1325
+ appendLaunchLog("quit: the dashboard this app started says someone is using it without saying who, so it was left running.")
1326
+ case .left:
1327
+ appendLaunchLog("quit: the dashboard this app started was asked to stop, and it did.")
1328
+ case .signalled:
1329
+ // The interesting line of the two. It means the graceful request did not land in time, so the
1330
+ // server was signalled instead and whatever it was writing was cut off.
1331
+ appendLaunchLog("quit: the dashboard this app started did not stop when asked, so it was signalled.")
1332
+ }
1333
+ self.releaseQuit()
1334
+ }
1335
+ // The backstop, for the case the bounds inside the work do not hold. Nothing but a reply ends a
1336
+ // `.terminateLater` deferral, so a wait that wedges would leave a window on screen that Cmd+Q no
1337
+ // longer closes. Comfortably longer than the ~5.5s the work can take, so it never pre-empts a stop
1338
+ // that is merely slow; when it does fire, the app quits and leaves the server up, which is the
1339
+ // pre-existing behaviour rather than a new failure.
1340
+ //
1341
+ // Scheduled on a BACKGROUND queue, not with DispatchQueue.main.asyncAfter and not with a run-loop
1342
+ // Timer, and the difference is the whole point of the backstop.
1343
+ //
1344
+ // main.asyncAfter has the same single failure the reply has (see releaseQuit): when the quit was entered
1345
+ // from inside a main-queue block, the nested wait never drains the main queue again, so a backstop queued
1346
+ // there fires on every path a person takes today and on none that a harness or a future caller enters
1347
+ // that way. Measured in exactly that harness: it did not fire.
1348
+ //
1349
+ // A Timer in `.common` does fire, but it shares a failure mode with the bug it exists to catch, since
1350
+ // it needs the main run loop to iterate in a mode it was registered for. A backstop should not depend
1351
+ // on the same liveness as the thing it backstops. A background timer depends on neither, so the
1352
+ // release is always REACHED; whether the reply can then be delivered still depends on the main loop
1353
+ // turning, which nothing here can change, and that residual case is an unquittable window either way.
1354
+ //
1355
+ // It also avoids owning a Timer that has to be invalidated once the work replies first. Nothing needs
1356
+ // cancelling: releaseQuit is a one-shot, so a late backstop finds the quit already answered.
1357
+ DispatchQueue.global().asyncAfter(deadline: .now() + quitDeferralDeadlineSeconds) { [weak self] in
1358
+ self?.releaseQuit()
1359
+ }
1360
+ return .terminateLater
1361
+ }
1362
+
1363
+ /// Whether this caller owns the deferral, or a deferral is already in flight.
1364
+ ///
1365
+ /// Separate from the reply latch below on purpose: that one answers "has the quit been released", this
1366
+ /// one answers "is a release already coming". Sharing one flag would make the second Cmd+Q either
1367
+ /// duplicate the stop or, worse, release the quit while the first stop is mid-poll, which exits the app
1368
+ /// before a stubborn child has been signalled.
1369
+ private func beginQuitDeferral() -> Bool {
1370
+ quitReplyLock.lock()
1371
+ defer { quitReplyLock.unlock() }
1372
+ if quitDeferralStarted { return false }
1373
+ quitDeferralStarted = true
1374
+ return true
1375
+ }
1376
+
1377
+ /// Let the deferred quit finish, once and only once.
1378
+ ///
1379
+ /// A `.terminateLater` app quits when this is answered and NEVER otherwise, so the reply is the whole
1380
+ /// contract, and both ways of getting it wrong are guarded: replying twice answers a question AppKit is
1381
+ /// no longer asking, and never replying leaves a window on screen that no longer responds to Cmd+Q.
1382
+ ///
1383
+ /// HOW the reply is delivered matters, and the reason is narrower than it first looks, so it is worth
1384
+ /// stating exactly rather than generally.
1385
+ ///
1386
+ /// `reply(toApplicationShouldTerminate:)` must run on the main thread, and the obvious way there from
1387
+ /// this background caller is `DispatchQueue.main.async`. That works on every path a person can actually
1388
+ /// take, and it was measured working: a quit from the menu item, a quit from the keyboard, closing the
1389
+ /// last window, and an Apple Event all deliver the reply and the app exits.
1390
+ ///
1391
+ /// It fails in one case. When `terminate` is entered from INSIDE a main-queue block, the nested wait
1392
+ /// AppKit runs is entered from within a main-queue drain, and CFRunLoop will not re-enter that drain, so
1393
+ /// a reply queued on the main queue never runs and the app keeps its window on screen until it is force
1394
+ /// quit. Measured both ways: `NSApp.terminate` from a `DispatchQueue.main.async` block hangs, and the
1395
+ /// same terminate delivered from the run loop exits cleanly.
1396
+ ///
1397
+ /// Nothing in this app enters `terminate` that way today. CFRunLoop is used anyway because it does not
1398
+ /// care how the quit arrived: it delivers in every case above and in the main-queue case as well. The
1399
+ /// cost is one unfamiliar call, and what it buys is a reply that does not depend on a detail of the
1400
+ /// caller that no future edit here would think to preserve.
1401
+ ///
1402
+ /// The common modes are required rather than decorative. `CFRunLoopPerformBlock` in the default mode
1403
+ /// alone never ran in any measured case, because the wait sits in `NSModalPanelRunLoopMode`. The wake
1404
+ /// follows the block, in that order, because a block enqueued against an idle loop waits for the next
1405
+ /// turn: measured delivery was about a millisecond with the wake after, and hundreds of milliseconds
1406
+ /// with it before or absent.
1407
+ private func releaseQuit() {
1408
+ quitReplyLock.lock()
1409
+ let alreadyReplied = quitReplied
1410
+ quitReplied = true
1411
+ quitReplyLock.unlock()
1412
+ guard !alreadyReplied else { return }
1413
+ CFRunLoopPerformBlock(CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue) {
1414
+ NSApp.reply(toApplicationShouldTerminate: true)
1415
+ }
1416
+ CFRunLoopWakeUp(CFRunLoopGetMain())
1417
+ }
1418
+
210
1419
  /// Route anything that is not our own localhost dashboard to the real browser. A Slack or docs
211
1420
  /// link opened inside this window would strand the user in an app with no back button, no tabs,
212
1421
  /// and no address bar.
@@ -369,32 +1578,34 @@ class AppDelegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKDown
369
1578
  showLoadFailure(error)
370
1579
  }
371
1580
 
1581
+ /// 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.
372
1583
  private func showLoadFailure(_ error: Error) {
373
- let html = """
374
- <html><body style="background:#0b0f14;color:#e8f0f8;font:14px -apple-system,sans-serif;\
375
- display:flex;align-items:center;justify-content:center;height:100vh;margin:0">
376
- <div style="max-width:34em;text-align:center">
377
- <div style="font-size:15px;margin-bottom:.6em">Could not reach the Radar dashboard</div>
378
- <div style="color:#8aa0b4;line-height:1.6">\(RADAR_URL) did not respond.<br>
379
- \(error.localizedDescription)<br><br>
380
- Press the button below, or press &#8984;R once it starts.</div>
381
- <button onclick="window.webkit.messageHandlers.radarRetry.postMessage('retry')"
382
- style="margin-top:1em;padding:.5em 1.2em;font:14px -apple-system,sans-serif;\
383
- background:#39d98a;color:#0b0f14;border:none;border-radius:6px;cursor:pointer">
384
- Retry</button>
385
- </div></body></html>
386
- """
387
- webView.loadHTMLString(html, baseURL: nil)
1584
+ webView.loadHTMLString(
1585
+ failurePage(state: LaunchStatus.shared.get(), url: RADAR_URL, webKitError: error.localizedDescription),
1586
+ baseURL: nil
1587
+ )
388
1588
  }
389
1589
 
390
- /// Handles the failure page's Retry button. Runs ensureDashboardRunning() on a background
391
- /// queue, NOT the main thread: its polling loop sleeps up to ~10s, and calling it here (after
392
- /// the window already exists) would freeze the whole app, including the button just clicked.
393
- private func handleRetryMessage() {
1590
+ /// Make sure the server is up, then go back to the dashboard. Shared by the failure page's Retry
1591
+ /// button and by Cmd+R, so the two controls the page can offer behave the same way.
1592
+ ///
1593
+ /// Runs ensureDashboardRunning() on a background queue, NOT the main thread: its polling loop
1594
+ /// sleeps up to ~10s, and calling it here (after the window already exists) would freeze the whole
1595
+ /// app, including the control that was just used.
1596
+ func retryLoad() {
394
1597
  DispatchQueue.global().async {
395
- ensureDashboardRunning()
1598
+ // Only a REFUSED attempt skips the reload: another one is mid-flight and will load the window
1599
+ // itself, and reloading now would fail against a server that is still starting and re-render the
1600
+ // earlier attempt's page. A failed attempt reloads, because it just learned the cause and the
1601
+ // failure page is where that cause is shown. Nothing else re-renders it: showLoadFailure is only
1602
+ // reachable from a load callback.
1603
+ // respectInUse: false, because this is the user asking. If this app adopted a stale dashboard,
1604
+ // its own window is the live tab that dashboard reports, so honouring the in-use guard here would
1605
+ // refuse the person pressing the button on behalf of the person pressing the button.
1606
+ if case .refused = ensureDashboardRunning(respectInUse: false) { return }
396
1607
  DispatchQueue.main.async {
397
- self.webView.load(URLRequest(url: radarURL))
1608
+ self.webView.load(URLRequest(url: dashboardPageURL))
398
1609
  }
399
1610
  }
400
1611
  }
@@ -409,7 +1620,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKDown
409
1620
  ) {
410
1621
  switch message.name {
411
1622
  case "radarReveal": handleRevealMessage(message)
412
- case "radarRetry": handleRetryMessage()
1623
+ case "radarRetry": retryLoad()
413
1624
  default: break
414
1625
  }
415
1626
  }
@@ -417,21 +1628,26 @@ class AppDelegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKDown
417
1628
 
418
1629
  // Cmd+R goes home, not just reload. WKWebView has no menu bar here, so the shortcut needs wiring
419
1630
  // by hand. See the comment inside sendEvent below for why this is the ONLY shortcut here, and why
420
- // it loads radarURL directly rather than calling webView.reload().
1631
+ // it loads dashboardPageURL (radarURL carrying this app's presence id) rather than calling
1632
+ // webView.reload().
421
1633
  class ReloadingApplication: NSApplication {
422
1634
  override func sendEvent(_ event: NSEvent) {
423
- // Load radarURL directly rather than webView.reload(): reload() repeats whatever is CURRENTLY
424
- // loaded, which is exactly the page a stranded window needs to get away from, not back to. A
425
- // second shortcut (originally Cmd+Left) for this used to exist here too, but Cmd+Left is the
426
- // standard macOS binding for "move cursor to start of line" -- hijacking it at this level,
427
- // before any focused search or filter field ever sees the key, broke normal text editing
428
- // anywhere in the dashboard. Cmd+R already covers the "get me back to the dashboard" need
429
- // without colliding with anything: it has no default text-editing meaning.
1635
+ // Goes through retryLoad() rather than webView.reload(): reload() repeats whatever is CURRENTLY
1636
+ // loaded, which is exactly the page a stranded window needs to get away from, not back to, and
1637
+ // retryLoad() also starts the server first, so Cmd+R does the same work as the Retry button the
1638
+ // failure page offers. A second shortcut (originally Cmd+Left) for this used to exist here too,
1639
+ // but Cmd+Left is the standard macOS binding for "move cursor to start of line" -- hijacking it
1640
+ // at this level, before any focused search or filter field ever sees the key, broke normal text
1641
+ // editing anywhere in the dashboard. Cmd+R already covers the "get me back to the dashboard"
1642
+ // need without colliding with anything: it has no default text-editing meaning.
1643
+ // isARepeat is dropped rather than passed through: holding the key would otherwise queue one
1644
+ // attempt per repeat, and the single-flight gate would refuse them all anyway.
430
1645
  if event.type == .keyDown,
1646
+ !event.isARepeat,
431
1647
  event.modifierFlags.contains(.command),
432
1648
  event.charactersIgnoringModifiers?.lowercased() == "r",
433
1649
  let delegate = self.delegate as? AppDelegate {
434
- delegate.webView.load(URLRequest(url: radarURL))
1650
+ delegate.retryLoad()
435
1651
  return
436
1652
  }
437
1653
  super.sendEvent(event)