@slack/radar-mcp 1.14.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.
Files changed (49) hide show
  1. package/README.md +15 -3
  2. package/dist/mcp/db-tools.js +23 -0
  3. package/dist/mcp/dispatch.d.ts +4 -0
  4. package/dist/mcp/dispatch.js +26 -0
  5. package/dist/mcp/index.js +105 -37
  6. package/dist/mcp/platform-detect.d.ts +110 -0
  7. package/dist/mcp/platform-detect.js +246 -0
  8. package/dist/mcp/prefs-tools.d.ts +4 -3
  9. package/dist/mcp/prefs-tools.js +26 -3
  10. package/dist/mcp/session-enable.js +19 -1
  11. package/dist/mcp/snapshot.js +4 -1
  12. package/dist/mcp/sources-gate.js +6 -3
  13. package/dist/mcp/tools.d.ts +11 -0
  14. package/dist/mcp/tools.js +38 -0
  15. package/dist/mcp/web-child-env.d.ts +1 -0
  16. package/dist/mcp/web-child-env.js +32 -0
  17. package/dist/shared/android.d.ts +89 -1
  18. package/dist/shared/android.js +352 -78
  19. package/dist/shared/constants.d.ts +25 -1
  20. package/dist/shared/constants.js +27 -1
  21. package/dist/shared/db.js +11 -2
  22. package/dist/shared/debug-log.js +6 -1
  23. package/dist/shared/enable-diagnosis.d.ts +28 -0
  24. package/dist/shared/enable-diagnosis.js +41 -0
  25. package/dist/shared/prefs.d.ts +0 -5
  26. package/dist/shared/prefs.js +6 -2
  27. package/dist/shared/screen.d.ts +46 -9
  28. package/dist/shared/screen.js +74 -11
  29. package/dist/shared/transport.d.ts +62 -5
  30. package/dist/shared/webapp.d.ts +50 -0
  31. package/dist/shared/webapp.js +65 -0
  32. package/dist/web/bin.js +5 -1
  33. package/dist/web/install-app.d.ts +87 -0
  34. package/dist/web/install-app.js +703 -0
  35. package/dist/web/macapp/RadarApp.swift +466 -0
  36. package/dist/web/public/icons/radar-1024.png +0 -0
  37. package/dist/web/public/icons/radar.svg +40 -0
  38. package/dist/web/public/index.html +41 -1
  39. package/dist/web/public/next/app.js +19 -4
  40. package/dist/web/public/next/db.js +145 -5
  41. package/dist/web/public/next/feed.js +18 -0
  42. package/dist/web/public/next/hooks.js +10 -1
  43. package/dist/web/public/next/registry.js +18 -10
  44. package/dist/web/public/next/screen.js +147 -43
  45. package/dist/web/public/next/store.js +393 -51
  46. package/dist/web/public/next/toast.js +134 -0
  47. package/dist/web/server.d.ts +26 -1
  48. package/dist/web/server.js +341 -113
  49. package/package.json +2 -2
@@ -8,14 +8,22 @@ import { AndroidTransport, resolveAdbPath } from "../shared/android.js";
8
8
  import { planReconnect } from "../shared/stream.js";
9
9
  import { RADAR_HOST, RADAR_PORT, RADAR_VERSION, WEB_PORT_DEFAULT } from "../shared/constants.js";
10
10
  import { friendlyFeatureFlagError } from "../shared/feature-flags.js";
11
+ import { deviceServerSilentError, readProcessState, } from "../shared/enable-diagnosis.js";
11
12
  import { cleanupPulledDatabases, initializeDatabasePath, listDatabases, pullDatabase, pulledSize, queryDatabase, resetDbState, availableUsers, } from "../shared/db.js";
12
13
  import { listPrefsFiles, readPrefsFile, parsePrefsXml, searchPrefs, } from "../shared/prefs.js";
13
14
  import { LogSession } from "./log-session.js";
14
15
  import { BLANK_SPEC, coerceSpec, validateSpec } from "./spec.js";
15
- import { screenCapabilities, refreshScreenCapabilities, grantScreenConsent, hasScreenConsent, detectDisplay, displayNote, captureScreenshot, startLive, addViewer, removeViewer, reapLiveIfIdle, primeIfNeeded, startRecording, stopRecording, getLive, recordingPath, resetScreenState, registerScreenCleanup, resolveFfmpeg, ffmpegInstallHint, SCREEN_BOUNDARY, } from "../shared/screen.js";
16
+ import { screenCapabilities, refreshScreenCapabilities, grantScreenConsent, hasScreenConsent, detectDisplay, displayNote, captureScreenshot, startLive, addViewer, removeViewer, reapLiveIfIdle, primeIfNeeded, startRecording, stopRecording, getLive, capturePath, saveScreenshot, screenshotSaveErrorMessage, resetScreenState, registerScreenCleanup, resolveFfmpeg, ffmpegInstallHint, SCREEN_BOUNDARY, } from "../shared/screen.js";
16
17
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
17
18
  const WEB_PORT = Number(process.env.SLACK_RADAR_WEB_PORT ?? WEB_PORT_DEFAULT);
18
19
  const INDEX_PATH = path.join(__dirname, "public", "index.html");
20
+ /**
21
+ * Ceiling for the diagnostic `ps` probe on the dashboard's failed-enable path. Deliberately
22
+ * shorter than the transport's default: /enable has already spent its own ping timeout
23
+ * proving the device server is unreachable, and this request blocks the dashboard's SSE
24
+ * tabs while it runs, so a fast "unknown" beats a slow confirmed answer here.
25
+ */
26
+ const DIAGNOSTIC_PS_TIMEOUT_MS = 1500;
19
27
  // Backpressure ceiling for an SSE connection's unwritten log frames. If a
20
28
  // client's socket buffer is already this deep (slow/backgrounded tab), new log
21
29
  // frames are dropped for that connection rather than queued without bound. ~4 MB
@@ -47,7 +55,18 @@ export function shouldDropLogFrame(replay, writableLength, cap = MAX_SSE_WRITABL
47
55
  // Each server start resets its own file to blank.
48
56
  const SPEC_DIR = path.join(os.homedir(), ".slack-radar");
49
57
  const SPEC_PATH = path.join(SPEC_DIR, `web-spec-${WEB_PORT}.json`);
58
+ // install-app.ts's runSelfHealCheck() writes this on every dock launch, regardless of port -- it
59
+ // is a per-machine install check, not per-dashboard-instance. A dedicated route rather than a
60
+ // field on /spec's body: /spec's JSON is a change-detection fingerprint the client diffs
61
+ // (JSON.stringify of the body) on every poll, and adding fields here would perturb that
62
+ // fingerprint every launch for a reason unrelated to the actual spec.
63
+ const SELF_HEAL_PATH = path.join(SPEC_DIR, "self-heal.json");
50
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;
51
70
  // Reassert the shared adb forward before every HTTP-based device read. Mirrors
52
71
  // mcp/index.ts's forwardForRead(): this process's own portForwarded cache cannot see a
53
72
  // repoint made by a SEPARATE process (the MCP server) sharing the same host-global
@@ -95,6 +114,16 @@ function loadSpec() {
95
114
  return BLANK_SPEC;
96
115
  }
97
116
  }
117
+ // {} (never missing/malformed) is a normal "never checked yet" state, not an error: a fresh
118
+ // install with no self-heal.json yet must not read as a failure.
119
+ function loadSelfHeal() {
120
+ try {
121
+ return JSON.parse(fs.readFileSync(SELF_HEAL_PATH, "utf8"));
122
+ }
123
+ catch {
124
+ return {};
125
+ }
126
+ }
98
127
  // Start every run from a clean slate so a refresh/restart opens blank — UNLESS the
99
128
  // process was spawned with an initial spec (SLACK_RADAR_INITIAL_SPEC). The MCP
100
129
  // open_radar_dashboard handler sets that env on a cold spawn so the spec file is
@@ -330,6 +359,165 @@ export async function shutdownDashboard(server, deps = {}) {
330
359
  fallback = setTimeout(finish, 2000);
331
360
  fallback.unref();
332
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
+ }
333
521
  /**
334
522
  * Start the periodic auto-close sweep. Called once by bin.ts AFTER a successful listen bind, not
335
523
  * from createServer, so importing this module (or spinning a throwaway server in a test) never
@@ -408,6 +596,10 @@ export function createServer(onShutdown) {
408
596
  sendJson(res, 200, loadSpec());
409
597
  return;
410
598
  }
599
+ if (url === "/self-heal" && req.method === "GET") {
600
+ sendJson(res, 200, loadSelfHeal());
601
+ return;
602
+ }
411
603
  if (url === "/setspec" && req.method === "POST") {
412
604
  handleSetSpec(req, res, isAuthoredRequest(req.headers));
413
605
  return;
@@ -433,7 +625,8 @@ export function createServer(onShutdown) {
433
625
  if (tab)
434
626
  touchTab(tab);
435
627
  }
436
- handleHealth(res);
628
+ // Deliberately not awaited; handleHealth answers res itself and never rejects.
629
+ void handleHealth(res);
437
630
  return;
438
631
  }
439
632
  if (urlPath === "/shutdown" && req.method === "POST") {
@@ -442,7 +635,8 @@ export function createServer(onShutdown) {
442
635
  }
443
636
  if (urlPath === "/enable" && req.method === "POST") {
444
637
  const serial = new URL(url, `http://localhost:${WEB_PORT}`).searchParams.get("device_serial");
445
- 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));
446
640
  return;
447
641
  }
448
642
  if (url === "/stream" && req.method === "GET") {
@@ -686,7 +880,7 @@ function handleShutdown(req, res, fire) {
686
880
  * is built. Drives the connection dot even on a blank dashboard. Reuses the same
687
881
  * forward/proxy base as the rest of the server.
688
882
  */
689
- function handleHealth(res) {
883
+ async function handleHealth(res) {
690
884
  // Reassert before reading: see forwardForRead's doc comment. Without this, a foreign
691
885
  // repoint of the shared port (the MCP process switching devices) makes /health probe
692
886
  // the WRONG device while still labeling the reply with THIS process's own (correct)
@@ -695,80 +889,43 @@ function handleHealth(res) {
695
889
  // the cost low on the 2s poll cadence; it only pays for a real rebuild when the shared
696
890
  // port is actually pointed somewhere else.
697
891
  forwardForRead();
698
- // A probe can fire BOTH an "end" and an "error"/"timeout" (partial response then socket
699
- // drop), so guard the response to exactly one write. Without this the second sendJson
700
- // does a second writeHead -> ERR_HTTP_HEADERS_SENT -> uncaught -> the whole server dies.
701
- let replied = false;
892
+ const ping = await pingDevice();
893
+ const ok = ping.state === "armed" && ping.status === 200;
702
894
  // The bound profile, read from the device ping body. This is the TRUTH about which
703
895
  // profile owns the socket (the app that bound first), unlike the host-side activate
704
896
  // guess in getActiveUserId() which can drift. The dashboard shows this so it never
705
897
  // claims a profile you are not actually seeing.
706
- const reply = (device, boundUserId, boundProfile, sources) => {
707
- if (replied)
708
- return;
709
- replied = true;
710
- const selected = transport.getSelectedDevice?.() ?? null;
711
- sendJson(res, 200, {
712
- device,
713
- screen: screenCapabilities(),
714
- boundUserId: boundUserId ?? null,
715
- boundProfile: boundProfile ?? null,
716
- device_serial: selected?.serial ?? null,
717
- device_label: selected?.label ?? null,
718
- // Capture sources the build declares on ping (seam builds only); null on older builds.
719
- sources: sources ?? null,
720
- });
721
- };
722
- const probe = http.request({
723
- host: RADAR_HOST,
724
- port: RADAR_PORT,
725
- path: "/api/ping",
726
- method: "GET",
727
- timeout: 2500,
728
- }, (up) => {
729
- // The ping body is the device's own small JSON status. Bound the accumulation anyway so
730
- // a misbehaving/compromised local endpoint cannot grow it without limit (matches the
731
- // bounded-read posture elsewhere in this file). 64KB is far above any real ping body;
732
- // once tripped we stop appending and parse what we have (a truncated body simply fails
733
- // the JSON.parse below and falls back to no bound profile, which is the safe default).
734
- const MAX_PING_BODY = 64 * 1024;
735
- let body = "";
736
- up.on("data", (c) => {
737
- if (body.length < MAX_PING_BODY)
738
- body += c;
739
- });
740
- up.on("end", () => {
741
- const ok = up.statusCode === 200;
742
- let uid = null;
743
- let profile = null;
744
- let sources = null;
745
- // Only trust the body on a 200. A device 5xx-ing with a stale ping body must NOT
746
- // surface a bound profile while device:false — that would let the dashboard show a
747
- // confident profile label for an unhealthy device.
748
- if (ok) {
749
- try {
750
- const p = JSON.parse(body);
751
- if (p.android_user_id != null)
752
- uid = String(p.android_user_id);
753
- if (typeof p.profile === "string")
754
- profile = p.profile;
755
- if (Array.isArray(p.sources))
756
- sources = p.sources;
757
- }
758
- catch {
759
- // non-JSON / partial body: device is up but we cannot name the profile
760
- }
761
- }
762
- reply(ok, uid, profile, sources);
763
- });
764
- up.on("error", () => reply(false));
765
- });
766
- probe.on("error", () => reply(false));
767
- probe.on("timeout", () => {
768
- probe.destroy();
769
- 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,
770
928
  });
771
- probe.end();
772
929
  }
773
930
  /**
774
931
  * The /enable response body for a completed device probe, plus its one side effect: a
@@ -807,6 +964,7 @@ const READ_ONLY_EXACT = new Set([
807
964
  "/index.html",
808
965
  "/health",
809
966
  "/spec",
967
+ "/self-heal",
810
968
  "/stream", // EventSource cannot set headers, so this must stay open
811
969
  "/backfill",
812
970
  "/detail",
@@ -929,15 +1087,15 @@ export function isLocalHostHeader(host, allowedHosts = process.env.SLACK_RADAR_A
929
1087
  }
930
1088
  return false;
931
1089
  }
932
- export function enableResultBody(enabled, onEnabled) {
1090
+ export function enableResultBody(enabled, onEnabled,
1091
+ // Defaults to "unknown" so a caller that cannot probe keeps the generic message,
1092
+ // which is also what every pre-existing two-argument call site gets.
1093
+ processState = "unknown") {
933
1094
  if (enabled) {
934
1095
  onEnabled?.();
935
1096
  return { enabled };
936
1097
  }
937
- return {
938
- enabled,
939
- error: "Radar broadcast sent but the device server did not respond. Is a debug build with the slack-radar modules running on the active profile?",
940
- };
1098
+ return { enabled, error: deviceServerSilentError(processState) };
941
1099
  }
942
1100
  /**
943
1101
  * Re-arm Radar from the dashboard. Mirrors the recovery sequence: reset cached
@@ -945,7 +1103,7 @@ export function enableResultBody(enabled, onEnabled) {
945
1103
  * user never has to drop to a terminal. Delegates entirely to AndroidTransport;
946
1104
  * no adb shelling here.
947
1105
  */
948
- function handleEnable(res, deviceSerial, authored) {
1106
+ async function handleEnable(res, deviceSerial, authored) {
949
1107
  transport.resetState();
950
1108
  // A reconnect may be a different device / re-armed profile, so drop the cached DB user
951
1109
  // set + sqlite path; the next /dbs re-detects the profiles fresh.
@@ -965,6 +1123,14 @@ function handleEnable(res, deviceSerial, authored) {
965
1123
  });
966
1124
  return;
967
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;
968
1134
  resetScreenState(); // re-detect the active display + clear any stale cast on re-arm
969
1135
  // On a switch to a different device, drop this device's pulled DB scratch AND the
970
1136
  // retained logcat capture -- both are per-device state resetDbState()/resetScreenState()
@@ -995,47 +1161,39 @@ function handleEnable(res, deviceSerial, authored) {
995
1161
  sendJson(res, 200, {
996
1162
  enabled: false,
997
1163
  error: reason ?? "ADB forward failed. Is a device connected?",
1164
+ device_serial: pinnedSerial(),
998
1165
  });
999
1166
  return;
1000
1167
  }
1001
- // activate() never throws; a failed broadcast is recorded on the transport.
1002
- // Surfacing it here gives the dashboard user the actual adb error instead of
1003
- // a bare enabled:false after the ping probe times out.
1004
- 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());
1005
1174
  const activateError = transport.getLastActivateError?.() ?? null;
1006
1175
  if (activateError) {
1007
1176
  sendJson(res, 200, {
1008
1177
  enabled: false,
1009
1178
  error: `Broadcast failed: ${activateError}. Is the device connected?`,
1179
+ device_serial: pinnedSerial(),
1010
1180
  });
1011
1181
  return;
1012
1182
  }
1013
- // Verify by pinging the device the same way /health does. Reply exactly once (an "end"
1014
- // and an "error"/"timeout" can both fire) to avoid a double writeHead crashing the server.
1015
- let replied = false;
1016
- const reply = (enabled) => {
1017
- if (replied)
1018
- return;
1019
- replied = true;
1020
- sendJson(res, 200, enableResultBody(enabled, keepAliveHookFor(authored)));
1021
- };
1022
- const probe = http.request({
1023
- host: RADAR_HOST,
1024
- port: RADAR_PORT,
1025
- path: "/api/ping",
1026
- method: "GET",
1027
- timeout: 2500,
1028
- }, (up) => {
1029
- up.resume();
1030
- up.on("end", () => reply(up.statusCode === 200));
1031
- up.on("error", () => reply(false));
1032
- });
1033
- probe.on("error", () => reply(false));
1034
- probe.on("timeout", () => {
1035
- probe.destroy();
1036
- 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(),
1037
1196
  });
1038
- probe.end();
1039
1197
  }
1040
1198
  // The device-buffered source kinds, in one table so a new source is one row here: the
1041
1199
  // device API route segment (clog and trace pluralize; the rest match the kind name) and
@@ -1393,9 +1551,10 @@ async function handlePrefsSearch(req, res) {
1393
1551
  * /screen/caps capabilities (ffmpeg/scrcpy present, install hint, consent state)
1394
1552
  * /screen/consent POST: grant consent for this server process
1395
1553
  * /screen/shot full-resolution PNG screenshot (pure screencap; works without ffmpeg)
1554
+ * /screen/shot/save capture a screenshot to disk and report the outcome (two-phase)
1396
1555
  * /screen/stream multipart/x-mixed-replace MJPEG live cast (needs ffmpeg + consent)
1397
1556
  * /screen/record/start|stop record the live cast to mp4 (needs ffmpeg + consent)
1398
- * /screen/download download a finished recording
1557
+ * /screen/download download a finished recording or screenshot
1399
1558
  * /screen/redetect re-detect the active display
1400
1559
  */
1401
1560
  function handleScreen(req, res) {
@@ -1431,7 +1590,55 @@ function handleScreen(req, res) {
1431
1590
  sendJson(res, 200, { consent: true });
1432
1591
  return;
1433
1592
  }
1593
+ // Screenshot, two-phase: capture to disk and report the outcome as JSON, exactly like
1594
+ // /screen/record/stop. The dashboard uses this rather than GET /screen/shot because a
1595
+ // Content-Disposition response is invisible to the page that asked for it -- it cannot
1596
+ // tell a saved PNG from a 403 or a 502, so it used to say "screenshot saved" either way.
1597
+ // The client downloads the file it names in a second step, once it knows there is one.
1598
+ if (url === "/screen/shot/save" && req.method === "POST") {
1599
+ if (!hasScreenConsent()) {
1600
+ sendJson(res, 403, { ok: false, error: "screen consent required" });
1601
+ return;
1602
+ }
1603
+ void (async () => {
1604
+ // Same guard as the /screen/caps refresh branch above, and for the same reason: an escaping
1605
+ // rejection would leave this request hanging until the client times out, and a route whose
1606
+ // whole purpose is reporting the outcome must not have a silent way to report nothing.
1607
+ try {
1608
+ await detectDisplay();
1609
+ const shot = await saveScreenshot();
1610
+ if (!shot.ok) {
1611
+ // Name the half that failed. A write failure is a host problem (no space, a dir mode the
1612
+ // process cannot write); calling it a capture failure would send the user to check a
1613
+ // phone that answered perfectly well.
1614
+ sendJson(res, 502, { ok: false, error: screenshotSaveErrorMessage(shot) });
1615
+ return;
1616
+ }
1617
+ const p = shot.path;
1618
+ let sizeBytes = 0;
1619
+ try {
1620
+ sizeBytes = fs.statSync(p).size;
1621
+ }
1622
+ catch {
1623
+ sizeBytes = 0;
1624
+ }
1625
+ const file = path.basename(p);
1626
+ sendJson(res, 200, {
1627
+ ok: true,
1628
+ file,
1629
+ sizeBytes,
1630
+ download: "/screen/download?f=" + encodeURIComponent(file),
1631
+ });
1632
+ }
1633
+ catch (e) {
1634
+ sendJson(res, 502, { ok: false, error: "screenshot failed: " + e.message });
1635
+ }
1636
+ })();
1637
+ return;
1638
+ }
1434
1639
  // Screenshot: pure screencap, no ffmpeg. Still consent-gated — it is the live screen.
1640
+ // Kept as a direct PNG for anyone hitting the URL by hand; the dashboard uses the
1641
+ // two-phase route above so it can actually see whether the capture worked.
1435
1642
  if (url.startsWith("/screen/shot")) {
1436
1643
  if (!hasScreenConsent()) {
1437
1644
  sendJson(res, 403, { error: "screen consent required" });
@@ -1538,24 +1745,45 @@ function handleScreen(req, res) {
1538
1745
  return;
1539
1746
  }
1540
1747
  if (url.startsWith("/screen/download")) {
1541
- // A recording is device-screen content, so gate download on consent too — a fresh
1542
- // (unconsented) process must not serve a prior session's screen recording.
1748
+ // A capture is device-screen content, so gate download on consent too — a fresh
1749
+ // (unconsented) process must not serve a prior session's screen recording or screenshot.
1543
1750
  if (!hasScreenConsent()) {
1544
1751
  sendJson(res, 403, { error: "screen consent required" });
1545
1752
  return;
1546
1753
  }
1547
1754
  const f = new URL(url, `http://localhost:${WEB_PORT}`).searchParams.get("f") ?? "";
1548
- const p = recordingPath(f);
1755
+ const p = capturePath(f);
1549
1756
  if (!p) {
1550
1757
  res.writeHead(404);
1551
1758
  res.end("Not found");
1552
1759
  return;
1553
1760
  }
1554
1761
  res.writeHead(200, {
1555
- "Content-Type": "video/mp4",
1762
+ // capturePath admits exactly two extensions, so the type follows from the name. It used to
1763
+ // be a hardcoded video/mp4, which served a screenshot as an mp4 once this route started
1764
+ // carrying them.
1765
+ "Content-Type": p.endsWith(".png") ? "image/png" : "video/mp4",
1556
1766
  "Content-Disposition": `attachment; filename="${path.basename(p)}"`,
1557
1767
  });
1558
1768
  fs.createReadStream(p).pipe(res);
1769
+ // Drop the server-side copy once it has been handed over. A capture is a full frame of
1770
+ // whatever is on the phone, and the download is the point of making it, so keeping it after
1771
+ // delivery just leaves device-screen content sitting in the tmp dir for the rest of the
1772
+ // session -- cleanupRecordings only runs on re-enable and exit. The user's own copy is
1773
+ // untouched, and reveal in the packaged app points at that copy in ~/Downloads, not at this
1774
+ // one. Unlinking a file mid-read is safe, this stream keeps its descriptor.
1775
+ //
1776
+ // Hung off "close" rather than "finish" so an ABORTED transfer drops the file too. Nothing
1777
+ // retries a download, so keeping it after an abort just leaves a full frame of the device
1778
+ // screen in the tmp dir until re-enable or exit, which is the leftover this removes.
1779
+ res.on("close", () => {
1780
+ try {
1781
+ fs.unlinkSync(p);
1782
+ }
1783
+ catch {
1784
+ // Already gone, or a reset cleaned the dir first. Nothing to report either way.
1785
+ }
1786
+ });
1559
1787
  return;
1560
1788
  }
1561
1789
  if (url === "/screen/redetect") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slack/radar-mcp",
3
- "version": "1.14.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",
@@ -23,7 +23,7 @@
23
23
  "start:web": "node dist/web/bin.js",
24
24
  "watch": "tsc --watch",
25
25
  "test": "npm run build && node tests/run.mjs",
26
- "test:tap": "npm run build && node --test --test-force-exit tests/*.test.mjs",
26
+ "test:tap": "npm run build && node --test tests/*.test.mjs",
27
27
  "test:smoke": "npm run build && bash tests/smoke.sh",
28
28
  "test:all": "npm run test && npm run test:smoke",
29
29
  "prepare": "npm run build"