@slack/radar-mcp 1.19.0 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +48 -8
  2. package/dist/mcp/api-paths.d.ts +11 -0
  3. package/dist/mcp/api-paths.js +67 -16
  4. package/dist/mcp/index.js +24 -7
  5. package/dist/mcp/network-detail.d.ts +5 -0
  6. package/dist/mcp/network-detail.js +86 -0
  7. package/dist/mcp/radar-response.d.ts +7 -0
  8. package/dist/mcp/radar-response.js +15 -0
  9. package/dist/mcp/session-backfill.d.ts +9 -3
  10. package/dist/mcp/session-backfill.js +77 -17
  11. package/dist/mcp/session-detail.js +54 -2
  12. package/dist/mcp/session-query.js +53 -11
  13. package/dist/mcp/sources-gate.js +4 -0
  14. package/dist/mcp/switchboard-tools.d.ts +9 -0
  15. package/dist/mcp/switchboard-tools.js +40 -0
  16. package/dist/mcp/tools.js +69 -18
  17. package/dist/shared/constants.d.ts +14 -3
  18. package/dist/shared/constants.js +14 -3
  19. package/dist/shared/event-spool.js +3 -2
  20. package/dist/shared/form-body.d.ts +18 -0
  21. package/dist/shared/form-body.js +251 -0
  22. package/dist/shared/stream.d.ts +1 -1
  23. package/dist/shared/switchboard.d.ts +9 -0
  24. package/dist/shared/switchboard.js +54 -0
  25. package/dist/shared/wire.d.ts +32 -0
  26. package/dist/web/install-app.d.ts +64 -1
  27. package/dist/web/install-app.js +174 -24
  28. package/dist/web/macapp/RadarApp.swift +1287 -71
  29. package/dist/web/public/index.html +216 -11
  30. package/dist/web/public/next/app.js +22 -12
  31. package/dist/web/public/next/db.js +180 -18
  32. package/dist/web/public/next/feed.js +571 -53
  33. package/dist/web/public/next/filters.js +160 -34
  34. package/dist/web/public/next/form-body.js +252 -0
  35. package/dist/web/public/next/inspector.js +103 -12
  36. package/dist/web/public/next/registry.js +33 -3
  37. package/dist/web/public/next/store.js +577 -53
  38. package/dist/web/public/next/voice-model.js +532 -0
  39. package/dist/web/public/next/voice.js +397 -0
  40. package/dist/web/server.d.ts +110 -6
  41. package/dist/web/server.js +436 -40
  42. package/dist/web/spec.d.ts +13 -6
  43. package/dist/web/spec.js +89 -6
  44. package/package.json +3 -3
@@ -1,4 +1,5 @@
1
1
  import http from "http";
2
+ import { SWITCHBOARD_KIND, SWITCHBOARD_BACKFILL_DEADLINE_MS, SWITCHBOARD_BACKFILL_SESSIONS, newestSwitchboardSessionIds, switchboardListPath, switchboardPageEvents, switchboardSessionPath, } from "../shared/switchboard.js";
2
3
  import fs from "fs";
3
4
  import os from "os";
4
5
  import path from "path";
@@ -296,6 +297,15 @@ export function registerScreenCleanupOnBind() {
296
297
  // harmlessly), it does not misfire an auto-close. Exported so tests pin the real constant
297
298
  // instead of a duplicated copy.
298
299
  export const TAB_LIVENESS_MS = 75_000;
300
+ /**
301
+ * How recently a tab must have polled to count as SOMEONE USING the dashboard, which is a different
302
+ * question from whether it is stale enough to auto-close, and takes a much tighter answer.
303
+ *
304
+ * Three of the dashboard's own five second profile polls. Generous enough that a live tab never
305
+ * flickers out of it, tight enough that closing a window releases the port in seconds rather than in
306
+ * the minute and a quarter TAB_LIVENESS_MS would impose.
307
+ */
308
+ export const TAB_IN_USE_MS = 15_000;
299
309
  // How long the dashboard must have ZERO live tabs before auto-close fires. Sized at ~3x the
300
310
  // worst-case legitimate gap between presence pings (~60-90s under intensive throttling), so a
301
311
  // backgrounded tab is never mistaken for a closed one. Not 90s — that is barely one throttled
@@ -303,10 +313,16 @@ export const TAB_LIVENESS_MS = 75_000;
303
313
  // backgrounded tab outright, permanently stopping its polling; auto-close eventually firing in
304
314
  // that case is correct behavior ("nobody is looking"), not a bug to work around.
305
315
  export const AUTO_CLOSE_GRACE_MS = 5 * 60_000;
316
+ // How long an authored write keeps a dashboard counted as in use by an agent session, when no tab is
317
+ // open. Its own constant rather than borrowing AUTO_CLOSE_GRACE_MS, which starts at the same value
318
+ // and answers a different question: that one decides when a process should end ITSELF, this one
319
+ // decides how long a quiet session may hold a port against another process taking it. Retuning
320
+ // either for its own reason must not silently retune the other.
321
+ export const MCP_IN_USE_MS = 5 * 60_000;
306
322
  // Sweep cadence: cheap (a map prune + a subtraction), frequent enough that auto-close fires
307
323
  // promptly once the grace window elapses.
308
324
  const AUTO_CLOSE_SWEEP_MS = 15_000;
309
- const presence = { tabs: new Map(), emptySince: null, everSeen: false };
325
+ const presence = { tabs: new Map(), emptySince: null, everSeen: false, keepAliveAt: null };
310
326
  /**
311
327
  * Pure auto-close decision, mirroring screen.ts's nextViewerAction/shouldRelaunch precedent:
312
328
  * the sweep owns the timestamp bookkeeping, this owns only the yes/no. Close only when there
@@ -323,6 +339,96 @@ export function shouldAutoClose(liveTabs, everSeen, msSinceEmpty) {
323
339
  return false;
324
340
  return msSinceEmpty >= AUTO_CLOSE_GRACE_MS;
325
341
  }
342
+ /**
343
+ * Whether anyone is using this dashboard RIGHT NOW, which is a different question from
344
+ * shouldAutoClose() above and deliberately not the same answer.
345
+ *
346
+ * shouldAutoClose adds the grace window, because a process deciding to end itself should be slow
347
+ * about it. This is read by a DIFFERENT process deciding whether it may take the port, and there the
348
+ * grace window is exactly wrong: the five minutes after a dock app quits and its tab closes is the
349
+ * window an upgrade lands in, and a leftover nobody is looking at is the thing that most needs
350
+ * replacing.
351
+ *
352
+ * So: a live tab counts, and an MCP session with no tab open counts (markKeepAlive clears the empty
353
+ * marker without setting everSeen, which is what keeps an hour-long debugging session alive), but a
354
+ * dashboard whose last tab has gone does not.
355
+ *
356
+ * Exported for unit testing without a clock or a socket, same as shouldAutoClose.
357
+ */
358
+ export function isInUse(now = Date.now()) {
359
+ return inUseReason(now) !== "no";
360
+ }
361
+ /**
362
+ * WHY this dashboard is in use, not merely whether, because the two claims are worth different
363
+ * decisions to the process asking.
364
+ *
365
+ * A "tab" claim is a window someone has open. A "mcp" claim is an agent session driving this
366
+ * dashboard with no window of its own, and stopping that costs the session's pulled databases, its
367
+ * device pin and its logcat ring, none of which it can get back. A single yes/no cannot tell those
368
+ * apart, so a launcher had to treat them the same, and the only safe reading of "the same" is the
369
+ * cautious one, which then blocks the upgrade this whole path exists to perform.
370
+ *
371
+ * Priority is deliberate: an mcp claim outranks a tab claim, because the app's OWN window is a tab
372
+ * and a decision about whether to disturb someone else must not be answered by our own presence.
373
+ *
374
+ * `ignoreTab` is how a caller asks the narrower question it actually has: is anyone OTHER than my own
375
+ * window using this. The dock app generates the presence id, hands it to the page it loads, and sends
376
+ * it back here, so its own window stops answering for everybody else. Without it the app could not
377
+ * tell its own tab from a real second browser tab, and had to guess; guessing either way is wrong,
378
+ * because one reading kills a page someone is reading and the other never stops anything.
379
+ */
380
+ export function inUseReason(now = Date.now(), ignoreTab, decision = "take") {
381
+ // A dashboard NO tab has ever opened, which is what an MCP-spawned one looks like. The server
382
+ // refuses to auto-close those for a reason that applies here word for word: nobody can have closed
383
+ // a window that never existed, so its quietness says nothing about whether the session driving it
384
+ // is finished. Without this the in-use answer was more permissive than the server's own protection,
385
+ // and a twenty-minute debugging session with no tab open read as a leftover.
386
+ //
387
+ // Only for a caller deciding whether to TAKE the port. To a caller deciding whether to STOP a server it
388
+ // started itself, this reading is a false positive with teeth: the app spawns a server, its window fails
389
+ // to load (a proxy with no loopback bypass is the documented case), no tab ever polls, and the quit path
390
+ // is told an agent session is driving it. It then leaves the server running, logs a session that does not
391
+ // exist, and the server cannot auto-close either, because shouldAutoClose reads the same everSeen flag.
392
+ // The port is held for good by a process with nothing on screen, which is exactly the orphan the quit
393
+ // path exists to prevent. The caller that spawned the process does not need this guess: it knows the
394
+ // process is its own, and "no window ever opened it" is then an answer rather than a gap.
395
+ if (!presence.everSeen && decision === "take")
396
+ return "mcp";
397
+ // An authored write that named no tab, which is what an agent session's looks like. The dashboard
398
+ // page makes authored writes too (a page load that finds a blank spec, every mode switch and filter
399
+ // Apply), and those name their tab and are credited as presence instead (creditAuthoredWrite), so a
400
+ // window changing a filter does not read as a session here. Checked BEFORE the tab loop so a
401
+ // session driving a dashboard that also has a window open still reads as mcp.
402
+ if (presence.keepAliveAt !== null && now - presence.keepAliveAt <= MCP_IN_USE_MS)
403
+ return "mcp";
404
+ // A tab that is still polling, and how recently it must have polled depends on what the caller is about
405
+ // to do.
406
+ //
407
+ // TAKING the port uses 15s, deliberately not the 75s auto-close uses. That 75s exists so a THROTTLED
408
+ // background tab is not mistaken for a closed one, and borrowing it here made a window someone closed a
409
+ // minute ago still report "in use", which blocked the upgrade for 75 seconds after a window closed,
410
+ // exactly the quit-and-reopen the installer instructs. Being tight costs a relaunch a few seconds later,
411
+ // which is what the user was asking for anyway.
412
+ //
413
+ // STOPPING uses the 75s, because that justification does not survive the change of caller: nothing
414
+ // relaunches a server after it is stopped. A hidden tab throttled to one poll a minute reads as absent at
415
+ // 15s, and stopping its server leaves it reloading onto a dead port with no way to recover from that tab.
416
+ // Being loose here costs one orphaned server, which the launch path already reclaims.
417
+ //
418
+ // Neither window helps a tab Chrome has DISCARDED, which stops polling forever. That is the same
419
+ // limitation auto-close names and accepts: a discarded tab reads as nobody looking.
420
+ const tabWindow = decision === "stop" ? TAB_LIVENESS_MS : TAB_IN_USE_MS;
421
+ for (const [id, ts] of presence.tabs) {
422
+ // Skipped BEFORE the freshness check, not after: the caller's own window is the freshest tab in the
423
+ // map, so an ordering that tests liveness first returns "tab" on it every time and the parameter
424
+ // does nothing.
425
+ if (ignoreTab !== undefined && id === ignoreTab)
426
+ continue;
427
+ if (now - ts <= tabWindow)
428
+ return "tab";
429
+ }
430
+ return "no";
431
+ }
326
432
  // A tab pinged /health with its id: record it live and remember a tab was seen. A fresh id
327
433
  // after zero live tabs is the 0->1 transition, so clear the empty marker immediately. `now` is
328
434
  // injectable so the sweep's staleness math is unit-testable with a fake clock.
@@ -341,8 +447,9 @@ export function touchTab(id, now = Date.now()) {
341
447
  * pin, and the pulled-DB cache. Deliberately does NOT set everSeen: an MCP-only dashboard that
342
448
  * nobody ever opened stays protected by the everSeen guard even after the MCP goes quiet.
343
449
  */
344
- export function markKeepAlive() {
450
+ export function markKeepAlive(now = Date.now()) {
345
451
  presence.emptySince = null;
452
+ presence.keepAliveAt = now;
346
453
  }
347
454
  /**
348
455
  * Whether a request may buy the process more life. True for our own client and the MCP, false
@@ -371,6 +478,78 @@ export function isAuthoredRequest(headers) {
371
478
  const essence = value.split(";")[0].trim().toLowerCase();
372
479
  return essence === "application/json";
373
480
  }
481
+ /**
482
+ * The shared strictness for both presence-id headers below.
483
+ *
484
+ * Strict for a duller reason than the security gates elsewhere in this file: a wrong read here is
485
+ * SILENT. An id that does not arrive intact matches no tab, and the only symptom is a dashboard that
486
+ * never gets replaced or a window that reports itself as somebody else.
487
+ *
488
+ * A REPEATED header is the case worth spelling out, because the obvious guess about it is wrong. Node does
489
+ * not hand a duplicated request header over as an array (only set-cookie arrives that way): it JOINS the
490
+ * values, so `X-Radar-Tab: A` sent twice arrives as the single string `"A, A"`. Measured. Taken at face
491
+ * value that becomes a presence key no tab will ever refresh, and for the next fifteen seconds a probe
492
+ * excluding `A` is told a tab holds the port. So a value carrying a comma is refused, and the array shape
493
+ * is still handled because the type admits it.
494
+ *
495
+ * The ids this accepts are generated by the app (a UUID) and by the page (a UUID, or a random decimal
496
+ * string in a browser without crypto.randomUUID), so refusing a comma costs nothing real.
497
+ */
498
+ function presenceIdHeader(value) {
499
+ if (typeof value !== "string")
500
+ return undefined;
501
+ if (value.length === 0 || value.includes(","))
502
+ return undefined;
503
+ return value;
504
+ }
505
+ /**
506
+ * "This request comes FROM the tab with this id." Sent by the dashboard page on its own authored
507
+ * writes, so a write can be credited to the window that made it.
508
+ */
509
+ export function readTabIdentity(headers) {
510
+ return presenceIdHeader(headers["x-radar-tab"]);
511
+ }
512
+ /**
513
+ * "Leave this id out of the answer." Sent by a launcher asking whether anyone OTHER than the window it
514
+ * owns is using this dashboard.
515
+ *
516
+ * A separate header from the identity one above, carrying the same value, and deliberately so: the app
517
+ * that sends this is NOT the tab. Its window may have failed to load, or may be showing the failure
518
+ * page. One header would invite a future route to treat the app's own probe as proof that its tab is
519
+ * live, which would record presence for a window that does not exist. Two names make that impossible
520
+ * rather than merely discouraged.
521
+ */
522
+ export function readIgnoredTab(headers) {
523
+ return presenceIdHeader(headers["x-radar-ignore-tab"]);
524
+ }
525
+ /**
526
+ * Which decision the caller says it is about to make. Anything other than the one recognised value reads as
527
+ * `take`, which is both the back-compatible answer (no installed launcher sends this) and the conservative
528
+ * one: it is the reading that protects a port rather than the one that permits a stop.
529
+ */
530
+ export function readInUseDecision(headers) {
531
+ return headers["x-radar-in-use-for"] === "stop" ? "stop" : "take";
532
+ }
533
+ /**
534
+ * Credit an authored write to whoever made it: a tab that named itself, or an agent session.
535
+ *
536
+ * The distinction is load-bearing, and getting it wrong was a real bug. `markKeepAlive` is what makes
537
+ * inUseReason answer "mcp", and the dashboard PAGE makes authored writes too: `bootDefault` posts
538
+ * /setspec on any page load that finds a blank spec, and every mode switch and filter Apply posts
539
+ * another. So a person opening the dock app and clicking one tab made the server report an agent
540
+ * session for the next MCP_IN_USE_MS, and "mcp" is the one claim nothing overrides — the launcher
541
+ * refuses to replace it and the quit path refuses to stop it. The app then left its own server running
542
+ * on quit, which is the exact leak the quit path exists to close, reachable by ordinary use.
543
+ *
544
+ * A tab's write is credited as presence instead, which is both true and stronger: it is the same thing
545
+ * the tab's own /health poll records. Only a write from something with no tab at all is a session.
546
+ */
547
+ export function creditAuthoredWrite(tab, now = Date.now()) {
548
+ if (tab !== undefined)
549
+ touchTab(tab, now);
550
+ else
551
+ markKeepAlive(now);
552
+ }
374
553
  /**
375
554
  * One sweep tick: prune stale tab ids, maintain the emptySince marker across the 1->0 / 0->1
376
555
  * transitions, and return whether the dashboard should auto-close now. Owns all timestamp
@@ -406,6 +585,7 @@ export function resetPresenceForTest() {
406
585
  presence.tabs.clear();
407
586
  presence.emptySince = null;
408
587
  presence.everSeen = false;
588
+ presence.keepAliveAt = null;
409
589
  }
410
590
  // Servers already tearing down. Keyed on the server rather than a module flag so the latch
411
591
  // scopes to the thing being closed: a second call for the SAME server is suppressed, while a
@@ -706,6 +886,12 @@ export function createServer(onShutdown) {
706
886
  });
707
887
  return;
708
888
  }
889
+ // Contract §7 (docs/wire-contract.md): every response the Host gate accepts names the host
890
+ // version, so a machine consumer can detect skew (@latest auto-upgrade, stale npx cache, the
891
+ // adopt trap) from any request instead of depending on /spec. Deliberately AFTER the Host
892
+ // check: a DNS-rebound page reads response headers as same-origin, and before this feature
893
+ // the version was never visible past that gate — refusals it issues stay version-silent.
894
+ res.setHeader("X-Radar-Version", RADAR_VERSION);
709
895
  const url = req.url ?? "";
710
896
  const urlPath = url.split("?")[0];
711
897
  // Second chokepoint, DEFAULT DENY. A request must prove it came from our own client unless its
@@ -737,12 +923,54 @@ export function createServer(onShutdown) {
737
923
  if ((req.method === "GET" || req.method === "HEAD") && serveStatic(urlPath, res, req.method === "HEAD", Array.isArray(inm) ? inm[0] : inm)) {
738
924
  return;
739
925
  }
740
- if (url === "/spec" && req.method === "GET") {
741
- // Version marker for a second launcher's adopt path: it can compare this against its own
742
- // RADAR_VERSION and warn on a mismatch (it still adopts; it never kills the holder).
743
- // A header, not a body field, so the /spec fingerprint and the client's change-detection
744
- // key (JSON.stringify of the body) stay byte-identical.
745
- res.setHeader("X-Radar-Version", RADAR_VERSION);
926
+ if (url === "/spec" && (req.method === "GET" || req.method === "HEAD")) {
927
+ // The version marker a second launcher's adopt path compares against its own RADAR_VERSION is
928
+ // the X-Radar-Version HEADER, set for every response at the top of this handler. A header, not
929
+ // a body field, so the /spec fingerprint and the client's change-detection key
930
+ // (JSON.stringify of the body) stay byte-identical.
931
+ //
932
+ // HEAD is here because that header is the only way to ask a running dashboard what version it
933
+ // is, and `curl -sI` is what someone reaches for to do that. Without HEAD the request fell past
934
+ // every handler to the terminal 404, so the answer read as "no dashboard here" while a dashboard
935
+ // was serving the port.
936
+ //
937
+ // The in-use answer rides the SAME response, deliberately: the app already makes this one
938
+ // request, and a second round trip on the launch path would be latency the user waits through
939
+ // before any window appears. Answered here rather than on /health because /spec is the
940
+ // fingerprint every launcher already probes, and because a launcher asking this must not have to
941
+ // send the X-Radar-Dashboard header that /health's presence side door requires.
942
+ //
943
+ // Two headers rather than one richer value, and NOT because anything already reads the first
944
+ // one: both ship together here, so no installed dock app reads the bit without the reason.
945
+ // The split is for the next change. A reader that only needs "is anyone there" keeps a stable
946
+ // answer while the vocabulary of reasons grows, and the wire contract's rule is that a new
947
+ // field may appear at any time and an older reader must ignore it. Widening the 1/0 value
948
+ // instead would make every future reason a breaking change to the same field.
949
+ //
950
+ // X-Radar-Ignore-Tab is the asking app's own presence id, and the answer excludes it. Echoed back
951
+ // in X-Radar-In-Use-Excludes, which is the part that earns its keep: a server too old to know the
952
+ // request header answers "a tab is using it" about the asker's OWN window, and it answers that
953
+ // with exactly the same two headers a current server uses to mean somebody else. The echo is the
954
+ // only thing that tells those apart, so it is what lets the app protect a real second browser tab
955
+ // without refusing to ever replace a dashboard its own window is looking at.
956
+ //
957
+ // Not gated on X-Radar-Dashboard, unlike /health's presence side door. That gate exists because
958
+ // touchTab WRITES: a foreign page could keep a dashboard alive or fake a tab on one. This only
959
+ // narrows the answer this one response carries, changes no state, and cannot be aimed: excluding
960
+ // an id means guessing a uuid, and the result of guessing it is being told nobody is using a
961
+ // dashboard the guesser could already have asked about without the header.
962
+ //
963
+ // X-Radar-In-Use-For names which decision the answer will inform, because the two callers of this
964
+ // route are asking different questions and one answer cannot serve both. See InUseDecision.
965
+ const ignoreTab = readIgnoredTab(req.headers);
966
+ const use = inUseReason(Date.now(), ignoreTab, readInUseDecision(req.headers));
967
+ res.setHeader("X-Radar-In-Use", use === "no" ? "0" : "1");
968
+ if (use !== "no")
969
+ res.setHeader("X-Radar-In-Use-By", use);
970
+ if (ignoreTab !== undefined)
971
+ res.setHeader("X-Radar-In-Use-Excludes", ignoreTab);
972
+ // The framing a HEAD needs to mirror a GET (RFC 9110 9.3.2) is stated by sendJson for every
973
+ // JSON route, so this one is an ordinary send.
746
974
  sendJson(res, 200, loadSpec());
747
975
  return;
748
976
  }
@@ -793,7 +1021,7 @@ export function createServer(onShutdown) {
793
1021
  // Deliberately not awaited; handleEnable answers res itself and never rejects.
794
1022
  // ?auto=1 marks the dashboard's own unattended recovery; see handleEnable's `auto`.
795
1023
  const auto = params.get("auto") === "1";
796
- void handleEnable(res, serial, isAuthoredRequest(req.headers), auto);
1024
+ void handleEnable(res, serial, isAuthoredRequest(req.headers), readTabIdentity(req.headers), auto);
797
1025
  return;
798
1026
  }
799
1027
  if (url === "/stream" && req.method === "GET") {
@@ -974,8 +1202,20 @@ function sendJson(res, status, payload) {
974
1202
  // ERR_HTTP_HEADERS_SENT and crash the whole process. Swallow the duplicate.
975
1203
  if (res.headersSent || res.writableEnded)
976
1204
  return;
977
- res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
978
- res.end(JSON.stringify(payload));
1205
+ // No special case for HEAD. Node drops the body itself when the request method was HEAD, so the
1206
+ // same call answers both, and measuring it was the only way to know: a flag here that skipped the
1207
+ // body produced a byte-identical response, which is a parameter earning nothing.
1208
+ //
1209
+ // Content-Length is stated rather than left to chunked encoding, so a HEAD reports the same
1210
+ // framing a GET would. Node drops the body but keeps the header, which is the whole point: a
1211
+ // caller sizing a response can ask without fetching it. Every JSON route gets that for free here,
1212
+ // which is why it belongs in this helper rather than in one route that happened to need it.
1213
+ const body = JSON.stringify(payload);
1214
+ res.writeHead(status, {
1215
+ "Content-Type": "application/json; charset=utf-8",
1216
+ "Content-Length": Buffer.byteLength(body),
1217
+ });
1218
+ res.end(body);
979
1219
  }
980
1220
  function readBody(req) {
981
1221
  return new Promise((resolve) => {
@@ -1018,8 +1258,10 @@ async function handleSetSpec(req, res, authored) {
1018
1258
  // request, so without the gate any page in the user's browser could postpone auto-close
1019
1259
  // forever by pinging this every few minutes. The spec still gets written either way, which
1020
1260
  // keeps a bare curl working; it just does not buy the process more life.
1261
+ //
1262
+ // Credited to the writer rather than assumed to be a session: see creditAuthoredWrite.
1021
1263
  if (authored)
1022
- markKeepAlive();
1264
+ creditAuthoredWrite(readTabIdentity(req.headers));
1023
1265
  sendJson(res, 200, {
1024
1266
  ok: true,
1025
1267
  url: `http://localhost:${WEB_PORT}`,
@@ -1111,10 +1353,10 @@ async function handleHealth(res) {
1111
1353
  * successful re-arm keeps the dashboard alive (an MCP-driven session can re-enable with no tab
1112
1354
  * open, and that must not let the idle timer fire out from under it).
1113
1355
  *
1114
- * `onEnabled` fires only on a successful probe. The route passes `markKeepAlive` when the
1115
- * request was authored (see isAuthoredRequest) and OMITS it otherwise, so an unauthored caller
1116
- * gets the same body but buys no extra process life. Injected rather than called directly so
1117
- * the keep-alive wiring is testable without a real device probe (handleEnable's ping goes over
1356
+ * `onEnabled` fires only on a successful probe. The route passes a hook that credits the WRITER
1357
+ * (creditAuthoredWrite) when the request was authored (see isAuthoredRequest) and OMITS it otherwise, so
1358
+ * an unauthored caller gets the same body but buys no extra process life. Injected rather than called
1359
+ * directly so the keep-alive wiring is testable without a real device probe (handleEnable's ping goes over
1118
1360
  * a real socket to RADAR_HOST:RADAR_PORT, which this function does not touch at all).
1119
1361
  *
1120
1362
  * A failed probe gets guidance, not a bare false: the broadcast landed (or exited 0 with no
@@ -1127,9 +1369,12 @@ async function handleHealth(res) {
1127
1369
  * through the route cannot cover this — handleEnable's device probe fails with no hardware, which
1128
1370
  * short-circuits before the hook is ever consulted, so a route-level test passes either way (a
1129
1371
  * mutation deleting the gate survived the whole suite before this existed).
1372
+ *
1373
+ * `tab` is the writer, and it decides WHICH credit the hook applies: a re-arm pressed in the dashboard
1374
+ * is a window's, not an agent session's. See creditAuthoredWrite.
1130
1375
  */
1131
- export function keepAliveHookFor(authored) {
1132
- return authored ? markKeepAlive : undefined;
1376
+ export function keepAliveHookFor(authored, tab) {
1377
+ return authored ? () => creditAuthoredWrite(tab) : undefined;
1133
1378
  }
1134
1379
  // Reads the dashboard serves to any local caller. Everything NOT matching is treated as
1135
1380
  // state-changing and needs proof it came from our own client (see isOpenToAnyCaller).
@@ -1297,9 +1542,10 @@ processState = "unknown") {
1297
1542
  // human press never joins an unattended flight: the press earns things the timer may not (the
1298
1543
  // screen teardown, adopting swapped hardware), so it waits for the flight to settle and then
1299
1544
  // 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.
1545
+ // is a superset of what the attempt could have earned. A joiner's own `authored` IS consulted, and so is
1546
+ // the tab it named: the flight's own hook credits only the writer that started it, and after a join those
1547
+ // are two different writers, so the joiner credits itself at the end of handleEnable. That mattered only
1548
+ // once the credit gained a writer; while it was one global keep-alive the winner's call did cover it.
1303
1549
  let enableInFlight = null;
1304
1550
  // Test seam: the next runEnable rejects with this error after `delayMs` (long enough for a second
1305
1551
  // request to join the flight), to prove a rejection still answers every request riding the flight
@@ -1309,6 +1555,10 @@ export function _setEnableFaultForTest(err, delayMs = 300) {
1309
1555
  enableFaultForTest = err ? { err, delayMs } : null;
1310
1556
  }
1311
1557
  async function handleEnable(res, deviceSerial, authored,
1558
+ // The tab that made this request, when one named itself. Travels next to `authored` because the two
1559
+ // are read together: authored decides WHETHER the re-arm buys the process more life, this decides
1560
+ // whose claim that life is recorded under.
1561
+ tab,
1312
1562
  // An UNATTENDED re-arm (the dashboard's own automatic recovery of a diagnosed-dead session,
1313
1563
  // marked with ?auto=1). See runEnable for what it may and may not do.
1314
1564
  auto = false) {
@@ -1358,7 +1608,7 @@ auto = false) {
1358
1608
  else {
1359
1609
  // .finally with an identity check, so a flight that settles after a successor took the slot
1360
1610
  // never clears the successor.
1361
- p = runEnable(target, authored, auto).finally(() => {
1611
+ p = runEnable(target, authored, auto, tab).finally(() => {
1362
1612
  if (enableInFlight?.p === p)
1363
1613
  enableInFlight = null;
1364
1614
  });
@@ -1377,6 +1627,13 @@ auto = false) {
1377
1627
  body: { enabled: false, error: `Enable failed: ${e.message}. Try again.`, instructs: true },
1378
1628
  };
1379
1629
  }
1630
+ // A JOINED request credits itself, because the flight's own hook only credits whoever started it and
1631
+ // after coalescing those are two different writers. The lossy direction is the one that matters: an
1632
+ // agent session joining a window's attempt would have its re-arm recorded as the window's, leave no
1633
+ // session claim on the port, and get taken by the next launcher. While the credit was writer-agnostic
1634
+ // this could not happen, so it arrives with the attribution and is fixed with it.
1635
+ if (joinable && authored && reply.body.enabled)
1636
+ creditAuthoredWrite(tab);
1380
1637
  sendJson(res, reply.status, reply.body);
1381
1638
  }
1382
1639
  /**
@@ -1394,7 +1651,9 @@ async function runEnable(deviceSerial, authored,
1394
1651
  // a process whose env forbids self-arming is refused before any device work, and an auto
1395
1652
  // attempt onto DIFFERENT hardware than this process last armed is refused before the
1396
1653
  // teardown decision; the same-device auto path takes the detection-only reset.
1397
- auto) {
1654
+ auto,
1655
+ // The tab that started this flight, when one named itself. Only reaches keepAliveHookFor below.
1656
+ tab) {
1398
1657
  if (enableFaultForTest) {
1399
1658
  const fault = enableFaultForTest;
1400
1659
  enableFaultForTest = null;
@@ -1608,7 +1867,7 @@ auto) {
1608
1867
  // patient default, where seconds of ping retries have already elapsed and a real answer
1609
1868
  // beats a fast "unknown".
1610
1869
  return { status: 200, body: {
1611
- ...enableResultBody(enabled, keepAliveHookFor(authored), enabled ? "unknown" : readProcessState(transport, DIAGNOSTIC_PS_TIMEOUT_MS)),
1870
+ ...enableResultBody(enabled, keepAliveHookFor(authored, tab), enabled ? "unknown" : readProcessState(transport, DIAGNOSTIC_PS_TIMEOUT_MS)),
1612
1871
  device_serial: pinnedSerial(),
1613
1872
  } };
1614
1873
  }
@@ -1622,12 +1881,111 @@ export const DEVICE_SOURCES = {
1622
1881
  clog: { segment: "clogs", arrayKey: "clogs" },
1623
1882
  trace: { segment: "traces", arrayKey: "traces" },
1624
1883
  };
1884
+ // Switchboard (the Slackbot voice transport) is not a row above because the device keeps it two
1885
+ // levels deep: `GET /api/switchboard` lists session summaries newest first (`total_captured` is
1886
+ // the records the plugin holds; there is no count named `events`), `GET /api/switchboard/<session_id>`
1887
+ // is that summary plus `events`, the page of records oldest first (the newest `limit` of them; the
1888
+ // device pages at 50 when the query is absent, so the caller's limit is forwarded per session or
1889
+ // a talkative session replays as its last few seconds). Records carry a plugin-minted `id`
1890
+ // (strictly increasing across sessions), but there is no per-record /detail, so it stays out of
1891
+ // the table /detail reads. The session cap bounds the round trips on connect (one list plus one
1892
+ // fetch per session); `limit` bounds the records, per session and again on the merged total.
1893
+ // Shapes: SwitchboardSessionSummary in src/shared/wire.ts; `levels` there is unread here (no
1894
+ // waveform yet). The session pick and the paths live in src/shared/switchboard.ts so the MCP's
1895
+ // spool backfill replays the same sessions; re-exported here for the tests that pin them.
1896
+ export { SWITCHBOARD_KIND, SWITCHBOARD_BACKFILL_SESSIONS, SWITCHBOARD_BACKFILL_DEADLINE_MS };
1897
+ // How much longer than the switchboard leg's own deadline the /backfill route waits before it
1898
+ // replies with what has landed. Same-length timers fire in the order they were armed, and the
1899
+ // route's is armed first, so without this the route would reply before the leg could hand back the
1900
+ // sessions that answered.
1901
+ export const BACKFILL_ROUTE_HEADROOM_MS = 250;
1902
+ function getDeviceJson(apiPath) {
1903
+ let rq;
1904
+ const result = new Promise((resolve) => {
1905
+ rq = http.request({ host: RADAR_HOST, port: RADAR_PORT, path: apiPath, method: "GET", timeout: 4000 }, (up) => {
1906
+ let b = "";
1907
+ up.on("data", (c) => (b += c));
1908
+ up.on("end", () => {
1909
+ try {
1910
+ const j = JSON.parse(b);
1911
+ resolve(j !== null && typeof j === "object" && !Array.isArray(j) ? j : null);
1912
+ }
1913
+ catch {
1914
+ resolve(null);
1915
+ }
1916
+ });
1917
+ up.on("error", () => resolve(null));
1918
+ });
1919
+ rq.on("error", () => resolve(null));
1920
+ rq.on("timeout", () => {
1921
+ rq?.destroy();
1922
+ resolve(null);
1923
+ });
1924
+ rq.on("close", () => resolve(null));
1925
+ rq.end();
1926
+ });
1927
+ return { result, abort: () => rq?.destroy() };
1928
+ }
1929
+ // The switchboard replay: the newest SWITCHBOARD_BACKFILL_SESSIONS sessions' records, oldest first,
1930
+ // trimmed to the newest `limit` records overall, as `{type: "switchboard", event}` frames.
1931
+ // Exported so a test can drive it against a fake device without going through the route; the
1932
+ // deadline is a parameter for the same reason. Each session's page is kept as it lands, so when
1933
+ // the deadline fires the reply is whatever arrived by then (a device sitting on one session's
1934
+ // route costs that session, not the whole replay), and the requests still open are dropped.
1935
+ export function fetchSwitchboardBackfill(limit, deadlineMs = SWITCHBOARD_BACKFILL_DEADLINE_MS) {
1936
+ return new Promise((resolve) => {
1937
+ const landed = [];
1938
+ const inflight = new Set();
1939
+ let settled = false;
1940
+ const finish = () => {
1941
+ if (settled)
1942
+ return;
1943
+ settled = true;
1944
+ clearTimeout(timer);
1945
+ for (const g of inflight)
1946
+ g.abort();
1947
+ inflight.clear();
1948
+ resolve(newestSwitchboardRecords(landed.flat(), limit));
1949
+ };
1950
+ const timer = setTimeout(finish, deadlineMs);
1951
+ fetchSwitchboardSessions(limit, landed, inflight).then(finish, finish);
1952
+ });
1953
+ }
1954
+ // Lists the sessions, then fetches the newest few in parallel, pushing each page onto `landed`
1955
+ // as it arrives and keeping the open requests in `inflight` for the deadline above.
1956
+ async function fetchSwitchboardSessions(limit, landed, inflight) {
1957
+ const get = async (apiPath) => {
1958
+ const g = getDeviceJson(apiPath);
1959
+ inflight.add(g);
1960
+ try {
1961
+ return await g.result;
1962
+ }
1963
+ finally {
1964
+ inflight.delete(g);
1965
+ }
1966
+ };
1967
+ const list = await get(switchboardListPath());
1968
+ await Promise.all(newestSwitchboardSessionIds(list).map(async (id) => {
1969
+ // `events` is the page of records on this route; the list route's count is `total_captured`.
1970
+ landed.push(switchboardPageEvents(await get(switchboardSessionPath(id, limit))));
1971
+ }));
1972
+ }
1973
+ // The merge order for every backfill: the record's own device timestamp, 0 when it has none.
1974
+ const when = (e) => Number(e.timestamp) || 0;
1975
+ // Oldest first by the record's own timestamp, then the newest `limit` kept. The pages arrive in
1976
+ // whatever order the device answers, so arrival order says nothing about time; the sort is stable,
1977
+ // so records sharing a timestamp keep the order the device wrote them in.
1978
+ function newestSwitchboardRecords(records, limit) {
1979
+ const sorted = [...records].sort((a, b) => when(a) - when(b));
1980
+ return sorted.slice(Math.max(0, sorted.length - limit)).map((e) => ({ type: SWITCHBOARD_KIND, event: e }));
1981
+ }
1625
1982
  /**
1626
1983
  * Replay the device's recent ring buffers for a source so a freshly-built tab
1627
1984
  * shows history immediately instead of filling only going forward. The device is
1628
- * the source of truth. "all" pulls network+rtm+clog+trace and merges them oldest->newest;
1629
- * "log" is host-side (no device buffer) and so has nothing to replay. Returns
1630
- * `[{type, event}]` frames mirroring the stream shape.
1985
+ * the source of truth. "all" pulls network+rtm+clog+trace+switchboard and merges them
1986
+ * oldest->newest; "log" is host-side (no device buffer) and so has nothing to replay. Returns
1987
+ * `[{type, event}]` frames mirroring the stream shape. Switchboard records carry `timestamp`
1988
+ * (epoch ms) like the ring kinds, so one sort key orders the merge.
1631
1989
  */
1632
1990
  function handleBackfill(req, res) {
1633
1991
  // Reassert before reading: see forwardForRead's doc comment. A failed reassert still
@@ -1637,12 +1995,51 @@ function handleBackfill(req, res) {
1637
1995
  forwardForRead();
1638
1996
  const u = new URL(req.url ?? "", `http://localhost:${WEB_PORT}`);
1639
1997
  const src = u.searchParams.get("source") ?? "network";
1640
- const limit = Math.min(500, Number(u.searchParams.get("limit")) || 200);
1998
+ // Clamped below at 1: a negative limit would slice the switchboard replay to nothing. Truncated
1999
+ // first so a fractional limit reaches the device as a whole number it can parse.
2000
+ const limit = Math.max(1, Math.min(500, Math.trunc(Number(u.searchParams.get("limit"))) || 200));
1641
2001
  const kinds = src === "all"
1642
2002
  ? Object.keys(DEVICE_SOURCES)
1643
2003
  : [src].filter((k) => Object.hasOwn(DEVICE_SOURCES, k));
2004
+ const wantsSwitchboard = src === "all" || src === SWITCHBOARD_KIND;
2005
+ // Every leg lands its frames here as it finishes; the reply is whatever has landed when the last
2006
+ // leg settles or the route's deadline fires, whichever is first. A ring leg has only the
2007
+ // socket's inactivity timeout, which measures silence, not progress: the device writes each
2008
+ // body in one go, but a large page over a slow adb pipe keeps bytes trickling and a wedged
2009
+ // tunnel can stall mid-body, and either would otherwise hold the whole reply. The switchboard
2010
+ // leg keeps its own deadline, armed later and for the same span, so the route gives it headroom
2011
+ // to fire first and hand back the sessions that did answer; a slow session route then costs that
2012
+ // session alone, not the replay.
2013
+ const landed = [];
2014
+ const inflight = new Set();
2015
+ let settled = false;
2016
+ const finish = () => {
2017
+ if (settled)
2018
+ return;
2019
+ settled = true;
2020
+ clearTimeout(timer);
2021
+ for (const rq of inflight)
2022
+ rq.destroy();
2023
+ inflight.clear();
2024
+ const merged = landed.flat().sort((a, b) => when(a.event) - when(b.event));
2025
+ sendJson(res, 200, { frames: merged });
2026
+ };
2027
+ // The ceiling for every leg, ring legs included: the switchboard span already sits above the
2028
+ // ring legs' 4 s socket timeout, so one number serves both.
2029
+ const timer = setTimeout(finish, SWITCHBOARD_BACKFILL_DEADLINE_MS + BACKFILL_ROUTE_HEADROOM_MS);
1644
2030
  const fetchKind = (kind) => new Promise((resolve) => {
1645
2031
  const apiPath = `/api/${DEVICE_SOURCES[kind].segment}?limit=${limit}`;
2032
+ // Settles once whichever of end, error, timeout or close comes first; the route's deadline
2033
+ // destroys the request, which raises close with no error, so close settles it too.
2034
+ let legDone = false;
2035
+ const done = (frames) => {
2036
+ if (legDone)
2037
+ return;
2038
+ legDone = true;
2039
+ inflight.delete(rq);
2040
+ landed.push(frames);
2041
+ resolve();
2042
+ };
1646
2043
  const rq = http.request({
1647
2044
  host: RADAR_HOST,
1648
2045
  port: RADAR_PORT,
@@ -1652,32 +2049,31 @@ function handleBackfill(req, res) {
1652
2049
  }, (up) => {
1653
2050
  let b = "";
1654
2051
  up.on("data", (c) => (b += c));
2052
+ up.on("error", () => done([]));
1655
2053
  up.on("end", () => {
1656
2054
  try {
1657
2055
  const j = JSON.parse(b);
1658
2056
  const arr = j[DEVICE_SOURCES[kind].arrayKey] ?? [];
1659
- resolve(arr.map((e) => ({ type: kind, event: e })));
2057
+ done(arr.map((e) => ({ type: kind, event: e })));
1660
2058
  }
1661
2059
  catch {
1662
- resolve([]);
2060
+ done([]);
1663
2061
  }
1664
2062
  });
1665
2063
  });
1666
- rq.on("error", () => resolve([]));
2064
+ inflight.add(rq);
2065
+ rq.on("error", () => done([]));
2066
+ rq.on("close", () => done([]));
1667
2067
  rq.on("timeout", () => {
1668
2068
  rq.destroy();
1669
- resolve([]);
2069
+ done([]);
1670
2070
  });
1671
2071
  rq.end();
1672
2072
  });
1673
- Promise.all(kinds.map(fetchKind))
1674
- .then((lists) => {
1675
- const merged = lists
1676
- .flat()
1677
- .sort((a, b) => (Number(a.event.timestamp) || 0) - (Number(b.event.timestamp) || 0));
1678
- sendJson(res, 200, { frames: merged });
1679
- })
1680
- .catch(() => sendJson(res, 200, { frames: [] }));
2073
+ const legs = kinds.map(fetchKind);
2074
+ if (wantsSwitchboard)
2075
+ legs.push(fetchSwitchboardBackfill(limit).then((frames) => { landed.push(frames); }));
2076
+ Promise.all(legs).then(finish, finish);
1681
2077
  }
1682
2078
  /**
1683
2079
  * Finish a /detail proxy response after an upstream error or timeout. The success