@slack/radar-mcp 1.18.1 → 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.
@@ -296,6 +296,15 @@ export function registerScreenCleanupOnBind() {
296
296
  // harmlessly), it does not misfire an auto-close. Exported so tests pin the real constant
297
297
  // instead of a duplicated copy.
298
298
  export const TAB_LIVENESS_MS = 75_000;
299
+ /**
300
+ * How recently a tab must have polled to count as SOMEONE USING the dashboard, which is a different
301
+ * question from whether it is stale enough to auto-close, and takes a much tighter answer.
302
+ *
303
+ * Three of the dashboard's own five second profile polls. Generous enough that a live tab never
304
+ * flickers out of it, tight enough that closing a window releases the port in seconds rather than in
305
+ * the minute and a quarter TAB_LIVENESS_MS would impose.
306
+ */
307
+ export const TAB_IN_USE_MS = 15_000;
299
308
  // How long the dashboard must have ZERO live tabs before auto-close fires. Sized at ~3x the
300
309
  // worst-case legitimate gap between presence pings (~60-90s under intensive throttling), so a
301
310
  // backgrounded tab is never mistaken for a closed one. Not 90s — that is barely one throttled
@@ -303,10 +312,16 @@ export const TAB_LIVENESS_MS = 75_000;
303
312
  // backgrounded tab outright, permanently stopping its polling; auto-close eventually firing in
304
313
  // that case is correct behavior ("nobody is looking"), not a bug to work around.
305
314
  export const AUTO_CLOSE_GRACE_MS = 5 * 60_000;
315
+ // How long an authored write keeps a dashboard counted as in use by an agent session, when no tab is
316
+ // open. Its own constant rather than borrowing AUTO_CLOSE_GRACE_MS, which starts at the same value
317
+ // and answers a different question: that one decides when a process should end ITSELF, this one
318
+ // decides how long a quiet session may hold a port against another process taking it. Retuning
319
+ // either for its own reason must not silently retune the other.
320
+ export const MCP_IN_USE_MS = 5 * 60_000;
306
321
  // Sweep cadence: cheap (a map prune + a subtraction), frequent enough that auto-close fires
307
322
  // promptly once the grace window elapses.
308
323
  const AUTO_CLOSE_SWEEP_MS = 15_000;
309
- const presence = { tabs: new Map(), emptySince: null, everSeen: false };
324
+ const presence = { tabs: new Map(), emptySince: null, everSeen: false, keepAliveAt: null };
310
325
  /**
311
326
  * Pure auto-close decision, mirroring screen.ts's nextViewerAction/shouldRelaunch precedent:
312
327
  * the sweep owns the timestamp bookkeeping, this owns only the yes/no. Close only when there
@@ -323,6 +338,96 @@ export function shouldAutoClose(liveTabs, everSeen, msSinceEmpty) {
323
338
  return false;
324
339
  return msSinceEmpty >= AUTO_CLOSE_GRACE_MS;
325
340
  }
341
+ /**
342
+ * Whether anyone is using this dashboard RIGHT NOW, which is a different question from
343
+ * shouldAutoClose() above and deliberately not the same answer.
344
+ *
345
+ * shouldAutoClose adds the grace window, because a process deciding to end itself should be slow
346
+ * about it. This is read by a DIFFERENT process deciding whether it may take the port, and there the
347
+ * grace window is exactly wrong: the five minutes after a dock app quits and its tab closes is the
348
+ * window an upgrade lands in, and a leftover nobody is looking at is the thing that most needs
349
+ * replacing.
350
+ *
351
+ * So: a live tab counts, and an MCP session with no tab open counts (markKeepAlive clears the empty
352
+ * marker without setting everSeen, which is what keeps an hour-long debugging session alive), but a
353
+ * dashboard whose last tab has gone does not.
354
+ *
355
+ * Exported for unit testing without a clock or a socket, same as shouldAutoClose.
356
+ */
357
+ export function isInUse(now = Date.now()) {
358
+ return inUseReason(now) !== "no";
359
+ }
360
+ /**
361
+ * WHY this dashboard is in use, not merely whether, because the two claims are worth different
362
+ * decisions to the process asking.
363
+ *
364
+ * A "tab" claim is a window someone has open. A "mcp" claim is an agent session driving this
365
+ * dashboard with no window of its own, and stopping that costs the session's pulled databases, its
366
+ * device pin and its logcat ring, none of which it can get back. A single yes/no cannot tell those
367
+ * apart, so a launcher had to treat them the same, and the only safe reading of "the same" is the
368
+ * cautious one, which then blocks the upgrade this whole path exists to perform.
369
+ *
370
+ * Priority is deliberate: an mcp claim outranks a tab claim, because the app's OWN window is a tab
371
+ * and a decision about whether to disturb someone else must not be answered by our own presence.
372
+ *
373
+ * `ignoreTab` is how a caller asks the narrower question it actually has: is anyone OTHER than my own
374
+ * window using this. The dock app generates the presence id, hands it to the page it loads, and sends
375
+ * it back here, so its own window stops answering for everybody else. Without it the app could not
376
+ * tell its own tab from a real second browser tab, and had to guess; guessing either way is wrong,
377
+ * because one reading kills a page someone is reading and the other never stops anything.
378
+ */
379
+ export function inUseReason(now = Date.now(), ignoreTab, decision = "take") {
380
+ // A dashboard NO tab has ever opened, which is what an MCP-spawned one looks like. The server
381
+ // refuses to auto-close those for a reason that applies here word for word: nobody can have closed
382
+ // a window that never existed, so its quietness says nothing about whether the session driving it
383
+ // is finished. Without this the in-use answer was more permissive than the server's own protection,
384
+ // and a twenty-minute debugging session with no tab open read as a leftover.
385
+ //
386
+ // Only for a caller deciding whether to TAKE the port. To a caller deciding whether to STOP a server it
387
+ // started itself, this reading is a false positive with teeth: the app spawns a server, its window fails
388
+ // to load (a proxy with no loopback bypass is the documented case), no tab ever polls, and the quit path
389
+ // is told an agent session is driving it. It then leaves the server running, logs a session that does not
390
+ // exist, and the server cannot auto-close either, because shouldAutoClose reads the same everSeen flag.
391
+ // The port is held for good by a process with nothing on screen, which is exactly the orphan the quit
392
+ // path exists to prevent. The caller that spawned the process does not need this guess: it knows the
393
+ // process is its own, and "no window ever opened it" is then an answer rather than a gap.
394
+ if (!presence.everSeen && decision === "take")
395
+ return "mcp";
396
+ // An authored write that named no tab, which is what an agent session's looks like. The dashboard
397
+ // page makes authored writes too (a page load that finds a blank spec, every mode switch and filter
398
+ // Apply), and those name their tab and are credited as presence instead (creditAuthoredWrite), so a
399
+ // window changing a filter does not read as a session here. Checked BEFORE the tab loop so a
400
+ // session driving a dashboard that also has a window open still reads as mcp.
401
+ if (presence.keepAliveAt !== null && now - presence.keepAliveAt <= MCP_IN_USE_MS)
402
+ return "mcp";
403
+ // A tab that is still polling, and how recently it must have polled depends on what the caller is about
404
+ // to do.
405
+ //
406
+ // TAKING the port uses 15s, deliberately not the 75s auto-close uses. That 75s exists so a THROTTLED
407
+ // background tab is not mistaken for a closed one, and borrowing it here made a window someone closed a
408
+ // minute ago still report "in use", which blocked the upgrade for 75 seconds after a window closed,
409
+ // exactly the quit-and-reopen the installer instructs. Being tight costs a relaunch a few seconds later,
410
+ // which is what the user was asking for anyway.
411
+ //
412
+ // STOPPING uses the 75s, because that justification does not survive the change of caller: nothing
413
+ // relaunches a server after it is stopped. A hidden tab throttled to one poll a minute reads as absent at
414
+ // 15s, and stopping its server leaves it reloading onto a dead port with no way to recover from that tab.
415
+ // Being loose here costs one orphaned server, which the launch path already reclaims.
416
+ //
417
+ // Neither window helps a tab Chrome has DISCARDED, which stops polling forever. That is the same
418
+ // limitation auto-close names and accepts: a discarded tab reads as nobody looking.
419
+ const tabWindow = decision === "stop" ? TAB_LIVENESS_MS : TAB_IN_USE_MS;
420
+ for (const [id, ts] of presence.tabs) {
421
+ // Skipped BEFORE the freshness check, not after: the caller's own window is the freshest tab in the
422
+ // map, so an ordering that tests liveness first returns "tab" on it every time and the parameter
423
+ // does nothing.
424
+ if (ignoreTab !== undefined && id === ignoreTab)
425
+ continue;
426
+ if (now - ts <= tabWindow)
427
+ return "tab";
428
+ }
429
+ return "no";
430
+ }
326
431
  // A tab pinged /health with its id: record it live and remember a tab was seen. A fresh id
327
432
  // after zero live tabs is the 0->1 transition, so clear the empty marker immediately. `now` is
328
433
  // injectable so the sweep's staleness math is unit-testable with a fake clock.
@@ -341,8 +446,9 @@ export function touchTab(id, now = Date.now()) {
341
446
  * pin, and the pulled-DB cache. Deliberately does NOT set everSeen: an MCP-only dashboard that
342
447
  * nobody ever opened stays protected by the everSeen guard even after the MCP goes quiet.
343
448
  */
344
- export function markKeepAlive() {
449
+ export function markKeepAlive(now = Date.now()) {
345
450
  presence.emptySince = null;
451
+ presence.keepAliveAt = now;
346
452
  }
347
453
  /**
348
454
  * Whether a request may buy the process more life. True for our own client and the MCP, false
@@ -371,6 +477,78 @@ export function isAuthoredRequest(headers) {
371
477
  const essence = value.split(";")[0].trim().toLowerCase();
372
478
  return essence === "application/json";
373
479
  }
480
+ /**
481
+ * The shared strictness for both presence-id headers below.
482
+ *
483
+ * Strict for a duller reason than the security gates elsewhere in this file: a wrong read here is
484
+ * SILENT. An id that does not arrive intact matches no tab, and the only symptom is a dashboard that
485
+ * never gets replaced or a window that reports itself as somebody else.
486
+ *
487
+ * A REPEATED header is the case worth spelling out, because the obvious guess about it is wrong. Node does
488
+ * not hand a duplicated request header over as an array (only set-cookie arrives that way): it JOINS the
489
+ * values, so `X-Radar-Tab: A` sent twice arrives as the single string `"A, A"`. Measured. Taken at face
490
+ * value that becomes a presence key no tab will ever refresh, and for the next fifteen seconds a probe
491
+ * excluding `A` is told a tab holds the port. So a value carrying a comma is refused, and the array shape
492
+ * is still handled because the type admits it.
493
+ *
494
+ * The ids this accepts are generated by the app (a UUID) and by the page (a UUID, or a random decimal
495
+ * string in a browser without crypto.randomUUID), so refusing a comma costs nothing real.
496
+ */
497
+ function presenceIdHeader(value) {
498
+ if (typeof value !== "string")
499
+ return undefined;
500
+ if (value.length === 0 || value.includes(","))
501
+ return undefined;
502
+ return value;
503
+ }
504
+ /**
505
+ * "This request comes FROM the tab with this id." Sent by the dashboard page on its own authored
506
+ * writes, so a write can be credited to the window that made it.
507
+ */
508
+ export function readTabIdentity(headers) {
509
+ return presenceIdHeader(headers["x-radar-tab"]);
510
+ }
511
+ /**
512
+ * "Leave this id out of the answer." Sent by a launcher asking whether anyone OTHER than the window it
513
+ * owns is using this dashboard.
514
+ *
515
+ * A separate header from the identity one above, carrying the same value, and deliberately so: the app
516
+ * that sends this is NOT the tab. Its window may have failed to load, or may be showing the failure
517
+ * page. One header would invite a future route to treat the app's own probe as proof that its tab is
518
+ * live, which would record presence for a window that does not exist. Two names make that impossible
519
+ * rather than merely discouraged.
520
+ */
521
+ export function readIgnoredTab(headers) {
522
+ return presenceIdHeader(headers["x-radar-ignore-tab"]);
523
+ }
524
+ /**
525
+ * Which decision the caller says it is about to make. Anything other than the one recognised value reads as
526
+ * `take`, which is both the back-compatible answer (no installed launcher sends this) and the conservative
527
+ * one: it is the reading that protects a port rather than the one that permits a stop.
528
+ */
529
+ export function readInUseDecision(headers) {
530
+ return headers["x-radar-in-use-for"] === "stop" ? "stop" : "take";
531
+ }
532
+ /**
533
+ * Credit an authored write to whoever made it: a tab that named itself, or an agent session.
534
+ *
535
+ * The distinction is load-bearing, and getting it wrong was a real bug. `markKeepAlive` is what makes
536
+ * inUseReason answer "mcp", and the dashboard PAGE makes authored writes too: `bootDefault` posts
537
+ * /setspec on any page load that finds a blank spec, and every mode switch and filter Apply posts
538
+ * another. So a person opening the dock app and clicking one tab made the server report an agent
539
+ * session for the next MCP_IN_USE_MS, and "mcp" is the one claim nothing overrides — the launcher
540
+ * refuses to replace it and the quit path refuses to stop it. The app then left its own server running
541
+ * on quit, which is the exact leak the quit path exists to close, reachable by ordinary use.
542
+ *
543
+ * A tab's write is credited as presence instead, which is both true and stronger: it is the same thing
544
+ * the tab's own /health poll records. Only a write from something with no tab at all is a session.
545
+ */
546
+ export function creditAuthoredWrite(tab, now = Date.now()) {
547
+ if (tab !== undefined)
548
+ touchTab(tab, now);
549
+ else
550
+ markKeepAlive(now);
551
+ }
374
552
  /**
375
553
  * One sweep tick: prune stale tab ids, maintain the emptySince marker across the 1->0 / 0->1
376
554
  * transitions, and return whether the dashboard should auto-close now. Owns all timestamp
@@ -406,6 +584,7 @@ export function resetPresenceForTest() {
406
584
  presence.tabs.clear();
407
585
  presence.emptySince = null;
408
586
  presence.everSeen = false;
587
+ presence.keepAliveAt = null;
409
588
  }
410
589
  // Servers already tearing down. Keyed on the server rather than a module flag so the latch
411
590
  // scopes to the thing being closed: a second call for the SAME server is suppressed, while a
@@ -538,11 +717,14 @@ function pingDevice(timeoutMs = PING_PROBE_MS) {
538
717
  */
539
718
  export function armOnBoot() {
540
719
  // An agent-spawned dashboard must not reach the device on its own. open_radar_dashboard is exempt
541
- // from the MCP session gate precisely BECAUSE opening a dashboard could not arm anything without a
542
- // human pressing Reconnect, and arming here would quietly remove the premise that exemption rests
543
- // on: an agent call would arm a device and begin logcat capture to disk with no human action, and
544
- // its child is detached with stdio ignored so even a failure line would reach nobody. A human
545
- // launch, whether a terminal `slack-radar web` or the dock app, sets no marker and does arm.
720
+ // from the MCP session gate precisely BECAUSE opening a dashboard could not arm anything by itself,
721
+ // and arming here would quietly remove the premise that exemption rests on: an agent call would arm
722
+ // a device and begin logcat capture to disk with no human action, and its child is detached with
723
+ // stdio ignored so even a failure line would reach nobody. The client's automatic re-enable is
724
+ // gated on the same flag (surfaced as /health's self_arm_blocked, and enforced server-side by
725
+ // handleEnable's own ?auto=1 refusal), so neither the boot nor an open tab
726
+ // arms an agent-spawned dashboard. A human launch, whether a terminal `slack-radar web` or the dock
727
+ // app, sets no marker: it arms here, and its tab may recover a dead session unattended.
546
728
  if (process.env.SLACK_RADAR_AGENT_LAUNCH)
547
729
  return;
548
730
  // Escape hatch, matching this file's other automatic-on-boot behaviours (SLACK_RADAR_NO_OPEN,
@@ -630,7 +812,7 @@ async function armDevice() {
630
812
  // devices/emulators found"), and that is the deliberately quiet case. An attached but
631
813
  // unauthorized device also selects nothing, so the gate is the raw listing, which keeps
632
814
  // exactly that case loud.
633
- if (reason && selection.devices.length > 0) {
815
+ if (reason && (selection.devices?.length ?? 0) > 0) {
634
816
  console.log(`Radar could not be armed at startup: ${reason}`);
635
817
  }
636
818
  return;
@@ -703,6 +885,12 @@ export function createServer(onShutdown) {
703
885
  });
704
886
  return;
705
887
  }
888
+ // Contract §7 (docs/wire-contract.md): every response the Host gate accepts names the host
889
+ // version, so a machine consumer can detect skew (@latest auto-upgrade, stale npx cache, the
890
+ // adopt trap) from any request instead of depending on /spec. Deliberately AFTER the Host
891
+ // check: a DNS-rebound page reads response headers as same-origin, and before this feature
892
+ // the version was never visible past that gate — refusals it issues stay version-silent.
893
+ res.setHeader("X-Radar-Version", RADAR_VERSION);
706
894
  const url = req.url ?? "";
707
895
  const urlPath = url.split("?")[0];
708
896
  // Second chokepoint, DEFAULT DENY. A request must prove it came from our own client unless its
@@ -734,12 +922,54 @@ export function createServer(onShutdown) {
734
922
  if ((req.method === "GET" || req.method === "HEAD") && serveStatic(urlPath, res, req.method === "HEAD", Array.isArray(inm) ? inm[0] : inm)) {
735
923
  return;
736
924
  }
737
- if (url === "/spec" && req.method === "GET") {
738
- // Version marker for a second launcher's adopt path: it can compare this against its own
739
- // RADAR_VERSION and warn on a mismatch (it still adopts; it never kills the holder).
740
- // A header, not a body field, so the /spec fingerprint and the client's change-detection
741
- // key (JSON.stringify of the body) stay byte-identical.
742
- res.setHeader("X-Radar-Version", RADAR_VERSION);
925
+ if (url === "/spec" && (req.method === "GET" || req.method === "HEAD")) {
926
+ // The version marker a second launcher's adopt path compares against its own RADAR_VERSION is
927
+ // the X-Radar-Version HEADER, set for every response at the top of this handler. A header, not
928
+ // a body field, so the /spec fingerprint and the client's change-detection key
929
+ // (JSON.stringify of the body) stay byte-identical.
930
+ //
931
+ // HEAD is here because that header is the only way to ask a running dashboard what version it
932
+ // is, and `curl -sI` is what someone reaches for to do that. Without HEAD the request fell past
933
+ // every handler to the terminal 404, so the answer read as "no dashboard here" while a dashboard
934
+ // was serving the port.
935
+ //
936
+ // The in-use answer rides the SAME response, deliberately: the app already makes this one
937
+ // request, and a second round trip on the launch path would be latency the user waits through
938
+ // before any window appears. Answered here rather than on /health because /spec is the
939
+ // fingerprint every launcher already probes, and because a launcher asking this must not have to
940
+ // send the X-Radar-Dashboard header that /health's presence side door requires.
941
+ //
942
+ // Two headers rather than one richer value, and NOT because anything already reads the first
943
+ // one: both ship together here, so no installed dock app reads the bit without the reason.
944
+ // The split is for the next change. A reader that only needs "is anyone there" keeps a stable
945
+ // answer while the vocabulary of reasons grows, and the wire contract's rule is that a new
946
+ // field may appear at any time and an older reader must ignore it. Widening the 1/0 value
947
+ // instead would make every future reason a breaking change to the same field.
948
+ //
949
+ // X-Radar-Ignore-Tab is the asking app's own presence id, and the answer excludes it. Echoed back
950
+ // in X-Radar-In-Use-Excludes, which is the part that earns its keep: a server too old to know the
951
+ // request header answers "a tab is using it" about the asker's OWN window, and it answers that
952
+ // with exactly the same two headers a current server uses to mean somebody else. The echo is the
953
+ // only thing that tells those apart, so it is what lets the app protect a real second browser tab
954
+ // without refusing to ever replace a dashboard its own window is looking at.
955
+ //
956
+ // Not gated on X-Radar-Dashboard, unlike /health's presence side door. That gate exists because
957
+ // touchTab WRITES: a foreign page could keep a dashboard alive or fake a tab on one. This only
958
+ // narrows the answer this one response carries, changes no state, and cannot be aimed: excluding
959
+ // an id means guessing a uuid, and the result of guessing it is being told nobody is using a
960
+ // dashboard the guesser could already have asked about without the header.
961
+ //
962
+ // X-Radar-In-Use-For names which decision the answer will inform, because the two callers of this
963
+ // route are asking different questions and one answer cannot serve both. See InUseDecision.
964
+ const ignoreTab = readIgnoredTab(req.headers);
965
+ const use = inUseReason(Date.now(), ignoreTab, readInUseDecision(req.headers));
966
+ res.setHeader("X-Radar-In-Use", use === "no" ? "0" : "1");
967
+ if (use !== "no")
968
+ res.setHeader("X-Radar-In-Use-By", use);
969
+ if (ignoreTab !== undefined)
970
+ res.setHeader("X-Radar-In-Use-Excludes", ignoreTab);
971
+ // The framing a HEAD needs to mirror a GET (RFC 9110 9.3.2) is stated by sendJson for every
972
+ // JSON route, so this one is an ordinary send.
743
973
  sendJson(res, 200, loadSpec());
744
974
  return;
745
975
  }
@@ -785,9 +1015,12 @@ export function createServer(onShutdown) {
785
1015
  return;
786
1016
  }
787
1017
  if (urlPath === "/enable" && req.method === "POST") {
788
- const serial = new URL(url, `http://localhost:${WEB_PORT}`).searchParams.get("device_serial");
1018
+ const params = new URL(url, `http://localhost:${WEB_PORT}`).searchParams;
1019
+ const serial = params.get("device_serial");
789
1020
  // Deliberately not awaited; handleEnable answers res itself and never rejects.
790
- void handleEnable(res, serial, isAuthoredRequest(req.headers));
1021
+ // ?auto=1 marks the dashboard's own unattended recovery; see handleEnable's `auto`.
1022
+ const auto = params.get("auto") === "1";
1023
+ void handleEnable(res, serial, isAuthoredRequest(req.headers), readTabIdentity(req.headers), auto);
791
1024
  return;
792
1025
  }
793
1026
  if (url === "/stream" && req.method === "GET") {
@@ -968,8 +1201,20 @@ function sendJson(res, status, payload) {
968
1201
  // ERR_HTTP_HEADERS_SENT and crash the whole process. Swallow the duplicate.
969
1202
  if (res.headersSent || res.writableEnded)
970
1203
  return;
971
- res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
972
- res.end(JSON.stringify(payload));
1204
+ // No special case for HEAD. Node drops the body itself when the request method was HEAD, so the
1205
+ // same call answers both, and measuring it was the only way to know: a flag here that skipped the
1206
+ // body produced a byte-identical response, which is a parameter earning nothing.
1207
+ //
1208
+ // Content-Length is stated rather than left to chunked encoding, so a HEAD reports the same
1209
+ // framing a GET would. Node drops the body but keeps the header, which is the whole point: a
1210
+ // caller sizing a response can ask without fetching it. Every JSON route gets that for free here,
1211
+ // which is why it belongs in this helper rather than in one route that happened to need it.
1212
+ const body = JSON.stringify(payload);
1213
+ res.writeHead(status, {
1214
+ "Content-Type": "application/json; charset=utf-8",
1215
+ "Content-Length": Buffer.byteLength(body),
1216
+ });
1217
+ res.end(body);
973
1218
  }
974
1219
  function readBody(req) {
975
1220
  return new Promise((resolve) => {
@@ -1012,8 +1257,10 @@ async function handleSetSpec(req, res, authored) {
1012
1257
  // request, so without the gate any page in the user's browser could postpone auto-close
1013
1258
  // forever by pinging this every few minutes. The spec still gets written either way, which
1014
1259
  // keeps a bare curl working; it just does not buy the process more life.
1260
+ //
1261
+ // Credited to the writer rather than assumed to be a session: see creditAuthoredWrite.
1015
1262
  if (authored)
1016
- markKeepAlive();
1263
+ creditAuthoredWrite(readTabIdentity(req.headers));
1017
1264
  sendJson(res, 200, {
1018
1265
  ok: true,
1019
1266
  url: `http://localhost:${WEB_PORT}`,
@@ -1083,6 +1330,19 @@ async function handleHealth(res) {
1083
1330
  boundProfile: profile,
1084
1331
  device_serial: selected?.serial ?? null,
1085
1332
  device_label: selected?.label ?? null,
1333
+ // Whether THIS PROCESS is forbidden from touching the device on its own. Two reasons
1334
+ // today: an agent spawned it (open_radar_dashboard is exempt from the MCP session gate
1335
+ // precisely because opening a dashboard cannot itself reach the device, and an
1336
+ // agent-spawned tab that re-armed on its own would remove the premise that exemption
1337
+ // rests on), or SLACK_RADAR_NO_ARM, which suppresses the boot arm and is documented as
1338
+ // the opt-out that "most deserves" one because it is the first behaviour to touch
1339
+ // physical hardware. Automatic recovery is the second such behaviour, so it honours the
1340
+ // same flags: otherwise setting NO_ARM stopped the boot arm and a visible tab armed the
1341
+ // device ten seconds later anyway. The client's automatic re-enable reads this and
1342
+ // refuses to arm (handleEnable refuses an ?auto=1 server-side too). Sent as one derived
1343
+ // boolean so a future third reason to refuse has one place to join, and the client needs
1344
+ // no env knowledge.
1345
+ self_arm_blocked: !!process.env.SLACK_RADAR_AGENT_LAUNCH || !!process.env.SLACK_RADAR_NO_ARM,
1086
1346
  // Capture sources the build declares on ping (seam builds only); null on older builds.
1087
1347
  sources,
1088
1348
  });
@@ -1092,10 +1352,10 @@ async function handleHealth(res) {
1092
1352
  * successful re-arm keeps the dashboard alive (an MCP-driven session can re-enable with no tab
1093
1353
  * open, and that must not let the idle timer fire out from under it).
1094
1354
  *
1095
- * `onEnabled` fires only on a successful probe. The route passes `markKeepAlive` when the
1096
- * request was authored (see isAuthoredRequest) and OMITS it otherwise, so an unauthored caller
1097
- * gets the same body but buys no extra process life. Injected rather than called directly so
1098
- * the keep-alive wiring is testable without a real device probe (handleEnable's ping goes over
1355
+ * `onEnabled` fires only on a successful probe. The route passes a hook that credits the WRITER
1356
+ * (creditAuthoredWrite) when the request was authored (see isAuthoredRequest) and OMITS it otherwise, so
1357
+ * an unauthored caller gets the same body but buys no extra process life. Injected rather than called
1358
+ * directly so the keep-alive wiring is testable without a real device probe (handleEnable's ping goes over
1099
1359
  * a real socket to RADAR_HOST:RADAR_PORT, which this function does not touch at all).
1100
1360
  *
1101
1361
  * A failed probe gets guidance, not a bare false: the broadcast landed (or exited 0 with no
@@ -1108,9 +1368,12 @@ async function handleHealth(res) {
1108
1368
  * through the route cannot cover this — handleEnable's device probe fails with no hardware, which
1109
1369
  * short-circuits before the hook is ever consulted, so a route-level test passes either way (a
1110
1370
  * mutation deleting the gate survived the whole suite before this existed).
1371
+ *
1372
+ * `tab` is the writer, and it decides WHICH credit the hook applies: a re-arm pressed in the dashboard
1373
+ * is a window's, not an agent session's. See creditAuthoredWrite.
1111
1374
  */
1112
- export function keepAliveHookFor(authored) {
1113
- return authored ? markKeepAlive : undefined;
1375
+ export function keepAliveHookFor(authored, tab) {
1376
+ return authored ? () => creditAuthoredWrite(tab) : undefined;
1114
1377
  }
1115
1378
  // Reads the dashboard serves to any local caller. Everything NOT matching is treated as
1116
1379
  // state-changing and needs proof it came from our own client (see isOpenToAnyCaller).
@@ -1256,15 +1519,175 @@ processState = "unknown") {
1256
1519
  onEnabled?.();
1257
1520
  return { enabled };
1258
1521
  }
1259
- return { enabled, error: deviceServerSilentError(processState) };
1522
+ // `instructs` travels with every failed reply: whether the wording tells the user what to do
1523
+ // next, decided where the wording is written rather than guessed from its prose by the client
1524
+ // (some reasons pass adb's own stderr straight through, which no verb list can classify). Here
1525
+ // only the "stopped" wording gives an instruction (launch a debug build and retry).
1526
+ return { enabled, error: deviceServerSilentError(processState), instructs: processState === "stopped" };
1527
+ }
1528
+ // One /enable at a time, full stop. Every visible tab diagnoses the same dead session off one
1529
+ // shared memo (diagnoseStreamOutage), so each fires its own immediate ?auto=1 in the same window,
1530
+ // and two concurrent runEnable calls race on the shared transport: the second's resetState()
1531
+ // clears lastActivateError under the first's in-flight activateAsync, and the first then reports
1532
+ // the generic "did not respond" wording instead of the adb error this route exists to show (and
1533
+ // both spend a budget slot on it). A pick for another device mid-flight races the same way and
1534
+ // moves the pin under the first flight's forward, so different targets never overlap either;
1535
+ // they queue. Same shape as outageDiagnosisInflight for the join: a request identical to the
1536
+ // flight in progress receives the winner's reply rather than a refusal, since a refusal is
1537
+ // terminal for the joiner's automation and would spend its whole budget on an attempt that may
1538
+ // have succeeded.
1539
+ //
1540
+ // Joins are for the SAME target only (a pick for device B must not adopt A's answer), and a
1541
+ // human press never joins an unattended flight: the press earns things the timer may not (the
1542
+ // screen teardown, adopting swapped hardware), so it waits for the flight to settle and then
1543
+ // runs on its own. An unattended attempt arriving during a press does join it; the press's reply
1544
+ // is a superset of what the attempt could have earned. A joiner's own `authored` IS consulted, and so is
1545
+ // the tab it named: the flight's own hook credits only the writer that started it, and after a join those
1546
+ // are two different writers, so the joiner credits itself at the end of handleEnable. That mattered only
1547
+ // once the credit gained a writer; while it was one global keep-alive the winner's call did cover it.
1548
+ let enableInFlight = null;
1549
+ // Test seam: the next runEnable rejects with this error after `delayMs` (long enough for a second
1550
+ // request to join the flight), to prove a rejection still answers every request riding the flight
1551
+ // instead of leaving them (and the client's Reconnect button) hanging.
1552
+ let enableFaultForTest = null;
1553
+ export function _setEnableFaultForTest(err, delayMs = 300) {
1554
+ enableFaultForTest = err ? { err, delayMs } : null;
1555
+ }
1556
+ async function handleEnable(res, deviceSerial, authored,
1557
+ // The tab that made this request, when one named itself. Travels next to `authored` because the two
1558
+ // are read together: authored decides WHETHER the re-arm buys the process more life, this decides
1559
+ // whose claim that life is recorded under.
1560
+ tab,
1561
+ // An UNATTENDED re-arm (the dashboard's own automatic recovery of a diagnosed-dead session,
1562
+ // marked with ?auto=1). See runEnable for what it may and may not do.
1563
+ auto = false) {
1564
+ // `||`, not `??`: an empty ?device_serial= means "no serial" to selectDevice too, so the two
1565
+ // requests must share one slot key.
1566
+ const target = deviceSerial || null;
1567
+ // The server-side half of the self-arm consent boundary. The client refuses off /health's
1568
+ // self_arm_blocked, but that field only reaches it on the first /health reply, and the
1569
+ // no_session diagnosis can beat that reply on a fresh tab, so the promise that an
1570
+ // agent-spawned (or SLACK_RADAR_NO_ARM) process never arms on its own is enforced here, where
1571
+ // the ?auto=1 marker already arrives. Answered before any side effect and before any join: a
1572
+ // forbidden process must not even pin a device for an attempt it is refusing, and this
1573
+ // per-request refusal must never be replaced by the reply of a human press it overlaps.
1574
+ if (auto && (process.env.SLACK_RADAR_AGENT_LAUNCH || process.env.SLACK_RADAR_NO_ARM)) {
1575
+ sendJson(res, 200, {
1576
+ enabled: false,
1577
+ error: "This dashboard may not arm the device on its own. Press Reconnect to arm it.",
1578
+ instructs: true,
1579
+ // A machine-readable marker for a refusal no later automatic attempt can change: the client
1580
+ // reads it to stop retrying and tell the user the next press is theirs, instead of burning
1581
+ // its budget on attempts this route will refuse the same way every time.
1582
+ refusal: "self_arm_blocked",
1583
+ });
1584
+ return;
1585
+ }
1586
+ // The rules above are held as invariants, not checked once: after any wait the slot may hold a
1587
+ // NEW flight (another tab's attempt, a pick for another device), so re-evaluate until nothing
1588
+ // stands in the way. The loop hands out its decision: the flight this request may join, or
1589
+ // null for "run your own". Acting on that binding rather than re-reading the slot keeps the
1590
+ // rule in one place; a re-read would need the same predicate again and would rot the first
1591
+ // time an await lands between the two.
1592
+ let joinable = null;
1593
+ for (;;) {
1594
+ const flight = enableInFlight;
1595
+ if (!flight)
1596
+ break;
1597
+ if (flight.serial === target && (auto || !flight.auto)) {
1598
+ joinable = flight;
1599
+ break;
1600
+ }
1601
+ await flight.p.catch(() => undefined);
1602
+ }
1603
+ let p;
1604
+ if (joinable) {
1605
+ p = joinable.p;
1606
+ }
1607
+ else {
1608
+ // .finally with an identity check, so a flight that settles after a successor took the slot
1609
+ // never clears the successor.
1610
+ p = runEnable(target, authored, auto, tab).finally(() => {
1611
+ if (enableInFlight?.p === p)
1612
+ enableInFlight = null;
1613
+ });
1614
+ enableInFlight = { serial: target, auto, p };
1615
+ }
1616
+ let reply;
1617
+ try {
1618
+ reply = await p;
1619
+ }
1620
+ catch (e) {
1621
+ // Nothing in runEnable is meant to reject, but a rejection that escaped here left every
1622
+ // request on the flight unanswered: the client's fetch never resolved, `enabling` stayed
1623
+ // latched, the Reconnect button stayed disabled and the automation never ran again.
1624
+ reply = {
1625
+ status: 500,
1626
+ body: { enabled: false, error: `Enable failed: ${e.message}. Try again.`, instructs: true },
1627
+ };
1628
+ }
1629
+ // A JOINED request credits itself, because the flight's own hook only credits whoever started it and
1630
+ // after coalescing those are two different writers. The lossy direction is the one that matters: an
1631
+ // agent session joining a window's attempt would have its re-arm recorded as the window's, leave no
1632
+ // session claim on the port, and get taken by the next launcher. While the credit was writer-agnostic
1633
+ // this could not happen, so it arrives with the attribution and is fixed with it.
1634
+ if (joinable && authored && reply.body.enabled)
1635
+ creditAuthoredWrite(tab);
1636
+ sendJson(res, reply.status, reply.body);
1260
1637
  }
1261
1638
  /**
1262
- * Re-arm Radar from the dashboard. Mirrors the recovery sequence: reset cached
1639
+ * The /enable body: one attempt against the device, run by handleEnable at most once at a time
1640
+ * per target. Re-arm Radar from the dashboard. Mirrors the recovery sequence: reset cached
1263
1641
  * forward state, rebuild a clean adb forward, and re-broadcast activation, so the
1264
1642
  * user never has to drop to a terminal. Delegates entirely to AndroidTransport;
1265
1643
  * no adb shelling here.
1266
1644
  */
1267
- async function handleEnable(res, deviceSerial, authored) {
1645
+ async function runEnable(deviceSerial, authored,
1646
+ // An UNATTENDED re-arm (the dashboard's own automatic recovery of a diagnosed-dead session,
1647
+ // marked with ?auto=1). It never takes the destructive screen teardown below — that reap
1648
+ // kills a live cast and deletes saved recordings, so a human press or an MCP enable earns
1649
+ // it and a timer does not. Two refusals in this handler enforce that: an auto attempt from
1650
+ // a process whose env forbids self-arming is refused before any device work, and an auto
1651
+ // attempt onto DIFFERENT hardware than this process last armed is refused before the
1652
+ // teardown decision; the same-device auto path takes the detection-only reset.
1653
+ auto,
1654
+ // The tab that started this flight, when one named itself. Only reaches keepAliveHookFor below.
1655
+ tab) {
1656
+ if (enableFaultForTest) {
1657
+ const fault = enableFaultForTest;
1658
+ enableFaultForTest = null;
1659
+ await new Promise((r) => setTimeout(r, fault.delayMs));
1660
+ throw fault.err;
1661
+ }
1662
+ // The unattended path decides "different hardware?" BEFORE anything is touched. selectDevice
1663
+ // below pins as it answers, and the reset/select/DB-drop/logcat-restart that used to run ahead
1664
+ // of this check had already re-pointed the process at the new device by the time the refusal
1665
+ // went out, under wording that said nothing had moved. resolveDevice is the same pick with no
1666
+ // pin, so a refused attempt leaves the process exactly as it found it (the transport keeps
1667
+ // its old selection, the pulled-DB scratch and the retained logcat ring stay). A transport
1668
+ // without resolveDevice falls back to the post-pin check further down. The listing runs again
1669
+ // inside selectDevice below; that second listing is the price of a refusal that changes
1670
+ // nothing, so do not reuse this one to save it.
1671
+ if (auto && transport.resolveDevice) {
1672
+ const would = transport.resolveDevice(deviceSerial ?? null);
1673
+ const target = would.ok ? (would.serial ?? null) : null;
1674
+ if (target !== null && lastArmedSerial !== null && target !== lastArmedSerial) {
1675
+ return { status: 200, body: {
1676
+ enabled: false,
1677
+ // "A different device" rather than "the device changed": the pin has not moved, and the
1678
+ // header's device chip may already be naming the newcomer as the one attached.
1679
+ error: "A different device is attached. Press Reconnect to use it.",
1680
+ instructs: true,
1681
+ // Terminal for the automation (see the marker on the env refusal above): lastArmedSerial is
1682
+ // kept, so every later unattended attempt onto this device is refused identically.
1683
+ refusal: "device_changed",
1684
+ // The pin did not move to the new device: this is still the old one, or null once the
1685
+ // listing noticed the old one is gone (every listing reconciles a vanished pin). Never the
1686
+ // new serial, so the client's baseline cannot advance off a refusal that armed nothing.
1687
+ device_serial: transport.getSelectedDevice?.()?.serial ?? null,
1688
+ } };
1689
+ }
1690
+ }
1268
1691
  transport.resetState();
1269
1692
  // A reconnect may be a different device / re-armed profile, so drop the cached DB user
1270
1693
  // set + sqlite path; the next /dbs re-detects the profiles fresh.
@@ -1277,12 +1700,12 @@ async function handleEnable(res, deviceSerial, authored) {
1277
1700
  // here with the list, before forwarding OR the screen reset.
1278
1701
  const selection = transport.selectDevice?.(deviceSerial ?? null);
1279
1702
  if (selection && !selection.ok) {
1280
- sendJson(res, 409, {
1281
- enabled: false,
1282
- error: selection.error,
1283
- devices: selection.devices,
1284
- });
1285
- return;
1703
+ return { status: 409, body: {
1704
+ enabled: false,
1705
+ error: selection.error,
1706
+ instructs: selection.instructs,
1707
+ devices: selection.devices,
1708
+ } };
1286
1709
  }
1287
1710
  // The serial pinned at REPLY time, which under an overlapping /enable can differ from the pin
1288
1711
  // this press made -- and reply time is the correct read: the verify probe rode the forward as
@@ -1305,7 +1728,9 @@ async function handleEnable(res, deviceSerial, authored) {
1305
1728
  // The second is not the old per-process one-shot back: that spent a teardown on the first enable
1306
1729
  // even when boot had already reaped. reapScreenOnce fires only when boot did not, and without it
1307
1730
  // such a process never reaps for its whole lifetime, because the switch gate needs a prior armed
1308
- // serial and only an arm can set one.
1731
+ // serial and only an arm can set one. Neither is ever earned by an unattended attempt (see the
1732
+ // `auto` parameter): a switched auto attempt is refused outright below, and a same-device one
1733
+ // takes the detection-only reset.
1309
1734
  //
1310
1735
  // Live work IS in reach on that path, and iOS is where it matters. armDevice returns before the
1311
1736
  // reap unless the transport implements selectDeviceAsync, and only AndroidTransport does
@@ -1321,6 +1746,34 @@ async function handleEnable(res, deviceSerial, authored) {
1321
1746
  const pinned = selection && selection.ok ? (selection.serial ?? null) : null;
1322
1747
  // A null pin means "nothing attached", not "the hardware changed".
1323
1748
  const switched = pinned !== null && lastArmedSerial !== null && pinned !== lastArmedSerial;
1749
+ // An unattended attempt must not adopt DIFFERENT hardware than this process last armed: a
1750
+ // hardware swap is a human-scale event, and the swap teardown below (kill the live cast,
1751
+ // delete saved clips, pkill screenrecord device-wide) is exactly the destructive step a
1752
+ // timer never earns. Refusing — rather than arming without the teardown — also keeps
1753
+ // lastArmedSerial intact, so the press that follows still reads the swap and spends the
1754
+ // teardown it is owed; arming here and advancing the serial would hide the swap from that
1755
+ // press.
1756
+ if (switched && auto) {
1757
+ // The pin has already moved to the new hardware (selectDevice above), and the stream proxy
1758
+ // reasserts its forward onto the current pin on every connect, so from here the tab reads the
1759
+ // NEW device. The per-device state that belongs to the OLD one must not follow it: the
1760
+ // retained logcat ring would replay device A's lines into a stream now serving device B, and
1761
+ // the pulled-DB scratch is A's. Same two drops the switched path below performs; only the
1762
+ // screen teardown is withheld, and lastArmedSerial stays put so the press earns it.
1763
+ cleanupPulledDatabases();
1764
+ logSession?.restart();
1765
+ return { status: 200, body: {
1766
+ enabled: false,
1767
+ // Reachable only on a transport without resolveDevice (or a listing that changed between
1768
+ // the resolve above and this pick), so the pin HAS moved here; say so.
1769
+ error: "The attached device changed and the dashboard now points at it. Press Reconnect to arm it.",
1770
+ instructs: true,
1771
+ // Terminal for the automation (see the marker on the env refusal above): lastArmedSerial is
1772
+ // kept, so every later unattended attempt onto this device is refused identically.
1773
+ refusal: "device_changed",
1774
+ device_serial: pinnedSerial(),
1775
+ } };
1776
+ }
1324
1777
  if (switched) {
1325
1778
  // A real hardware change earns the teardown every time, not once per process, so this is the
1326
1779
  // one reap that does not go through reapScreenOnce. Setting the flag here still tells a later
@@ -1328,10 +1781,13 @@ async function handleEnable(res, deviceSerial, authored) {
1328
1781
  reapedThisProcess = true;
1329
1782
  dashboardScreen.reset();
1330
1783
  }
1331
- else if (!reapScreenOnce(pinned, false)) {
1332
- // No teardown was owed. false covers the empty-cable enable for the same reason the seed
1333
- // below needs a real pin: there is no device to reap on, so spending the one-shot there would
1334
- // leave a later real pin with nothing left to earn a teardown with.
1784
+ else if (auto || !reapScreenOnce(pinned, false)) {
1785
+ // No teardown was owed — or this is the unattended auto re-arm, which may never spend one
1786
+ // (see the `auto` parameter): the one-shot stays unspent for the next human press, which is
1787
+ // where the responsibility for killing a live cast and deleting clips belongs. false covers
1788
+ // the empty-cable enable for the same reason the seed below needs a real pin: there is no
1789
+ // device to reap on, so spending the one-shot there would leave a later real pin with
1790
+ // nothing left to earn a teardown with.
1335
1791
  dashboardScreen.resetDetection();
1336
1792
  }
1337
1793
  // Only remember a serial we actually ARMED. selectDevice returns { ok: true, serial: null } when
@@ -1365,12 +1821,13 @@ async function handleEnable(res, deviceSerial, authored) {
1365
1821
  const forwarded = forwardForRead();
1366
1822
  if (!forwarded) {
1367
1823
  const reason = transport.getLastForwardError?.() ?? null;
1368
- sendJson(res, 200, {
1369
- enabled: false,
1370
- error: reason ?? "ADB forward failed. Is a device connected?",
1371
- device_serial: pinnedSerial(),
1372
- });
1373
- return;
1824
+ return { status: 200, body: {
1825
+ enabled: false,
1826
+ error: reason ?? "ADB forward failed. Is a device connected?",
1827
+ // adb's own text, or a question: neither tells the user what to do.
1828
+ instructs: false,
1829
+ device_serial: pinnedSerial(),
1830
+ } };
1374
1831
  }
1375
1832
  // activateAsync() never throws; a failed broadcast is recorded on the transport.
1376
1833
  // Surfacing it here gives the dashboard user the actual adb error instead of a bare
@@ -1385,27 +1842,33 @@ async function handleEnable(res, deviceSerial, authored) {
1385
1842
  }
1386
1843
  const activateError = transport.getLastActivateError?.() ?? null;
1387
1844
  if (activateError) {
1388
- sendJson(res, 200, {
1389
- enabled: false,
1390
- error: `Broadcast failed: ${activateError}. Is the device connected?`,
1391
- device_serial: pinnedSerial(),
1392
- });
1393
- return;
1845
+ return { status: 200, body: {
1846
+ enabled: false,
1847
+ error: `Broadcast failed: ${activateError}. Is the device connected?`,
1848
+ instructs: false,
1849
+ device_serial: pinnedSerial(),
1850
+ } };
1394
1851
  }
1395
1852
  // Verify by pinging the device the same way /health does (the shared pingDevice, so the
1396
1853
  // ceiling and the three-state rules cannot drift from the other probe sites).
1397
1854
  const ping = await pingDevice();
1398
1855
  const enabled = ping.state === "armed" && ping.status === 200;
1856
+ // A verified arm refutes any cached "no_session" the same way a stream connect does (the
1857
+ // memo is evidence about a session this route just restored): without this, another stream
1858
+ // client's mid-retry memo read could announce the pre-arm diagnosis for up to its TTL and
1859
+ // drive that tab to fire a spurious /enable against the live session.
1860
+ if (enabled)
1861
+ invalidateOutageDiagnosis();
1399
1862
  // Probe the process state only on the failure path: a successful enable needs no diagnosis,
1400
1863
  // and the probe is a real adb round trip. Capped short, because by this point the failure is
1401
1864
  // already established and the user is watching a request that has stalled their SSE tabs; an
1402
1865
  // explanation must not cost more than the operation it explains. The MCP path keeps the
1403
1866
  // patient default, where seconds of ping retries have already elapsed and a real answer
1404
1867
  // beats a fast "unknown".
1405
- sendJson(res, 200, {
1406
- ...enableResultBody(enabled, keepAliveHookFor(authored), enabled ? "unknown" : readProcessState(transport, DIAGNOSTIC_PS_TIMEOUT_MS)),
1407
- device_serial: pinnedSerial(),
1408
- });
1868
+ return { status: 200, body: {
1869
+ ...enableResultBody(enabled, keepAliveHookFor(authored, tab), enabled ? "unknown" : readProcessState(transport, DIAGNOSTIC_PS_TIMEOUT_MS)),
1870
+ device_serial: pinnedSerial(),
1871
+ } };
1409
1872
  }
1410
1873
  // The device-buffered source kinds, in one table so a new source is one row here: the
1411
1874
  // device API route segment (clog and trace pluralize; the rest match the kind name) and
@@ -2116,12 +2579,138 @@ export function parseLogcat(line, resolvePkg = packageForPid) {
2116
2579
  package: resolvePkg(pidN),
2117
2580
  };
2118
2581
  }
2582
+ // How long a freshly opened device stream may go without response HEADERS before the attempt is
2583
+ // declared dead. A healthy device answers /api/stream immediately; the pathological case this
2584
+ // bounds is a dead device-side socket behind a LIVE adb forward, where the host adb server
2585
+ // accepts the TCP connection unconditionally and then nothing ever answers — no error event, no
2586
+ // end event, just silence (observed live 2026-09-03: a stream that emitted no _status frame at
2587
+ // all). Generous enough to sit above pingDevice's observed 2.2s worst case.
2588
+ const STREAM_RESPONSE_TIMEOUT_MS = 6000;
2589
+ // Test seam: the real deadline is deliberately generous, which would make every hang-mode test
2590
+ // wait it out in real time. Never read anywhere else.
2591
+ let streamResponseTimeoutMs = STREAM_RESPONSE_TIMEOUT_MS;
2592
+ export function _setStreamResponseTimeoutForTest(ms) {
2593
+ streamResponseTimeoutMs = ms ?? STREAM_RESPONSE_TIMEOUT_MS;
2594
+ }
2595
+ // Why the device stream keeps dying, answered from the device's own socket table — the one read
2596
+ // the adb forward cannot distort (see pingDevice's classification rules: through a forward, an
2597
+ // absent socket and a live-but-hiccuping session both present as resets). ABSENT means no radar
2598
+ // server is bound anywhere on the device: the session ENDED (idle watchdog, app restart), and
2599
+ // only a re-enable brings it back — which the retry loop deliberately never performs (enabling
2600
+ // binds an identity and mutates device state; a read loop must not, and a wire-contract machine
2601
+ // consumer holding /stream must never arm a device by holding it). The dashboard CLIENT acts on
2602
+ // this instead: its auto-re-arm is the human's own tab pressing its own Reconnect.
2603
+ //
2604
+ // One probe at a time, memoized briefly: every open stream connection retries on its own clock,
2605
+ // so several tabs against a dead session would otherwise each run their own adb read (a call
2606
+ // with a 5s ceiling) every few seconds.
2607
+ const OUTAGE_DIAGNOSIS_TTL_MS = 8000;
2608
+ let outageDiagnosisTtlMs = OUTAGE_DIAGNOSIS_TTL_MS;
2609
+ // Test seam for the memo TTL: the collapse-slot invariants below are only observable once the
2610
+ // memo has expired, and 8 seconds of wall clock per assertion is the flake this seam avoids.
2611
+ export function _setOutageDiagnosisTtlForTest(ms) {
2612
+ outageDiagnosisTtlMs = ms ?? OUTAGE_DIAGNOSIS_TTL_MS;
2613
+ }
2614
+ let lastOutageDiagnosis = null;
2615
+ let outageDiagnosisInflight = null;
2616
+ // Bumped wherever a live connect invalidates the diagnosis. A probe is an adb round trip
2617
+ // with a 5s ceiling racing a 1-2s reconnect cadence, so probe-resolves-after-recovery is the
2618
+ // COMMON ordering: without the generation check, that late resolution would re-poison the
2619
+ // just-cleared memo with a fresh timestamp, and any other stream (a second tab) or a quick
2620
+ // re-drop of this one would inherit "no_session" for the full TTL and re-arm against the
2621
+ // live session.
2622
+ let outageDiagnosisGeneration = 0;
2623
+ // Test seam: the real probe reaches a physical device over adb, which a test host may or may
2624
+ // not have, so tests pin the answer instead of inheriting whatever hardware is attached.
2625
+ let outageProbe = () => transport.radarSocketPresentAsync?.() ?? Promise.resolve("unknown");
2626
+ export function _setOutageProbeForTest(probe) {
2627
+ outageProbe = probe ?? (() => transport.radarSocketPresentAsync?.() ?? Promise.resolve("unknown"));
2628
+ lastOutageDiagnosis = null;
2629
+ outageDiagnosisInflight = null;
2630
+ outageDiagnosisGeneration++;
2631
+ // This is the "restore the diagnosis machinery" seam, so the TTL goes back with the rest: a
2632
+ // test that shortened it and forgot its own restore must not leak a 50ms memo into the next.
2633
+ outageDiagnosisTtlMs = OUTAGE_DIAGNOSIS_TTL_MS;
2634
+ }
2635
+ // Test seams for the diagnosis cache itself. The generation rule is a pure invariant about
2636
+ // ordering (a probe that resolves after an invalidation must not cache), and driving it
2637
+ // through the real stream would mean racing an adb-shaped probe against a live reconnect
2638
+ // cadence on the wall clock — the flake this pair exists to avoid.
2639
+ export function _diagnoseOutageForTest() {
2640
+ return diagnoseStreamOutage();
2641
+ }
2642
+ export function _invalidateOutageDiagnosisForTest() {
2643
+ invalidateOutageDiagnosis();
2644
+ }
2645
+ // A live connect refutes any "no_session" — cached, in flight, or both. Exported to the
2646
+ // connect callback only through this helper so the memo and the pending write cannot be
2647
+ // invalidated separately (clearing just the memo was cycle-2's reopened race).
2648
+ function invalidateOutageDiagnosis() {
2649
+ lastOutageDiagnosis = null;
2650
+ // Drop the in-flight slot too: its eventual result is pre-invalidation evidence, and a
2651
+ // post-recovery consult must start a FRESH probe rather than await (or worse, adopt) the
2652
+ // orphan. The orphan's own cleanup is identity-checked, so it cannot null a successor.
2653
+ outageDiagnosisInflight = null;
2654
+ outageDiagnosisGeneration++;
2655
+ }
2656
+ async function diagnoseStreamOutage() {
2657
+ const now = Date.now();
2658
+ if (lastOutageDiagnosis && now - lastOutageDiagnosis.ts < outageDiagnosisTtlMs) {
2659
+ return lastOutageDiagnosis.reason;
2660
+ }
2661
+ if (outageDiagnosisInflight)
2662
+ return outageDiagnosisInflight;
2663
+ const generation = outageDiagnosisGeneration;
2664
+ // A holder rather than a bare binding: the async body needs its own promise's identity for
2665
+ // the slot-release check below, and it can run synchronously up to its first await —
2666
+ // before any direct `const probe = …` binding would initialize.
2667
+ const holder = { p: null };
2668
+ holder.p = (async () => {
2669
+ let reason = null;
2670
+ try {
2671
+ // The probe is CALLED synchronously (concurrent consults rely on it starting inside this
2672
+ // tick), but a synchronous throw is turned into a rejection so the body still suspends at
2673
+ // the await. Without that, a sync throw would let this whole body finish BEFORE the caller
2674
+ // stores holder.p into the collapse slot; the slot would then hold an already-settled
2675
+ // promise that the identity-checked release below never clears, wedging every later
2676
+ // consult on a stale null until the next live connect.
2677
+ let probe;
2678
+ try {
2679
+ probe = Promise.resolve(outageProbe());
2680
+ }
2681
+ catch (e) {
2682
+ probe = Promise.reject(e);
2683
+ }
2684
+ reason = (await probe) === "absent" ? "no_session" : null;
2685
+ }
2686
+ catch {
2687
+ // An unreadable socket table is "unknown", and unknown never classifies an outage.
2688
+ }
2689
+ // Release the collapse slot only if it is still OURS: a probe orphaned by an
2690
+ // invalidation (a live connect, the test seam) must not null a successor's in-flight
2691
+ // promise and briefly break the one-probe-at-a-time collapse.
2692
+ if (outageDiagnosisInflight === holder.p)
2693
+ outageDiagnosisInflight = null;
2694
+ // A stale probe reports nothing and caches nothing: evidence gathered before the
2695
+ // invalidation describes an outage that already ended.
2696
+ if (generation !== outageDiagnosisGeneration)
2697
+ return null;
2698
+ lastOutageDiagnosis = { ts: Date.now(), reason };
2699
+ return reason;
2700
+ })();
2701
+ outageDiagnosisInflight = holder.p;
2702
+ return holder.p;
2703
+ }
2119
2704
  /**
2120
2705
  * Self-healing SSE proxy. Keeps ONE long-lived response open to the browser and
2121
2706
  * internally (re)connects to the device `/api/stream` every couple seconds while
2122
2707
  * it is down, so the browser's EventSource never sees a close and never gives up.
2123
2708
  * Every other retry it rebuilds the adb forward (the real cause of recurring
2124
2709
  * "unreachable"), reusing AndroidTransport rather than shelling adb directly.
2710
+ * When retries keep failing it additionally asks WHY (see diagnoseStreamOutage)
2711
+ * and stamps the answer as `reason` on the `_status` frame, so a client can tell
2712
+ * "transport blip, the proxy will heal this" from "no radar session exists and
2713
+ * someone has to re-enable".
2125
2714
  *
2126
2715
  * When the active spec wants logs (source "log" or "all"), the handler subscribes
2127
2716
  * to the shared session-long logSession: it is first replayed the entire retained
@@ -2140,11 +2729,26 @@ function handleStream(req, res) {
2140
2729
  let upstream = null;
2141
2730
  let closed = false;
2142
2731
  let lastState = "";
2143
- const announce = (state, msg) => {
2144
- if (state === lastState)
2732
+ let lastReason = "";
2733
+ let headersDeadline = null;
2734
+ const announce = (state, msg, reason) => {
2735
+ // Dedup on state AND reason, with one asymmetry: a diagnosed outage keeps its diagnosis.
2736
+ // The retry loop re-announces generic "waiting" wording on every failed attempt, and once
2737
+ // this outage has been classified (reason set), that generic repeat is the SAME outage
2738
+ // described worse — letting it through would strip the reason the client is acting on
2739
+ // (see the dashboard's auto-re-arm) a second or two after it arrived. A reason CHANGE does
2740
+ // pass: the re-diagnosis retires a stale no_session with reason "undiagnosed" (a frame the
2741
+ // client reads as "drop the latch", not as a diagnosis of its own).
2742
+ if (state === lastState && !reason && lastReason)
2743
+ return;
2744
+ if (state === lastState && (reason ?? "") === lastReason)
2145
2745
  return;
2146
2746
  lastState = state;
2147
- res.write(`data: ${JSON.stringify({ type: "_status", event: { state, msg } })}\n\n`);
2747
+ lastReason = reason ?? "";
2748
+ const event = { state, msg };
2749
+ if (reason)
2750
+ event.reason = reason;
2751
+ res.write(`data: ${JSON.stringify({ type: "_status", event })}\n\n`);
2148
2752
  };
2149
2753
  // Keep the persistent logcat capture armed for the life of this connection.
2150
2754
  // start() is idempotent, so it is safe to call both on initial setup and from
@@ -2178,6 +2782,41 @@ function handleStream(req, res) {
2178
2782
  return;
2179
2783
  settled = true;
2180
2784
  retries++;
2785
+ // A failure that keeps repeating deserves a WHY. The second attempt (the first repeat —
2786
+ // one failure is routine) and a coarse cadence after that, so a fresh classification can
2787
+ // still ARRIVE mid-outage without running an adb probe on every 2s retry. announce never
2788
+ // downgrades a reasoned waiting to a generic one on its own (see its dedup asymmetry), but
2789
+ // a later probe that no longer finds the session absent (the socket is present, or the
2790
+ // table cannot be read because the device is gone) RETIRES a diagnosis this outage
2791
+ // announced: the outage changed nature under the latched reason, and without this the
2792
+ // client's headline kept asserting "no radar session" over a reason span saying the device
2793
+ // is unreachable, while its automation spent attempts on hardware that was not there.
2794
+ // Fire-and-forget: the probe must never delay the reconnect cadence it is describing.
2795
+ if (retries === 2 || retries % 6 === 0) {
2796
+ // A probe orphaned by an invalidation (this tab's own arm landing, an MCP activate, a live
2797
+ // connect) reports null exactly like a fresh "not absent" answer would. The generation tells
2798
+ // them apart: a stale null must not retire a diagnosis against a session that just armed.
2799
+ const generation = outageDiagnosisGeneration;
2800
+ void diagnoseStreamOutage().then((reason) => {
2801
+ // The connected check closes a REPRODUCED race: the probe is an adb round trip (5s
2802
+ // ceiling) racing a 1-2s reconnect cadence, so a session restored during its flight
2803
+ // (an auto-re-arm landing, an MCP activate, a manual press) can reconnect this stream
2804
+ // before the probe resolves — and announcing the stale diagnosis then would drive the
2805
+ // client to fire /enable AGAINST THE LIVE SESSION it just got back, the exact clobber
2806
+ // the socket-table diagnosis exists to prevent.
2807
+ if (closed || lastState === "connected" || generation !== outageDiagnosisGeneration)
2808
+ return;
2809
+ if (reason === null) {
2810
+ // "Not absent" covers both a socket that is present and a table that could not be read
2811
+ // (device gone, adb busy), so the wording asserts no cause; the generic per-retry
2812
+ // message is what the loop would say anyway.
2813
+ if (lastReason === "no_session")
2814
+ announce("waiting", "device not answering, retrying…", "undiagnosed");
2815
+ return;
2816
+ }
2817
+ announce("waiting", "no radar session on the device", reason);
2818
+ });
2819
+ }
2181
2820
  // planReconnect (shared/stream.ts) owns the cadence: every other retry it
2182
2821
  // rebuilds a clean forward before reconnecting and returns the delay. One
2183
2822
  // implementation for this proxy and the MCP stream, so a tuning change
@@ -2193,12 +2832,44 @@ function handleStream(req, res) {
2193
2832
  // (tuned for "device end died"), which would only catch a foreign repoint by luck on
2194
2833
  // half of attempts; this cheap check-first call covers every attempt instead.
2195
2834
  forwardForRead();
2835
+ // Bound the wait for response headers: see STREAM_RESPONSE_TIMEOUT_MS. Without this, the
2836
+ // accepted-but-never-answered connect mode fires none of the callbacks below and the
2837
+ // stream sits silent forever — no _status, no retry, nothing for a client to act on.
2838
+ // Per-ATTEMPT const, mirrored into the connection-scoped slot only for the close
2839
+ // teardown: each attempt's handlers clear their OWN deadline, so a stale attempt's late
2840
+ // error event can never clear the live attempt's timer out from under it.
2841
+ const myDeadline = setTimeout(() => {
2842
+ if (closed)
2843
+ return;
2844
+ announce("waiting", "device not answering, retrying…");
2845
+ try {
2846
+ upstream?.destroy();
2847
+ }
2848
+ catch {
2849
+ // already torn down
2850
+ }
2851
+ retry();
2852
+ }, streamResponseTimeoutMs);
2853
+ headersDeadline = myDeadline;
2196
2854
  upstream = http.request({
2197
2855
  host: RADAR_HOST,
2198
2856
  port: RADAR_PORT,
2199
2857
  path: "/api/stream",
2200
2858
  method: "GET",
2201
2859
  }, (up) => {
2860
+ clearTimeout(myDeadline);
2861
+ if (headersDeadline === myDeadline)
2862
+ headersDeadline = null;
2863
+ // A fresh outage on a long-lived connection must diagnose as early as the first one:
2864
+ // the "second failure" trigger and planReconnect's every-other-attempt forward
2865
+ // rebuild both key off this counter, and neither should inherit the count from an
2866
+ // outage that already recovered.
2867
+ retries = 0;
2868
+ // A live connect refutes any "no_session" — the cached memo AND a probe still in
2869
+ // flight (see invalidateOutageDiagnosis): without this, other stream clients would
2870
+ // re-read the pre-recovery diagnosis for up to its TTL and re-arm against the
2871
+ // healthy session.
2872
+ invalidateOutageDiagnosis();
2202
2873
  announce("connected", "device stream connected");
2203
2874
  // Re-arm logs on the same path the device proxy heals on: if the device
2204
2875
  // dropped and came back, `adb logcat` had exited; restart it (idempotent)
@@ -2215,6 +2886,9 @@ function handleStream(req, res) {
2215
2886
  });
2216
2887
  });
2217
2888
  upstream.on("error", () => {
2889
+ clearTimeout(myDeadline);
2890
+ if (headersDeadline === myDeadline)
2891
+ headersDeadline = null;
2218
2892
  announce("waiting", "device unreachable, retrying…");
2219
2893
  retry();
2220
2894
  });
@@ -2271,6 +2945,8 @@ function handleStream(req, res) {
2271
2945
  req.on("close", () => {
2272
2946
  closed = true;
2273
2947
  clearInterval(heartbeat);
2948
+ if (headersDeadline)
2949
+ clearTimeout(headersDeadline);
2274
2950
  if (unsubscribeLogs)
2275
2951
  unsubscribeLogs(); // detach listener; capture stays up
2276
2952
  try {