@slack/radar-mcp 1.19.0 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
@@ -706,6 +885,12 @@ export function createServer(onShutdown) {
706
885
  });
707
886
  return;
708
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);
709
894
  const url = req.url ?? "";
710
895
  const urlPath = url.split("?")[0];
711
896
  // Second chokepoint, DEFAULT DENY. A request must prove it came from our own client unless its
@@ -737,12 +922,54 @@ export function createServer(onShutdown) {
737
922
  if ((req.method === "GET" || req.method === "HEAD") && serveStatic(urlPath, res, req.method === "HEAD", Array.isArray(inm) ? inm[0] : inm)) {
738
923
  return;
739
924
  }
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);
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.
746
973
  sendJson(res, 200, loadSpec());
747
974
  return;
748
975
  }
@@ -793,7 +1020,7 @@ export function createServer(onShutdown) {
793
1020
  // Deliberately not awaited; handleEnable answers res itself and never rejects.
794
1021
  // ?auto=1 marks the dashboard's own unattended recovery; see handleEnable's `auto`.
795
1022
  const auto = params.get("auto") === "1";
796
- void handleEnable(res, serial, isAuthoredRequest(req.headers), auto);
1023
+ void handleEnable(res, serial, isAuthoredRequest(req.headers), readTabIdentity(req.headers), auto);
797
1024
  return;
798
1025
  }
799
1026
  if (url === "/stream" && req.method === "GET") {
@@ -974,8 +1201,20 @@ function sendJson(res, status, payload) {
974
1201
  // ERR_HTTP_HEADERS_SENT and crash the whole process. Swallow the duplicate.
975
1202
  if (res.headersSent || res.writableEnded)
976
1203
  return;
977
- res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
978
- 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);
979
1218
  }
980
1219
  function readBody(req) {
981
1220
  return new Promise((resolve) => {
@@ -1018,8 +1257,10 @@ async function handleSetSpec(req, res, authored) {
1018
1257
  // request, so without the gate any page in the user's browser could postpone auto-close
1019
1258
  // forever by pinging this every few minutes. The spec still gets written either way, which
1020
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.
1021
1262
  if (authored)
1022
- markKeepAlive();
1263
+ creditAuthoredWrite(readTabIdentity(req.headers));
1023
1264
  sendJson(res, 200, {
1024
1265
  ok: true,
1025
1266
  url: `http://localhost:${WEB_PORT}`,
@@ -1111,10 +1352,10 @@ async function handleHealth(res) {
1111
1352
  * successful re-arm keeps the dashboard alive (an MCP-driven session can re-enable with no tab
1112
1353
  * open, and that must not let the idle timer fire out from under it).
1113
1354
  *
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
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
1118
1359
  * a real socket to RADAR_HOST:RADAR_PORT, which this function does not touch at all).
1119
1360
  *
1120
1361
  * A failed probe gets guidance, not a bare false: the broadcast landed (or exited 0 with no
@@ -1127,9 +1368,12 @@ async function handleHealth(res) {
1127
1368
  * through the route cannot cover this — handleEnable's device probe fails with no hardware, which
1128
1369
  * short-circuits before the hook is ever consulted, so a route-level test passes either way (a
1129
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.
1130
1374
  */
1131
- export function keepAliveHookFor(authored) {
1132
- return authored ? markKeepAlive : undefined;
1375
+ export function keepAliveHookFor(authored, tab) {
1376
+ return authored ? () => creditAuthoredWrite(tab) : undefined;
1133
1377
  }
1134
1378
  // Reads the dashboard serves to any local caller. Everything NOT matching is treated as
1135
1379
  // state-changing and needs proof it came from our own client (see isOpenToAnyCaller).
@@ -1297,9 +1541,10 @@ processState = "unknown") {
1297
1541
  // human press never joins an unattended flight: the press earns things the timer may not (the
1298
1542
  // screen teardown, adopting swapped hardware), so it waits for the flight to settle and then
1299
1543
  // 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.
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.
1303
1548
  let enableInFlight = null;
1304
1549
  // Test seam: the next runEnable rejects with this error after `delayMs` (long enough for a second
1305
1550
  // request to join the flight), to prove a rejection still answers every request riding the flight
@@ -1309,6 +1554,10 @@ export function _setEnableFaultForTest(err, delayMs = 300) {
1309
1554
  enableFaultForTest = err ? { err, delayMs } : null;
1310
1555
  }
1311
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,
1312
1561
  // An UNATTENDED re-arm (the dashboard's own automatic recovery of a diagnosed-dead session,
1313
1562
  // marked with ?auto=1). See runEnable for what it may and may not do.
1314
1563
  auto = false) {
@@ -1358,7 +1607,7 @@ auto = false) {
1358
1607
  else {
1359
1608
  // .finally with an identity check, so a flight that settles after a successor took the slot
1360
1609
  // never clears the successor.
1361
- p = runEnable(target, authored, auto).finally(() => {
1610
+ p = runEnable(target, authored, auto, tab).finally(() => {
1362
1611
  if (enableInFlight?.p === p)
1363
1612
  enableInFlight = null;
1364
1613
  });
@@ -1377,6 +1626,13 @@ auto = false) {
1377
1626
  body: { enabled: false, error: `Enable failed: ${e.message}. Try again.`, instructs: true },
1378
1627
  };
1379
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);
1380
1636
  sendJson(res, reply.status, reply.body);
1381
1637
  }
1382
1638
  /**
@@ -1394,7 +1650,9 @@ async function runEnable(deviceSerial, authored,
1394
1650
  // a process whose env forbids self-arming is refused before any device work, and an auto
1395
1651
  // attempt onto DIFFERENT hardware than this process last armed is refused before the
1396
1652
  // teardown decision; the same-device auto path takes the detection-only reset.
1397
- auto) {
1653
+ auto,
1654
+ // The tab that started this flight, when one named itself. Only reaches keepAliveHookFor below.
1655
+ tab) {
1398
1656
  if (enableFaultForTest) {
1399
1657
  const fault = enableFaultForTest;
1400
1658
  enableFaultForTest = null;
@@ -1608,7 +1866,7 @@ auto) {
1608
1866
  // patient default, where seconds of ping retries have already elapsed and a real answer
1609
1867
  // beats a fast "unknown".
1610
1868
  return { status: 200, body: {
1611
- ...enableResultBody(enabled, keepAliveHookFor(authored), enabled ? "unknown" : readProcessState(transport, DIAGNOSTIC_PS_TIMEOUT_MS)),
1869
+ ...enableResultBody(enabled, keepAliveHookFor(authored, tab), enabled ? "unknown" : readProcessState(transport, DIAGNOSTIC_PS_TIMEOUT_MS)),
1612
1870
  device_serial: pinnedSerial(),
1613
1871
  } };
1614
1872
  }
@@ -24,6 +24,8 @@ export type Viz = (typeof VIZ)[number];
24
24
  export declare const SERIES_METRICS: readonly ["ratePerSec", "count", "avg", "errorRate"];
25
25
  export type SeriesMetric = (typeof SERIES_METRICS)[number];
26
26
  declare const HIGHLIGHT_OPS: readonly [">", ">=", "<", "<=", "=="];
27
+ export declare const LOG_LEVELS: readonly ["VERBOSE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL"];
28
+ export type LogLevel = (typeof LOG_LEVELS)[number];
27
29
  export type HighlightOp = (typeof HIGHLIGHT_OPS)[number];
28
30
  export interface GraphSeries {
29
31
  label?: string;
@@ -61,6 +63,7 @@ export interface Spec {
61
63
  source?: Source;
62
64
  match?: Record<string, string>;
63
65
  bodyContains?: string;
66
+ minLevel?: LogLevel;
64
67
  viz?: Viz[];
65
68
  rateWindowSec?: number;
66
69
  series?: GraphSeries[];
package/dist/web/spec.js CHANGED
@@ -33,6 +33,9 @@ export const SERIES_METRICS = [
33
33
  "errorRate",
34
34
  ];
35
35
  const HIGHLIGHT_OPS = [">", ">=", "<", "<=", "=="];
36
+ // Logcat priorities, lowest first. `minLevel` on a log-carrying spec keeps rows at that priority
37
+ // or above, and this order is what "or above" means.
38
+ export const LOG_LEVELS = ["VERBOSE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL"];
36
39
  /** The empty dashboard. Rendered until a spec is pushed. */
37
40
  export const BLANK_SPEC = { title: "", blank: true, viz: [] };
38
41
  function isRecord(v) {
@@ -50,6 +53,19 @@ export function coerceSpec(input) {
50
53
  if (!isRecord(input))
51
54
  return BLANK_SPEC;
52
55
  const s = input;
56
+ // Ahead of the browser-source return below, so a lowercase level on those sources is refused
57
+ // for the reason that applies (the source), not for its spelling. VERBOSE is the floor, and the
58
+ // floor is spelled as no field: with the field present it would hide a log row whose priority
59
+ // levelRank cannot place, and the page would show a "level ≥ VERBOSE" chip for what the UI treats
60
+ // as no filter. The UI never sends it (changeLevel drops the field), but the MCP enum offers it,
61
+ // and both wire entry points (/setspec and the SLACK_RADAR_INITIAL_SPEC seed) come through here.
62
+ if (typeof s.minLevel === "string") {
63
+ const up = s.minLevel.toUpperCase();
64
+ if (up === LOG_LEVELS[0])
65
+ delete s.minLevel;
66
+ else
67
+ s.minLevel = up;
68
+ }
53
69
  // The DB, Prefs, and feature-flags browsers have no match/viz/series to repair; leave as-is.
54
70
  if (s.source === "db" || s.source === "prefs" || s.source === "flags")
55
71
  return s;
@@ -100,6 +116,18 @@ export function validateSpec(s) {
100
116
  if (!spec.source || !SOURCES.includes(spec.source)) {
101
117
  return `source must be one of ${SOURCES.join("|")}`;
102
118
  }
119
+ // Checked ahead of the per-source returns below so a browser source cannot carry the field
120
+ // through unexamined. Only log rows have a priority, so accepting it anywhere but log and all
121
+ // would store a filter that can never act, which reads as "the level is set" while changing
122
+ // nothing.
123
+ if (spec.minLevel !== undefined) {
124
+ if (!LOG_LEVELS.includes(spec.minLevel)) {
125
+ return `minLevel must be one of ${LOG_LEVELS.join("|")}`;
126
+ }
127
+ if (spec.source !== "log" && spec.source !== "all") {
128
+ return "minLevel applies to the log and all sources only";
129
+ }
130
+ }
103
131
  // The DB browser is a distinct view: no viz/series/match. Only its optional deep-link
104
132
  // fields are constrained (each must be a string when present).
105
133
  if (spec.source === "db") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slack/radar-mcp",
3
- "version": "1.19.0",
3
+ "version": "1.20.0",
4
4
  "description": "MCP server and web dashboard for debugging Slack on Android and iOS Simulator",
5
5
  "type": "module",
6
6
  "main": "dist/mcp/index.js",