@slack/radar-mcp 1.18.1 → 1.19.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.
@@ -538,11 +538,14 @@ function pingDevice(timeoutMs = PING_PROBE_MS) {
538
538
  */
539
539
  export function armOnBoot() {
540
540
  // 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.
541
+ // from the MCP session gate precisely BECAUSE opening a dashboard could not arm anything by itself,
542
+ // and arming here would quietly remove the premise that exemption rests on: an agent call would arm
543
+ // a device and begin logcat capture to disk with no human action, and its child is detached with
544
+ // stdio ignored so even a failure line would reach nobody. The client's automatic re-enable is
545
+ // gated on the same flag (surfaced as /health's self_arm_blocked, and enforced server-side by
546
+ // handleEnable's own ?auto=1 refusal), so neither the boot nor an open tab
547
+ // arms an agent-spawned dashboard. A human launch, whether a terminal `slack-radar web` or the dock
548
+ // app, sets no marker: it arms here, and its tab may recover a dead session unattended.
546
549
  if (process.env.SLACK_RADAR_AGENT_LAUNCH)
547
550
  return;
548
551
  // Escape hatch, matching this file's other automatic-on-boot behaviours (SLACK_RADAR_NO_OPEN,
@@ -630,7 +633,7 @@ async function armDevice() {
630
633
  // devices/emulators found"), and that is the deliberately quiet case. An attached but
631
634
  // unauthorized device also selects nothing, so the gate is the raw listing, which keeps
632
635
  // exactly that case loud.
633
- if (reason && selection.devices.length > 0) {
636
+ if (reason && (selection.devices?.length ?? 0) > 0) {
634
637
  console.log(`Radar could not be armed at startup: ${reason}`);
635
638
  }
636
639
  return;
@@ -785,9 +788,12 @@ export function createServer(onShutdown) {
785
788
  return;
786
789
  }
787
790
  if (urlPath === "/enable" && req.method === "POST") {
788
- const serial = new URL(url, `http://localhost:${WEB_PORT}`).searchParams.get("device_serial");
791
+ const params = new URL(url, `http://localhost:${WEB_PORT}`).searchParams;
792
+ const serial = params.get("device_serial");
789
793
  // Deliberately not awaited; handleEnable answers res itself and never rejects.
790
- void handleEnable(res, serial, isAuthoredRequest(req.headers));
794
+ // ?auto=1 marks the dashboard's own unattended recovery; see handleEnable's `auto`.
795
+ const auto = params.get("auto") === "1";
796
+ void handleEnable(res, serial, isAuthoredRequest(req.headers), auto);
791
797
  return;
792
798
  }
793
799
  if (url === "/stream" && req.method === "GET") {
@@ -1083,6 +1089,19 @@ async function handleHealth(res) {
1083
1089
  boundProfile: profile,
1084
1090
  device_serial: selected?.serial ?? null,
1085
1091
  device_label: selected?.label ?? null,
1092
+ // Whether THIS PROCESS is forbidden from touching the device on its own. Two reasons
1093
+ // today: an agent spawned it (open_radar_dashboard is exempt from the MCP session gate
1094
+ // precisely because opening a dashboard cannot itself reach the device, and an
1095
+ // agent-spawned tab that re-armed on its own would remove the premise that exemption
1096
+ // rests on), or SLACK_RADAR_NO_ARM, which suppresses the boot arm and is documented as
1097
+ // the opt-out that "most deserves" one because it is the first behaviour to touch
1098
+ // physical hardware. Automatic recovery is the second such behaviour, so it honours the
1099
+ // same flags: otherwise setting NO_ARM stopped the boot arm and a visible tab armed the
1100
+ // device ten seconds later anyway. The client's automatic re-enable reads this and
1101
+ // refuses to arm (handleEnable refuses an ?auto=1 server-side too). Sent as one derived
1102
+ // boolean so a future third reason to refuse has one place to join, and the client needs
1103
+ // no env knowledge.
1104
+ self_arm_blocked: !!process.env.SLACK_RADAR_AGENT_LAUNCH || !!process.env.SLACK_RADAR_NO_ARM,
1086
1105
  // Capture sources the build declares on ping (seam builds only); null on older builds.
1087
1106
  sources,
1088
1107
  });
@@ -1256,15 +1275,161 @@ processState = "unknown") {
1256
1275
  onEnabled?.();
1257
1276
  return { enabled };
1258
1277
  }
1259
- return { enabled, error: deviceServerSilentError(processState) };
1278
+ // `instructs` travels with every failed reply: whether the wording tells the user what to do
1279
+ // next, decided where the wording is written rather than guessed from its prose by the client
1280
+ // (some reasons pass adb's own stderr straight through, which no verb list can classify). Here
1281
+ // only the "stopped" wording gives an instruction (launch a debug build and retry).
1282
+ return { enabled, error: deviceServerSilentError(processState), instructs: processState === "stopped" };
1283
+ }
1284
+ // One /enable at a time, full stop. Every visible tab diagnoses the same dead session off one
1285
+ // shared memo (diagnoseStreamOutage), so each fires its own immediate ?auto=1 in the same window,
1286
+ // and two concurrent runEnable calls race on the shared transport: the second's resetState()
1287
+ // clears lastActivateError under the first's in-flight activateAsync, and the first then reports
1288
+ // the generic "did not respond" wording instead of the adb error this route exists to show (and
1289
+ // both spend a budget slot on it). A pick for another device mid-flight races the same way and
1290
+ // moves the pin under the first flight's forward, so different targets never overlap either;
1291
+ // they queue. Same shape as outageDiagnosisInflight for the join: a request identical to the
1292
+ // flight in progress receives the winner's reply rather than a refusal, since a refusal is
1293
+ // terminal for the joiner's automation and would spend its whole budget on an attempt that may
1294
+ // have succeeded.
1295
+ //
1296
+ // Joins are for the SAME target only (a pick for device B must not adopt A's answer), and a
1297
+ // human press never joins an unattended flight: the press earns things the timer may not (the
1298
+ // screen teardown, adopting swapped hardware), so it waits for the flight to settle and then
1299
+ // runs on its own. An unattended attempt arriving during a press does join it; the press's reply
1300
+ // is a superset of what the attempt could have earned. A joiner's own `authored` is never
1301
+ // consulted: its only effect would be markKeepAlive, which is global and idempotent, so the
1302
+ // winner's call covers it.
1303
+ let enableInFlight = null;
1304
+ // Test seam: the next runEnable rejects with this error after `delayMs` (long enough for a second
1305
+ // request to join the flight), to prove a rejection still answers every request riding the flight
1306
+ // instead of leaving them (and the client's Reconnect button) hanging.
1307
+ let enableFaultForTest = null;
1308
+ export function _setEnableFaultForTest(err, delayMs = 300) {
1309
+ enableFaultForTest = err ? { err, delayMs } : null;
1310
+ }
1311
+ async function handleEnable(res, deviceSerial, authored,
1312
+ // An UNATTENDED re-arm (the dashboard's own automatic recovery of a diagnosed-dead session,
1313
+ // marked with ?auto=1). See runEnable for what it may and may not do.
1314
+ auto = false) {
1315
+ // `||`, not `??`: an empty ?device_serial= means "no serial" to selectDevice too, so the two
1316
+ // requests must share one slot key.
1317
+ const target = deviceSerial || null;
1318
+ // The server-side half of the self-arm consent boundary. The client refuses off /health's
1319
+ // self_arm_blocked, but that field only reaches it on the first /health reply, and the
1320
+ // no_session diagnosis can beat that reply on a fresh tab, so the promise that an
1321
+ // agent-spawned (or SLACK_RADAR_NO_ARM) process never arms on its own is enforced here, where
1322
+ // the ?auto=1 marker already arrives. Answered before any side effect and before any join: a
1323
+ // forbidden process must not even pin a device for an attempt it is refusing, and this
1324
+ // per-request refusal must never be replaced by the reply of a human press it overlaps.
1325
+ if (auto && (process.env.SLACK_RADAR_AGENT_LAUNCH || process.env.SLACK_RADAR_NO_ARM)) {
1326
+ sendJson(res, 200, {
1327
+ enabled: false,
1328
+ error: "This dashboard may not arm the device on its own. Press Reconnect to arm it.",
1329
+ instructs: true,
1330
+ // A machine-readable marker for a refusal no later automatic attempt can change: the client
1331
+ // reads it to stop retrying and tell the user the next press is theirs, instead of burning
1332
+ // its budget on attempts this route will refuse the same way every time.
1333
+ refusal: "self_arm_blocked",
1334
+ });
1335
+ return;
1336
+ }
1337
+ // The rules above are held as invariants, not checked once: after any wait the slot may hold a
1338
+ // NEW flight (another tab's attempt, a pick for another device), so re-evaluate until nothing
1339
+ // stands in the way. The loop hands out its decision: the flight this request may join, or
1340
+ // null for "run your own". Acting on that binding rather than re-reading the slot keeps the
1341
+ // rule in one place; a re-read would need the same predicate again and would rot the first
1342
+ // time an await lands between the two.
1343
+ let joinable = null;
1344
+ for (;;) {
1345
+ const flight = enableInFlight;
1346
+ if (!flight)
1347
+ break;
1348
+ if (flight.serial === target && (auto || !flight.auto)) {
1349
+ joinable = flight;
1350
+ break;
1351
+ }
1352
+ await flight.p.catch(() => undefined);
1353
+ }
1354
+ let p;
1355
+ if (joinable) {
1356
+ p = joinable.p;
1357
+ }
1358
+ else {
1359
+ // .finally with an identity check, so a flight that settles after a successor took the slot
1360
+ // never clears the successor.
1361
+ p = runEnable(target, authored, auto).finally(() => {
1362
+ if (enableInFlight?.p === p)
1363
+ enableInFlight = null;
1364
+ });
1365
+ enableInFlight = { serial: target, auto, p };
1366
+ }
1367
+ let reply;
1368
+ try {
1369
+ reply = await p;
1370
+ }
1371
+ catch (e) {
1372
+ // Nothing in runEnable is meant to reject, but a rejection that escaped here left every
1373
+ // request on the flight unanswered: the client's fetch never resolved, `enabling` stayed
1374
+ // latched, the Reconnect button stayed disabled and the automation never ran again.
1375
+ reply = {
1376
+ status: 500,
1377
+ body: { enabled: false, error: `Enable failed: ${e.message}. Try again.`, instructs: true },
1378
+ };
1379
+ }
1380
+ sendJson(res, reply.status, reply.body);
1260
1381
  }
1261
1382
  /**
1262
- * Re-arm Radar from the dashboard. Mirrors the recovery sequence: reset cached
1383
+ * The /enable body: one attempt against the device, run by handleEnable at most once at a time
1384
+ * per target. Re-arm Radar from the dashboard. Mirrors the recovery sequence: reset cached
1263
1385
  * forward state, rebuild a clean adb forward, and re-broadcast activation, so the
1264
1386
  * user never has to drop to a terminal. Delegates entirely to AndroidTransport;
1265
1387
  * no adb shelling here.
1266
1388
  */
1267
- async function handleEnable(res, deviceSerial, authored) {
1389
+ async function runEnable(deviceSerial, authored,
1390
+ // An UNATTENDED re-arm (the dashboard's own automatic recovery of a diagnosed-dead session,
1391
+ // marked with ?auto=1). It never takes the destructive screen teardown below — that reap
1392
+ // kills a live cast and deletes saved recordings, so a human press or an MCP enable earns
1393
+ // it and a timer does not. Two refusals in this handler enforce that: an auto attempt from
1394
+ // a process whose env forbids self-arming is refused before any device work, and an auto
1395
+ // attempt onto DIFFERENT hardware than this process last armed is refused before the
1396
+ // teardown decision; the same-device auto path takes the detection-only reset.
1397
+ auto) {
1398
+ if (enableFaultForTest) {
1399
+ const fault = enableFaultForTest;
1400
+ enableFaultForTest = null;
1401
+ await new Promise((r) => setTimeout(r, fault.delayMs));
1402
+ throw fault.err;
1403
+ }
1404
+ // The unattended path decides "different hardware?" BEFORE anything is touched. selectDevice
1405
+ // below pins as it answers, and the reset/select/DB-drop/logcat-restart that used to run ahead
1406
+ // of this check had already re-pointed the process at the new device by the time the refusal
1407
+ // went out, under wording that said nothing had moved. resolveDevice is the same pick with no
1408
+ // pin, so a refused attempt leaves the process exactly as it found it (the transport keeps
1409
+ // its old selection, the pulled-DB scratch and the retained logcat ring stay). A transport
1410
+ // without resolveDevice falls back to the post-pin check further down. The listing runs again
1411
+ // inside selectDevice below; that second listing is the price of a refusal that changes
1412
+ // nothing, so do not reuse this one to save it.
1413
+ if (auto && transport.resolveDevice) {
1414
+ const would = transport.resolveDevice(deviceSerial ?? null);
1415
+ const target = would.ok ? (would.serial ?? null) : null;
1416
+ if (target !== null && lastArmedSerial !== null && target !== lastArmedSerial) {
1417
+ return { status: 200, body: {
1418
+ enabled: false,
1419
+ // "A different device" rather than "the device changed": the pin has not moved, and the
1420
+ // header's device chip may already be naming the newcomer as the one attached.
1421
+ error: "A different device is attached. Press Reconnect to use it.",
1422
+ instructs: true,
1423
+ // Terminal for the automation (see the marker on the env refusal above): lastArmedSerial is
1424
+ // kept, so every later unattended attempt onto this device is refused identically.
1425
+ refusal: "device_changed",
1426
+ // The pin did not move to the new device: this is still the old one, or null once the
1427
+ // listing noticed the old one is gone (every listing reconciles a vanished pin). Never the
1428
+ // new serial, so the client's baseline cannot advance off a refusal that armed nothing.
1429
+ device_serial: transport.getSelectedDevice?.()?.serial ?? null,
1430
+ } };
1431
+ }
1432
+ }
1268
1433
  transport.resetState();
1269
1434
  // A reconnect may be a different device / re-armed profile, so drop the cached DB user
1270
1435
  // set + sqlite path; the next /dbs re-detects the profiles fresh.
@@ -1277,12 +1442,12 @@ async function handleEnable(res, deviceSerial, authored) {
1277
1442
  // here with the list, before forwarding OR the screen reset.
1278
1443
  const selection = transport.selectDevice?.(deviceSerial ?? null);
1279
1444
  if (selection && !selection.ok) {
1280
- sendJson(res, 409, {
1281
- enabled: false,
1282
- error: selection.error,
1283
- devices: selection.devices,
1284
- });
1285
- return;
1445
+ return { status: 409, body: {
1446
+ enabled: false,
1447
+ error: selection.error,
1448
+ instructs: selection.instructs,
1449
+ devices: selection.devices,
1450
+ } };
1286
1451
  }
1287
1452
  // The serial pinned at REPLY time, which under an overlapping /enable can differ from the pin
1288
1453
  // this press made -- and reply time is the correct read: the verify probe rode the forward as
@@ -1305,7 +1470,9 @@ async function handleEnable(res, deviceSerial, authored) {
1305
1470
  // The second is not the old per-process one-shot back: that spent a teardown on the first enable
1306
1471
  // even when boot had already reaped. reapScreenOnce fires only when boot did not, and without it
1307
1472
  // 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.
1473
+ // serial and only an arm can set one. Neither is ever earned by an unattended attempt (see the
1474
+ // `auto` parameter): a switched auto attempt is refused outright below, and a same-device one
1475
+ // takes the detection-only reset.
1309
1476
  //
1310
1477
  // Live work IS in reach on that path, and iOS is where it matters. armDevice returns before the
1311
1478
  // reap unless the transport implements selectDeviceAsync, and only AndroidTransport does
@@ -1321,6 +1488,34 @@ async function handleEnable(res, deviceSerial, authored) {
1321
1488
  const pinned = selection && selection.ok ? (selection.serial ?? null) : null;
1322
1489
  // A null pin means "nothing attached", not "the hardware changed".
1323
1490
  const switched = pinned !== null && lastArmedSerial !== null && pinned !== lastArmedSerial;
1491
+ // An unattended attempt must not adopt DIFFERENT hardware than this process last armed: a
1492
+ // hardware swap is a human-scale event, and the swap teardown below (kill the live cast,
1493
+ // delete saved clips, pkill screenrecord device-wide) is exactly the destructive step a
1494
+ // timer never earns. Refusing — rather than arming without the teardown — also keeps
1495
+ // lastArmedSerial intact, so the press that follows still reads the swap and spends the
1496
+ // teardown it is owed; arming here and advancing the serial would hide the swap from that
1497
+ // press.
1498
+ if (switched && auto) {
1499
+ // The pin has already moved to the new hardware (selectDevice above), and the stream proxy
1500
+ // reasserts its forward onto the current pin on every connect, so from here the tab reads the
1501
+ // NEW device. The per-device state that belongs to the OLD one must not follow it: the
1502
+ // retained logcat ring would replay device A's lines into a stream now serving device B, and
1503
+ // the pulled-DB scratch is A's. Same two drops the switched path below performs; only the
1504
+ // screen teardown is withheld, and lastArmedSerial stays put so the press earns it.
1505
+ cleanupPulledDatabases();
1506
+ logSession?.restart();
1507
+ return { status: 200, body: {
1508
+ enabled: false,
1509
+ // Reachable only on a transport without resolveDevice (or a listing that changed between
1510
+ // the resolve above and this pick), so the pin HAS moved here; say so.
1511
+ error: "The attached device changed and the dashboard now points at it. Press Reconnect to arm it.",
1512
+ instructs: true,
1513
+ // Terminal for the automation (see the marker on the env refusal above): lastArmedSerial is
1514
+ // kept, so every later unattended attempt onto this device is refused identically.
1515
+ refusal: "device_changed",
1516
+ device_serial: pinnedSerial(),
1517
+ } };
1518
+ }
1324
1519
  if (switched) {
1325
1520
  // A real hardware change earns the teardown every time, not once per process, so this is the
1326
1521
  // one reap that does not go through reapScreenOnce. Setting the flag here still tells a later
@@ -1328,10 +1523,13 @@ async function handleEnable(res, deviceSerial, authored) {
1328
1523
  reapedThisProcess = true;
1329
1524
  dashboardScreen.reset();
1330
1525
  }
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.
1526
+ else if (auto || !reapScreenOnce(pinned, false)) {
1527
+ // No teardown was owed — or this is the unattended auto re-arm, which may never spend one
1528
+ // (see the `auto` parameter): the one-shot stays unspent for the next human press, which is
1529
+ // where the responsibility for killing a live cast and deleting clips belongs. false covers
1530
+ // the empty-cable enable for the same reason the seed below needs a real pin: there is no
1531
+ // device to reap on, so spending the one-shot there would leave a later real pin with
1532
+ // nothing left to earn a teardown with.
1335
1533
  dashboardScreen.resetDetection();
1336
1534
  }
1337
1535
  // Only remember a serial we actually ARMED. selectDevice returns { ok: true, serial: null } when
@@ -1365,12 +1563,13 @@ async function handleEnable(res, deviceSerial, authored) {
1365
1563
  const forwarded = forwardForRead();
1366
1564
  if (!forwarded) {
1367
1565
  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;
1566
+ return { status: 200, body: {
1567
+ enabled: false,
1568
+ error: reason ?? "ADB forward failed. Is a device connected?",
1569
+ // adb's own text, or a question: neither tells the user what to do.
1570
+ instructs: false,
1571
+ device_serial: pinnedSerial(),
1572
+ } };
1374
1573
  }
1375
1574
  // activateAsync() never throws; a failed broadcast is recorded on the transport.
1376
1575
  // Surfacing it here gives the dashboard user the actual adb error instead of a bare
@@ -1385,27 +1584,33 @@ async function handleEnable(res, deviceSerial, authored) {
1385
1584
  }
1386
1585
  const activateError = transport.getLastActivateError?.() ?? null;
1387
1586
  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;
1587
+ return { status: 200, body: {
1588
+ enabled: false,
1589
+ error: `Broadcast failed: ${activateError}. Is the device connected?`,
1590
+ instructs: false,
1591
+ device_serial: pinnedSerial(),
1592
+ } };
1394
1593
  }
1395
1594
  // Verify by pinging the device the same way /health does (the shared pingDevice, so the
1396
1595
  // ceiling and the three-state rules cannot drift from the other probe sites).
1397
1596
  const ping = await pingDevice();
1398
1597
  const enabled = ping.state === "armed" && ping.status === 200;
1598
+ // A verified arm refutes any cached "no_session" the same way a stream connect does (the
1599
+ // memo is evidence about a session this route just restored): without this, another stream
1600
+ // client's mid-retry memo read could announce the pre-arm diagnosis for up to its TTL and
1601
+ // drive that tab to fire a spurious /enable against the live session.
1602
+ if (enabled)
1603
+ invalidateOutageDiagnosis();
1399
1604
  // Probe the process state only on the failure path: a successful enable needs no diagnosis,
1400
1605
  // and the probe is a real adb round trip. Capped short, because by this point the failure is
1401
1606
  // already established and the user is watching a request that has stalled their SSE tabs; an
1402
1607
  // explanation must not cost more than the operation it explains. The MCP path keeps the
1403
1608
  // patient default, where seconds of ping retries have already elapsed and a real answer
1404
1609
  // 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
- });
1610
+ return { status: 200, body: {
1611
+ ...enableResultBody(enabled, keepAliveHookFor(authored), enabled ? "unknown" : readProcessState(transport, DIAGNOSTIC_PS_TIMEOUT_MS)),
1612
+ device_serial: pinnedSerial(),
1613
+ } };
1409
1614
  }
1410
1615
  // The device-buffered source kinds, in one table so a new source is one row here: the
1411
1616
  // device API route segment (clog and trace pluralize; the rest match the kind name) and
@@ -2116,12 +2321,138 @@ export function parseLogcat(line, resolvePkg = packageForPid) {
2116
2321
  package: resolvePkg(pidN),
2117
2322
  };
2118
2323
  }
2324
+ // How long a freshly opened device stream may go without response HEADERS before the attempt is
2325
+ // declared dead. A healthy device answers /api/stream immediately; the pathological case this
2326
+ // bounds is a dead device-side socket behind a LIVE adb forward, where the host adb server
2327
+ // accepts the TCP connection unconditionally and then nothing ever answers — no error event, no
2328
+ // end event, just silence (observed live 2026-09-03: a stream that emitted no _status frame at
2329
+ // all). Generous enough to sit above pingDevice's observed 2.2s worst case.
2330
+ const STREAM_RESPONSE_TIMEOUT_MS = 6000;
2331
+ // Test seam: the real deadline is deliberately generous, which would make every hang-mode test
2332
+ // wait it out in real time. Never read anywhere else.
2333
+ let streamResponseTimeoutMs = STREAM_RESPONSE_TIMEOUT_MS;
2334
+ export function _setStreamResponseTimeoutForTest(ms) {
2335
+ streamResponseTimeoutMs = ms ?? STREAM_RESPONSE_TIMEOUT_MS;
2336
+ }
2337
+ // Why the device stream keeps dying, answered from the device's own socket table — the one read
2338
+ // the adb forward cannot distort (see pingDevice's classification rules: through a forward, an
2339
+ // absent socket and a live-but-hiccuping session both present as resets). ABSENT means no radar
2340
+ // server is bound anywhere on the device: the session ENDED (idle watchdog, app restart), and
2341
+ // only a re-enable brings it back — which the retry loop deliberately never performs (enabling
2342
+ // binds an identity and mutates device state; a read loop must not, and a wire-contract machine
2343
+ // consumer holding /stream must never arm a device by holding it). The dashboard CLIENT acts on
2344
+ // this instead: its auto-re-arm is the human's own tab pressing its own Reconnect.
2345
+ //
2346
+ // One probe at a time, memoized briefly: every open stream connection retries on its own clock,
2347
+ // so several tabs against a dead session would otherwise each run their own adb read (a call
2348
+ // with a 5s ceiling) every few seconds.
2349
+ const OUTAGE_DIAGNOSIS_TTL_MS = 8000;
2350
+ let outageDiagnosisTtlMs = OUTAGE_DIAGNOSIS_TTL_MS;
2351
+ // Test seam for the memo TTL: the collapse-slot invariants below are only observable once the
2352
+ // memo has expired, and 8 seconds of wall clock per assertion is the flake this seam avoids.
2353
+ export function _setOutageDiagnosisTtlForTest(ms) {
2354
+ outageDiagnosisTtlMs = ms ?? OUTAGE_DIAGNOSIS_TTL_MS;
2355
+ }
2356
+ let lastOutageDiagnosis = null;
2357
+ let outageDiagnosisInflight = null;
2358
+ // Bumped wherever a live connect invalidates the diagnosis. A probe is an adb round trip
2359
+ // with a 5s ceiling racing a 1-2s reconnect cadence, so probe-resolves-after-recovery is the
2360
+ // COMMON ordering: without the generation check, that late resolution would re-poison the
2361
+ // just-cleared memo with a fresh timestamp, and any other stream (a second tab) or a quick
2362
+ // re-drop of this one would inherit "no_session" for the full TTL and re-arm against the
2363
+ // live session.
2364
+ let outageDiagnosisGeneration = 0;
2365
+ // Test seam: the real probe reaches a physical device over adb, which a test host may or may
2366
+ // not have, so tests pin the answer instead of inheriting whatever hardware is attached.
2367
+ let outageProbe = () => transport.radarSocketPresentAsync?.() ?? Promise.resolve("unknown");
2368
+ export function _setOutageProbeForTest(probe) {
2369
+ outageProbe = probe ?? (() => transport.radarSocketPresentAsync?.() ?? Promise.resolve("unknown"));
2370
+ lastOutageDiagnosis = null;
2371
+ outageDiagnosisInflight = null;
2372
+ outageDiagnosisGeneration++;
2373
+ // This is the "restore the diagnosis machinery" seam, so the TTL goes back with the rest: a
2374
+ // test that shortened it and forgot its own restore must not leak a 50ms memo into the next.
2375
+ outageDiagnosisTtlMs = OUTAGE_DIAGNOSIS_TTL_MS;
2376
+ }
2377
+ // Test seams for the diagnosis cache itself. The generation rule is a pure invariant about
2378
+ // ordering (a probe that resolves after an invalidation must not cache), and driving it
2379
+ // through the real stream would mean racing an adb-shaped probe against a live reconnect
2380
+ // cadence on the wall clock — the flake this pair exists to avoid.
2381
+ export function _diagnoseOutageForTest() {
2382
+ return diagnoseStreamOutage();
2383
+ }
2384
+ export function _invalidateOutageDiagnosisForTest() {
2385
+ invalidateOutageDiagnosis();
2386
+ }
2387
+ // A live connect refutes any "no_session" — cached, in flight, or both. Exported to the
2388
+ // connect callback only through this helper so the memo and the pending write cannot be
2389
+ // invalidated separately (clearing just the memo was cycle-2's reopened race).
2390
+ function invalidateOutageDiagnosis() {
2391
+ lastOutageDiagnosis = null;
2392
+ // Drop the in-flight slot too: its eventual result is pre-invalidation evidence, and a
2393
+ // post-recovery consult must start a FRESH probe rather than await (or worse, adopt) the
2394
+ // orphan. The orphan's own cleanup is identity-checked, so it cannot null a successor.
2395
+ outageDiagnosisInflight = null;
2396
+ outageDiagnosisGeneration++;
2397
+ }
2398
+ async function diagnoseStreamOutage() {
2399
+ const now = Date.now();
2400
+ if (lastOutageDiagnosis && now - lastOutageDiagnosis.ts < outageDiagnosisTtlMs) {
2401
+ return lastOutageDiagnosis.reason;
2402
+ }
2403
+ if (outageDiagnosisInflight)
2404
+ return outageDiagnosisInflight;
2405
+ const generation = outageDiagnosisGeneration;
2406
+ // A holder rather than a bare binding: the async body needs its own promise's identity for
2407
+ // the slot-release check below, and it can run synchronously up to its first await —
2408
+ // before any direct `const probe = …` binding would initialize.
2409
+ const holder = { p: null };
2410
+ holder.p = (async () => {
2411
+ let reason = null;
2412
+ try {
2413
+ // The probe is CALLED synchronously (concurrent consults rely on it starting inside this
2414
+ // tick), but a synchronous throw is turned into a rejection so the body still suspends at
2415
+ // the await. Without that, a sync throw would let this whole body finish BEFORE the caller
2416
+ // stores holder.p into the collapse slot; the slot would then hold an already-settled
2417
+ // promise that the identity-checked release below never clears, wedging every later
2418
+ // consult on a stale null until the next live connect.
2419
+ let probe;
2420
+ try {
2421
+ probe = Promise.resolve(outageProbe());
2422
+ }
2423
+ catch (e) {
2424
+ probe = Promise.reject(e);
2425
+ }
2426
+ reason = (await probe) === "absent" ? "no_session" : null;
2427
+ }
2428
+ catch {
2429
+ // An unreadable socket table is "unknown", and unknown never classifies an outage.
2430
+ }
2431
+ // Release the collapse slot only if it is still OURS: a probe orphaned by an
2432
+ // invalidation (a live connect, the test seam) must not null a successor's in-flight
2433
+ // promise and briefly break the one-probe-at-a-time collapse.
2434
+ if (outageDiagnosisInflight === holder.p)
2435
+ outageDiagnosisInflight = null;
2436
+ // A stale probe reports nothing and caches nothing: evidence gathered before the
2437
+ // invalidation describes an outage that already ended.
2438
+ if (generation !== outageDiagnosisGeneration)
2439
+ return null;
2440
+ lastOutageDiagnosis = { ts: Date.now(), reason };
2441
+ return reason;
2442
+ })();
2443
+ outageDiagnosisInflight = holder.p;
2444
+ return holder.p;
2445
+ }
2119
2446
  /**
2120
2447
  * Self-healing SSE proxy. Keeps ONE long-lived response open to the browser and
2121
2448
  * internally (re)connects to the device `/api/stream` every couple seconds while
2122
2449
  * it is down, so the browser's EventSource never sees a close and never gives up.
2123
2450
  * Every other retry it rebuilds the adb forward (the real cause of recurring
2124
2451
  * "unreachable"), reusing AndroidTransport rather than shelling adb directly.
2452
+ * When retries keep failing it additionally asks WHY (see diagnoseStreamOutage)
2453
+ * and stamps the answer as `reason` on the `_status` frame, so a client can tell
2454
+ * "transport blip, the proxy will heal this" from "no radar session exists and
2455
+ * someone has to re-enable".
2125
2456
  *
2126
2457
  * When the active spec wants logs (source "log" or "all"), the handler subscribes
2127
2458
  * to the shared session-long logSession: it is first replayed the entire retained
@@ -2140,11 +2471,26 @@ function handleStream(req, res) {
2140
2471
  let upstream = null;
2141
2472
  let closed = false;
2142
2473
  let lastState = "";
2143
- const announce = (state, msg) => {
2144
- if (state === lastState)
2474
+ let lastReason = "";
2475
+ let headersDeadline = null;
2476
+ const announce = (state, msg, reason) => {
2477
+ // Dedup on state AND reason, with one asymmetry: a diagnosed outage keeps its diagnosis.
2478
+ // The retry loop re-announces generic "waiting" wording on every failed attempt, and once
2479
+ // this outage has been classified (reason set), that generic repeat is the SAME outage
2480
+ // described worse — letting it through would strip the reason the client is acting on
2481
+ // (see the dashboard's auto-re-arm) a second or two after it arrived. A reason CHANGE does
2482
+ // pass: the re-diagnosis retires a stale no_session with reason "undiagnosed" (a frame the
2483
+ // client reads as "drop the latch", not as a diagnosis of its own).
2484
+ if (state === lastState && !reason && lastReason)
2485
+ return;
2486
+ if (state === lastState && (reason ?? "") === lastReason)
2145
2487
  return;
2146
2488
  lastState = state;
2147
- res.write(`data: ${JSON.stringify({ type: "_status", event: { state, msg } })}\n\n`);
2489
+ lastReason = reason ?? "";
2490
+ const event = { state, msg };
2491
+ if (reason)
2492
+ event.reason = reason;
2493
+ res.write(`data: ${JSON.stringify({ type: "_status", event })}\n\n`);
2148
2494
  };
2149
2495
  // Keep the persistent logcat capture armed for the life of this connection.
2150
2496
  // start() is idempotent, so it is safe to call both on initial setup and from
@@ -2178,6 +2524,41 @@ function handleStream(req, res) {
2178
2524
  return;
2179
2525
  settled = true;
2180
2526
  retries++;
2527
+ // A failure that keeps repeating deserves a WHY. The second attempt (the first repeat —
2528
+ // one failure is routine) and a coarse cadence after that, so a fresh classification can
2529
+ // still ARRIVE mid-outage without running an adb probe on every 2s retry. announce never
2530
+ // downgrades a reasoned waiting to a generic one on its own (see its dedup asymmetry), but
2531
+ // a later probe that no longer finds the session absent (the socket is present, or the
2532
+ // table cannot be read because the device is gone) RETIRES a diagnosis this outage
2533
+ // announced: the outage changed nature under the latched reason, and without this the
2534
+ // client's headline kept asserting "no radar session" over a reason span saying the device
2535
+ // is unreachable, while its automation spent attempts on hardware that was not there.
2536
+ // Fire-and-forget: the probe must never delay the reconnect cadence it is describing.
2537
+ if (retries === 2 || retries % 6 === 0) {
2538
+ // A probe orphaned by an invalidation (this tab's own arm landing, an MCP activate, a live
2539
+ // connect) reports null exactly like a fresh "not absent" answer would. The generation tells
2540
+ // them apart: a stale null must not retire a diagnosis against a session that just armed.
2541
+ const generation = outageDiagnosisGeneration;
2542
+ void diagnoseStreamOutage().then((reason) => {
2543
+ // The connected check closes a REPRODUCED race: the probe is an adb round trip (5s
2544
+ // ceiling) racing a 1-2s reconnect cadence, so a session restored during its flight
2545
+ // (an auto-re-arm landing, an MCP activate, a manual press) can reconnect this stream
2546
+ // before the probe resolves — and announcing the stale diagnosis then would drive the
2547
+ // client to fire /enable AGAINST THE LIVE SESSION it just got back, the exact clobber
2548
+ // the socket-table diagnosis exists to prevent.
2549
+ if (closed || lastState === "connected" || generation !== outageDiagnosisGeneration)
2550
+ return;
2551
+ if (reason === null) {
2552
+ // "Not absent" covers both a socket that is present and a table that could not be read
2553
+ // (device gone, adb busy), so the wording asserts no cause; the generic per-retry
2554
+ // message is what the loop would say anyway.
2555
+ if (lastReason === "no_session")
2556
+ announce("waiting", "device not answering, retrying…", "undiagnosed");
2557
+ return;
2558
+ }
2559
+ announce("waiting", "no radar session on the device", reason);
2560
+ });
2561
+ }
2181
2562
  // planReconnect (shared/stream.ts) owns the cadence: every other retry it
2182
2563
  // rebuilds a clean forward before reconnecting and returns the delay. One
2183
2564
  // implementation for this proxy and the MCP stream, so a tuning change
@@ -2193,12 +2574,44 @@ function handleStream(req, res) {
2193
2574
  // (tuned for "device end died"), which would only catch a foreign repoint by luck on
2194
2575
  // half of attempts; this cheap check-first call covers every attempt instead.
2195
2576
  forwardForRead();
2577
+ // Bound the wait for response headers: see STREAM_RESPONSE_TIMEOUT_MS. Without this, the
2578
+ // accepted-but-never-answered connect mode fires none of the callbacks below and the
2579
+ // stream sits silent forever — no _status, no retry, nothing for a client to act on.
2580
+ // Per-ATTEMPT const, mirrored into the connection-scoped slot only for the close
2581
+ // teardown: each attempt's handlers clear their OWN deadline, so a stale attempt's late
2582
+ // error event can never clear the live attempt's timer out from under it.
2583
+ const myDeadline = setTimeout(() => {
2584
+ if (closed)
2585
+ return;
2586
+ announce("waiting", "device not answering, retrying…");
2587
+ try {
2588
+ upstream?.destroy();
2589
+ }
2590
+ catch {
2591
+ // already torn down
2592
+ }
2593
+ retry();
2594
+ }, streamResponseTimeoutMs);
2595
+ headersDeadline = myDeadline;
2196
2596
  upstream = http.request({
2197
2597
  host: RADAR_HOST,
2198
2598
  port: RADAR_PORT,
2199
2599
  path: "/api/stream",
2200
2600
  method: "GET",
2201
2601
  }, (up) => {
2602
+ clearTimeout(myDeadline);
2603
+ if (headersDeadline === myDeadline)
2604
+ headersDeadline = null;
2605
+ // A fresh outage on a long-lived connection must diagnose as early as the first one:
2606
+ // the "second failure" trigger and planReconnect's every-other-attempt forward
2607
+ // rebuild both key off this counter, and neither should inherit the count from an
2608
+ // outage that already recovered.
2609
+ retries = 0;
2610
+ // A live connect refutes any "no_session" — the cached memo AND a probe still in
2611
+ // flight (see invalidateOutageDiagnosis): without this, other stream clients would
2612
+ // re-read the pre-recovery diagnosis for up to its TTL and re-arm against the
2613
+ // healthy session.
2614
+ invalidateOutageDiagnosis();
2202
2615
  announce("connected", "device stream connected");
2203
2616
  // Re-arm logs on the same path the device proxy heals on: if the device
2204
2617
  // dropped and came back, `adb logcat` had exited; restart it (idempotent)
@@ -2215,6 +2628,9 @@ function handleStream(req, res) {
2215
2628
  });
2216
2629
  });
2217
2630
  upstream.on("error", () => {
2631
+ clearTimeout(myDeadline);
2632
+ if (headersDeadline === myDeadline)
2633
+ headersDeadline = null;
2218
2634
  announce("waiting", "device unreachable, retrying…");
2219
2635
  retry();
2220
2636
  });
@@ -2271,6 +2687,8 @@ function handleStream(req, res) {
2271
2687
  req.on("close", () => {
2272
2688
  closed = true;
2273
2689
  clearInterval(heartbeat);
2690
+ if (headersDeadline)
2691
+ clearTimeout(headersDeadline);
2274
2692
  if (unsubscribeLogs)
2275
2693
  unsubscribeLogs(); // detach listener; capture stays up
2276
2694
  try {