@slack/radar-mcp 1.17.0 → 1.17.1

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.
@@ -62,6 +62,11 @@ const SPEC_PATH = path.join(SPEC_DIR, `web-spec-${WEB_PORT}.json`);
62
62
  // fingerprint every launch for a reason unrelated to the actual spec.
63
63
  const SELF_HEAL_PATH = path.join(SPEC_DIR, "self-heal.json");
64
64
  const transport = new AndroidTransport();
65
+ // The ONE ceiling for every device ping this file makes (boot-arm, /health, /enable all go
66
+ // through pingDevice). A shorter one turns ordinary latency into a false negative: boot would
67
+ // read a live-but-slow session as absent, and /health would flap the connection dot. Observed
68
+ // latency reaches past 2.2 seconds against an unauthorized device, so this must stay above that.
69
+ const PING_PROBE_MS = 2500;
65
70
  // Reassert the shared adb forward before every HTTP-based device read. Mirrors
66
71
  // mcp/index.ts's forwardForRead(): this process's own portForwarded cache cannot see a
67
72
  // repoint made by a SEPARATE process (the MCP server) sharing the same host-global
@@ -354,6 +359,165 @@ export async function shutdownDashboard(server, deps = {}) {
354
359
  fallback = setTimeout(finish, 2000);
355
360
  fallback.unref();
356
361
  }
362
+ /**
363
+ * The ONE device ping every probe site uses: boot-arm's armed check, /health, and /enable's
364
+ * verify step. One function rather than three inline copies so the three-state rules below hold
365
+ * everywhere at once, and so the ceiling cannot be lowered at one site while the others keep the
366
+ * old value. The default ceiling sits inside observed latency: a health read against an
367
+ * unauthorized device has been measured at over 2.2 seconds.
368
+ *
369
+ * The classification rules, each load-bearing:
370
+ * - Anything that ANSWERS is "armed": something we must not clobber. A 200 is Radar; another
371
+ * status still means a live server on the socket, which is not ours to re-arm out from under.
372
+ * - Only a clean REFUSAL is "unarmed": ECONNREFUSED means nothing is listening on the local
373
+ * port at all. Through a built adb forward that hardly ever happens: the HOST adb server
374
+ * accepts every connection first and only then discovers whether the device side exists, so
375
+ * an absent device-side socket presents as a RESET, not a refusal.
376
+ * - A timeout, a reset, or a mid-response error is "unknown": not an answer. A reset in
377
+ * particular is ambiguous by construction here (an absent socket and a misbehaving live
378
+ * session read identically through the forward), so the boot chain resolves it against the
379
+ * device's own socket table instead of guessing at this layer.
380
+ */
381
+ function pingDevice(timeoutMs = PING_PROBE_MS) {
382
+ return new Promise((resolve) => {
383
+ let settled = false;
384
+ const done = (state, status = null, body = "") => {
385
+ if (settled)
386
+ return;
387
+ settled = true;
388
+ resolve({ state, status, body });
389
+ };
390
+ const req = http.request({ host: RADAR_HOST, port: RADAR_PORT, path: "/api/ping", method: "GET", timeout: timeoutMs }, (up) => {
391
+ // The ping body is the device's own small JSON status. Bound the accumulation anyway so a
392
+ // misbehaving local endpoint cannot grow it without limit; a truncated body simply fails
393
+ // the caller's JSON.parse, which every caller treats as "no extra detail".
394
+ const MAX_PING_BODY = 64 * 1024;
395
+ let body = "";
396
+ up.on("data", (c) => {
397
+ if (body.length < MAX_PING_BODY)
398
+ body += c;
399
+ });
400
+ up.on("end", () => done("armed", up.statusCode ?? null, body));
401
+ up.on("error", () => done("unknown"));
402
+ });
403
+ req.on("error", (e) => done(e.code === "ECONNREFUSED" ? "unarmed" : "unknown"));
404
+ req.on("timeout", () => {
405
+ req.destroy();
406
+ done("unknown");
407
+ });
408
+ req.end();
409
+ });
410
+ }
411
+ /**
412
+ * Arm Radar once, at dashboard boot, so a launch against a freshly restarted app does not land on
413
+ * "waiting for device" until the human finds the Reconnect button. Called by bin.ts from the listen
414
+ * callback, for the same reason startAutoCloseSweep is: only the process that actually WON the port
415
+ * may touch the device, so a second launcher that adopts a running dashboard never re-arms someone
416
+ * else's session.
417
+ *
418
+ * The work itself runs OFF the event loop entirely (see armDevice), because an
419
+ * attached-but-unauthorised or locked device can hold a single adb call at its 5 second ceiling,
420
+ * and a chain of them can run 15 seconds or more. A server that cannot answer meanwhile breaks
421
+ * the adopt path this file otherwise protects carefully: a second launcher hits EADDRINUSE,
422
+ * probes the loopback /spec with a 2 second timeout to recognise this dashboard, and declares
423
+ * the port foreign and exits if that probe does not answer.
424
+ *
425
+ * NOT routed through handleEnable, which is written around an HTTP response. Two of the steps it
426
+ * additionally performs really are no-ops in a fresh process (resetState and resetDbState only clear
427
+ * in-process fields that are already at their defaults), but two are NOT, and this is deliberately
428
+ * left as a known gap rather than claimed away: resetScreenState() kills orphaned device-side
429
+ * screenrecord processes left by a crashed prior dashboard, and the switched-device branch
430
+ * (cleanupPulledDatabases + logSession.restart) is gated on a serial inherited from the environment,
431
+ * so a boot carrying a stale ANDROID_SERIAL can legitimately be a switch. Pressing Reconnect still
432
+ * performs both. If a third step is ever needed here, extract the shared core instead of copying it.
433
+ */
434
+ export function armOnBoot() {
435
+ // An agent-spawned dashboard must not reach the device on its own. open_radar_dashboard is exempt
436
+ // from the MCP session gate precisely BECAUSE opening a dashboard could not arm anything without a
437
+ // human pressing Reconnect, and arming here would quietly remove the premise that exemption rests
438
+ // on: an agent call would arm a device and begin logcat capture to disk with no human action, and
439
+ // its child is detached with stdio ignored so even a failure line would reach nobody. A human
440
+ // launch, whether a terminal `slack-radar web` or the dock app, sets no marker and does arm.
441
+ if (process.env.SLACK_RADAR_AGENT_LAUNCH)
442
+ return;
443
+ // Escape hatch, matching this file's other automatic-on-boot behaviours (SLACK_RADAR_NO_OPEN,
444
+ // SLACK_RADAR_NO_AUTO_CLOSE, SLACK_RADAR_NO_FFMPEG). This is the first one that touches the
445
+ // physical device, so it is the one that most deserves an opt-out.
446
+ if (process.env.SLACK_RADAR_NO_ARM)
447
+ return;
448
+ void armDevice();
449
+ }
450
+ /**
451
+ * The deferred body of armOnBoot. Never throws: every call below reports through the transport.
452
+ *
453
+ * Every adb step runs through the transport's *Async methods (promisified execFile), so each adb
454
+ * call lives in its own child process and the event loop stays free WHILE a call is in flight,
455
+ * not merely between calls. The bound this buys: the server can accept and answer at any point
456
+ * in the chain, including the middle of a single wedged 5 second adb call, so a second
457
+ * launcher's 2 second /spec probe is answered no matter how slow the device is. An earlier
458
+ * version ran synchronous transport calls with yields between them, which still left each
459
+ * individual call as an unanswerable window at its own ceiling.
460
+ *
461
+ * A detached child was also considered and rejected, but not for the reason once claimed here
462
+ * (that a child's logcat capture would die with it: the dashboard's Logs tab actually reads
463
+ * logSession, spawned per /stream, and startCapture's file is only read by the MCP side's
464
+ * getRecentLogs and snapshot). The real problem is state: selectDevice pins ANDROID_SERIAL and
465
+ * activate records radarEnabled and the timeout, and a child would set all three in its own
466
+ * process and exit, leaving THIS server unpinned and unaware of what it just armed.
467
+ */
468
+ async function armDevice() {
469
+ // One macrotask before any adb child spawns, so armOnBoot's caller provably returns with zero
470
+ // device work started in its own tick (execFile spawns its child synchronously even though the
471
+ // result is awaited).
472
+ await new Promise((resolve) => setImmediate(resolve));
473
+ // Two DIFFERENT situations return not-ok here and both are deliberately silent: a genuinely
474
+ // ambiguous host (two or more devices, which the header's picker must ask about rather than have
475
+ // answered for the user), and a device list that could not be read at all. The second is a real
476
+ // condition, and it is not left unreported: /_control/devices polls separately and distinguishes
477
+ // adb_error from zero devices, which the header's device chip renders as "device: adb error".
478
+ const selection = await transport.selectDeviceAsync(null);
479
+ if (!selection.ok)
480
+ return;
481
+ // The forward could not be built. Nothing to arm, and the dashboard is still usable for a
482
+ // device plugged in later, but the REASON is printed rather than swallowed: an attached device
483
+ // that is unauthorized or offline fails exactly here, and silence on that path is what left
484
+ // people staring at "waiting for device" with no idea a launch had already tried and why it
485
+ // stopped.
486
+ if (!(await transport.reassertForwardAsync())) {
487
+ const reason = transport.getLastForwardError?.() ?? null;
488
+ // Only when something is on the cable: an empty desk fails the forward too ("no
489
+ // devices/emulators found"), and that is the deliberately quiet case. An attached but
490
+ // unauthorized device also selects nothing, so the gate is the raw listing, which keeps
491
+ // exactly that case loud.
492
+ if (reason && selection.devices.length > 0) {
493
+ console.log(`Radar could not be armed at startup: ${reason}`);
494
+ }
495
+ return;
496
+ }
497
+ // ALREADY ARMED, so leave it alone. This is not just an optimisation. activate()'s own skip guard
498
+ // is per-instance state and this process is brand new, so without this check boot would
499
+ // re-broadcast on every launch -- and the timeout it would send is this fresh instance's own
500
+ // default, which can be SHORTER than one another process explicitly asked for. An MCP session that
501
+ // armed for 30 minutes would have its idle window silently cut to the default by someone merely
502
+ // opening a dashboard to look, with no error surfaced to either side.
503
+ if ((await pingDevice()).state === "armed")
504
+ return;
505
+ // Anything else the ping says is inconclusive HERE, including a reset: the probe travels the
506
+ // adb forward, and the host adb server accepts every connection before discovering whether the
507
+ // device side exists, so an absent socket and a misbehaving live session read identically. The
508
+ // device's own socket table is the authority the forward cannot distort: ABSENT means no server
509
+ // is bound anywhere, so a broadcast cannot take another session's window. Anything else skips,
510
+ // because the cost of guessing wrong is another process's window while the cost of not arming
511
+ // is one press of a button that is already on screen.
512
+ if ((await transport.radarSocketPresentAsync()) !== "absent")
513
+ return;
514
+ await transport.activateAsync(transport.getTimeoutMinutes());
515
+ // A device WAS reachable and the broadcast still failed, which is worth printing. Silence here is
516
+ // what left people staring at "waiting for device" with no idea a launch had already tried.
517
+ const error = transport.getLastActivateError?.() ?? null;
518
+ if (error)
519
+ console.log(`Radar could not be armed at startup: ${error}`);
520
+ }
357
521
  /**
358
522
  * Start the periodic auto-close sweep. Called once by bin.ts AFTER a successful listen bind, not
359
523
  * from createServer, so importing this module (or spinning a throwaway server in a test) never
@@ -461,7 +625,8 @@ export function createServer(onShutdown) {
461
625
  if (tab)
462
626
  touchTab(tab);
463
627
  }
464
- handleHealth(res);
628
+ // Deliberately not awaited; handleHealth answers res itself and never rejects.
629
+ void handleHealth(res);
465
630
  return;
466
631
  }
467
632
  if (urlPath === "/shutdown" && req.method === "POST") {
@@ -470,7 +635,8 @@ export function createServer(onShutdown) {
470
635
  }
471
636
  if (urlPath === "/enable" && req.method === "POST") {
472
637
  const serial = new URL(url, `http://localhost:${WEB_PORT}`).searchParams.get("device_serial");
473
- handleEnable(res, serial, isAuthoredRequest(req.headers));
638
+ // Deliberately not awaited; handleEnable answers res itself and never rejects.
639
+ void handleEnable(res, serial, isAuthoredRequest(req.headers));
474
640
  return;
475
641
  }
476
642
  if (url === "/stream" && req.method === "GET") {
@@ -714,7 +880,7 @@ function handleShutdown(req, res, fire) {
714
880
  * is built. Drives the connection dot even on a blank dashboard. Reuses the same
715
881
  * forward/proxy base as the rest of the server.
716
882
  */
717
- function handleHealth(res) {
883
+ async function handleHealth(res) {
718
884
  // Reassert before reading: see forwardForRead's doc comment. Without this, a foreign
719
885
  // repoint of the shared port (the MCP process switching devices) makes /health probe
720
886
  // the WRONG device while still labeling the reply with THIS process's own (correct)
@@ -723,80 +889,43 @@ function handleHealth(res) {
723
889
  // the cost low on the 2s poll cadence; it only pays for a real rebuild when the shared
724
890
  // port is actually pointed somewhere else.
725
891
  forwardForRead();
726
- // A probe can fire BOTH an "end" and an "error"/"timeout" (partial response then socket
727
- // drop), so guard the response to exactly one write. Without this the second sendJson
728
- // does a second writeHead -> ERR_HTTP_HEADERS_SENT -> uncaught -> the whole server dies.
729
- let replied = false;
892
+ const ping = await pingDevice();
893
+ const ok = ping.state === "armed" && ping.status === 200;
730
894
  // The bound profile, read from the device ping body. This is the TRUTH about which
731
895
  // profile owns the socket (the app that bound first), unlike the host-side activate
732
896
  // guess in getActiveUserId() which can drift. The dashboard shows this so it never
733
897
  // claims a profile you are not actually seeing.
734
- const reply = (device, boundUserId, boundProfile, sources) => {
735
- if (replied)
736
- return;
737
- replied = true;
738
- const selected = transport.getSelectedDevice?.() ?? null;
739
- sendJson(res, 200, {
740
- device,
741
- screen: screenCapabilities(),
742
- boundUserId: boundUserId ?? null,
743
- boundProfile: boundProfile ?? null,
744
- device_serial: selected?.serial ?? null,
745
- device_label: selected?.label ?? null,
746
- // Capture sources the build declares on ping (seam builds only); null on older builds.
747
- sources: sources ?? null,
748
- });
749
- };
750
- const probe = http.request({
751
- host: RADAR_HOST,
752
- port: RADAR_PORT,
753
- path: "/api/ping",
754
- method: "GET",
755
- timeout: 2500,
756
- }, (up) => {
757
- // The ping body is the device's own small JSON status. Bound the accumulation anyway so
758
- // a misbehaving/compromised local endpoint cannot grow it without limit (matches the
759
- // bounded-read posture elsewhere in this file). 64KB is far above any real ping body;
760
- // once tripped we stop appending and parse what we have (a truncated body simply fails
761
- // the JSON.parse below and falls back to no bound profile, which is the safe default).
762
- const MAX_PING_BODY = 64 * 1024;
763
- let body = "";
764
- up.on("data", (c) => {
765
- if (body.length < MAX_PING_BODY)
766
- body += c;
767
- });
768
- up.on("end", () => {
769
- const ok = up.statusCode === 200;
770
- let uid = null;
771
- let profile = null;
772
- let sources = null;
773
- // Only trust the body on a 200. A device 5xx-ing with a stale ping body must NOT
774
- // surface a bound profile while device:false — that would let the dashboard show a
775
- // confident profile label for an unhealthy device.
776
- if (ok) {
777
- try {
778
- const p = JSON.parse(body);
779
- if (p.android_user_id != null)
780
- uid = String(p.android_user_id);
781
- if (typeof p.profile === "string")
782
- profile = p.profile;
783
- if (Array.isArray(p.sources))
784
- sources = p.sources;
785
- }
786
- catch {
787
- // non-JSON / partial body: device is up but we cannot name the profile
788
- }
789
- }
790
- reply(ok, uid, profile, sources);
791
- });
792
- up.on("error", () => reply(false));
793
- });
794
- probe.on("error", () => reply(false));
795
- probe.on("timeout", () => {
796
- probe.destroy();
797
- reply(false);
898
+ let uid = null;
899
+ let profile = null;
900
+ let sources = null;
901
+ // Only trust the body on a healthy 200. A device 5xx-ing with a stale ping body must NOT
902
+ // surface a bound profile while device:false -- that would let the dashboard show a
903
+ // confident profile label for an unhealthy device.
904
+ if (ok) {
905
+ try {
906
+ const p = JSON.parse(ping.body);
907
+ if (p.android_user_id != null)
908
+ uid = String(p.android_user_id);
909
+ if (typeof p.profile === "string")
910
+ profile = p.profile;
911
+ if (Array.isArray(p.sources))
912
+ sources = p.sources;
913
+ }
914
+ catch {
915
+ // non-JSON / partial body: device is up but we cannot name the profile
916
+ }
917
+ }
918
+ const selected = transport.getSelectedDevice?.() ?? null;
919
+ sendJson(res, 200, {
920
+ device: ok,
921
+ screen: screenCapabilities(),
922
+ boundUserId: uid,
923
+ boundProfile: profile,
924
+ device_serial: selected?.serial ?? null,
925
+ device_label: selected?.label ?? null,
926
+ // Capture sources the build declares on ping (seam builds only); null on older builds.
927
+ sources,
798
928
  });
799
- probe.end();
800
929
  }
801
930
  /**
802
931
  * The /enable response body for a completed device probe, plus its one side effect: a
@@ -974,7 +1103,7 @@ processState = "unknown") {
974
1103
  * user never has to drop to a terminal. Delegates entirely to AndroidTransport;
975
1104
  * no adb shelling here.
976
1105
  */
977
- function handleEnable(res, deviceSerial, authored) {
1106
+ async function handleEnable(res, deviceSerial, authored) {
978
1107
  transport.resetState();
979
1108
  // A reconnect may be a different device / re-armed profile, so drop the cached DB user
980
1109
  // set + sqlite path; the next /dbs re-detects the profiles fresh.
@@ -994,6 +1123,14 @@ function handleEnable(res, deviceSerial, authored) {
994
1123
  });
995
1124
  return;
996
1125
  }
1126
+ // The serial pinned at REPLY time, which under an overlapping /enable can differ from the pin
1127
+ // this press made -- and reply time is the correct read: the verify probe rode the forward as
1128
+ // it is NOW, readProcessState reads the same current pin, and the next /health poll reports
1129
+ // this serial, so the reply stays consistent with its own diagnosis and with the poll that
1130
+ // follows. Echoed on every reply past this point so the store can advance its serial baseline
1131
+ // from the reply itself, instead of discovering the pin from a later health poll whose serial
1132
+ // edge would retire the very reason the reply carries.
1133
+ const pinnedSerial = () => transport.getSelectedDevice?.()?.serial ?? null;
997
1134
  resetScreenState(); // re-detect the active display + clear any stale cast on re-arm
998
1135
  // On a switch to a different device, drop this device's pulled DB scratch AND the
999
1136
  // retained logcat capture -- both are per-device state resetDbState()/resetScreenState()
@@ -1024,53 +1161,39 @@ function handleEnable(res, deviceSerial, authored) {
1024
1161
  sendJson(res, 200, {
1025
1162
  enabled: false,
1026
1163
  error: reason ?? "ADB forward failed. Is a device connected?",
1164
+ device_serial: pinnedSerial(),
1027
1165
  });
1028
1166
  return;
1029
1167
  }
1030
- // activate() never throws; a failed broadcast is recorded on the transport.
1031
- // Surfacing it here gives the dashboard user the actual adb error instead of
1032
- // a bare enabled:false after the ping probe times out.
1033
- transport.activate(transport.getTimeoutMinutes());
1168
+ // activateAsync() never throws; a failed broadcast is recorded on the transport.
1169
+ // Surfacing it here gives the dashboard user the actual adb error instead of a bare
1170
+ // enabled:false after the ping probe times out. Async for the same reason as the boot chain:
1171
+ // the broadcast waits for ordered delivery under a 15 second ceiling, and a Reconnect press
1172
+ // must not hold the event loop for it.
1173
+ await transport.activateAsync(transport.getTimeoutMinutes());
1034
1174
  const activateError = transport.getLastActivateError?.() ?? null;
1035
1175
  if (activateError) {
1036
1176
  sendJson(res, 200, {
1037
1177
  enabled: false,
1038
1178
  error: `Broadcast failed: ${activateError}. Is the device connected?`,
1179
+ device_serial: pinnedSerial(),
1039
1180
  });
1040
1181
  return;
1041
1182
  }
1042
- // Verify by pinging the device the same way /health does. Reply exactly once (an "end"
1043
- // and an "error"/"timeout" can both fire) to avoid a double writeHead crashing the server.
1044
- let replied = false;
1045
- const reply = (enabled) => {
1046
- if (replied)
1047
- return;
1048
- replied = true;
1049
- // Probe only on the failure path: a successful enable needs no diagnosis, and the
1050
- // probe is a real adb round trip. Capped short, because by this point the failure is
1051
- // already established and the user is watching a request that has stalled their SSE
1052
- // tabs; an explanation must not cost more than the operation it explains. The MCP path
1053
- // keeps the patient default, where seconds of ping retries have already elapsed and a
1054
- // real answer beats a fast "unknown".
1055
- sendJson(res, 200, enableResultBody(enabled, keepAliveHookFor(authored), enabled ? "unknown" : readProcessState(transport, DIAGNOSTIC_PS_TIMEOUT_MS)));
1056
- };
1057
- const probe = http.request({
1058
- host: RADAR_HOST,
1059
- port: RADAR_PORT,
1060
- path: "/api/ping",
1061
- method: "GET",
1062
- timeout: 2500,
1063
- }, (up) => {
1064
- up.resume();
1065
- up.on("end", () => reply(up.statusCode === 200));
1066
- up.on("error", () => reply(false));
1067
- });
1068
- probe.on("error", () => reply(false));
1069
- probe.on("timeout", () => {
1070
- probe.destroy();
1071
- reply(false);
1183
+ // Verify by pinging the device the same way /health does (the shared pingDevice, so the
1184
+ // ceiling and the three-state rules cannot drift from the other probe sites).
1185
+ const ping = await pingDevice();
1186
+ const enabled = ping.state === "armed" && ping.status === 200;
1187
+ // Probe the process state only on the failure path: a successful enable needs no diagnosis,
1188
+ // and the probe is a real adb round trip. Capped short, because by this point the failure is
1189
+ // already established and the user is watching a request that has stalled their SSE tabs; an
1190
+ // explanation must not cost more than the operation it explains. The MCP path keeps the
1191
+ // patient default, where seconds of ping retries have already elapsed and a real answer
1192
+ // beats a fast "unknown".
1193
+ sendJson(res, 200, {
1194
+ ...enableResultBody(enabled, keepAliveHookFor(authored), enabled ? "unknown" : readProcessState(transport, DIAGNOSTIC_PS_TIMEOUT_MS)),
1195
+ device_serial: pinnedSerial(),
1072
1196
  });
1073
- probe.end();
1074
1197
  }
1075
1198
  // The device-buffered source kinds, in one table so a new source is one row here: the
1076
1199
  // device API route segment (clog and trace pluralize; the rest match the kind name) and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slack/radar-mcp",
3
- "version": "1.17.0",
3
+ "version": "1.17.1",
4
4
  "description": "MCP server and web dashboard for on-device debugging of the Slack Android app via ADB",
5
5
  "type": "module",
6
6
  "main": "dist/mcp/index.js",