@slack/radar-mcp 1.17.0 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +24 -7
  2. package/dist/mcp/flags-tools.d.ts +14 -9
  3. package/dist/mcp/flags-tools.js +70 -20
  4. package/dist/mcp/index.js +17 -10
  5. package/dist/mcp/platform-detect.d.ts +2 -0
  6. package/dist/mcp/platform-detect.js +2 -0
  7. package/dist/mcp/tools.js +4 -3
  8. package/dist/mcp/web-child-env.d.ts +1 -0
  9. package/dist/mcp/web-child-env.js +32 -0
  10. package/dist/shared/android-dashboard-screen.d.ts +15 -0
  11. package/dist/shared/android-dashboard-screen.js +48 -0
  12. package/dist/shared/android.d.ts +50 -0
  13. package/dist/shared/android.js +248 -35
  14. package/dist/shared/dashboard-screen.d.ts +35 -0
  15. package/dist/shared/dashboard-screen.js +12 -0
  16. package/dist/shared/ios-dashboard-screen.d.ts +32 -0
  17. package/dist/shared/ios-dashboard-screen.js +266 -0
  18. package/dist/shared/ios.d.ts +72 -0
  19. package/dist/shared/ios.js +313 -0
  20. package/dist/shared/platform.d.ts +3 -0
  21. package/dist/shared/platform.js +16 -0
  22. package/dist/shared/screen-artifacts.d.ts +10 -0
  23. package/dist/shared/screen-artifacts.js +57 -0
  24. package/dist/shared/screen.d.ts +20 -5
  25. package/dist/shared/screen.js +35 -39
  26. package/dist/shared/transport.d.ts +38 -0
  27. package/dist/shared/webapp.d.ts +1 -0
  28. package/dist/shared/webapp.js +2 -0
  29. package/dist/web/bin.js +5 -1
  30. package/dist/web/public/index.html +51 -11
  31. package/dist/web/public/next/app.js +16 -4
  32. package/dist/web/public/next/db.js +292 -39
  33. package/dist/web/public/next/flags.js +306 -48
  34. package/dist/web/public/next/registry.js +18 -10
  35. package/dist/web/public/next/screen.js +76 -11
  36. package/dist/web/public/next/store.js +280 -36
  37. package/dist/web/server.d.ts +26 -3
  38. package/dist/web/server.js +397 -179
  39. package/package.json +3 -2
@@ -4,8 +4,10 @@ import os from "os";
4
4
  import path from "path";
5
5
  import { spawn } from "child_process";
6
6
  import { fileURLToPath } from "url";
7
- import { AndroidTransport, resolveAdbPath } from "../shared/android.js";
7
+ import { resolveAdbPath } from "../shared/android.js";
8
+ import { createTransport } from "../shared/platform.js";
8
9
  import { planReconnect } from "../shared/stream.js";
10
+ import { createDashboardScreenController, } from "../shared/dashboard-screen.js";
9
11
  import { RADAR_HOST, RADAR_PORT, RADAR_VERSION, WEB_PORT_DEFAULT } from "../shared/constants.js";
10
12
  import { friendlyFeatureFlagError } from "../shared/feature-flags.js";
11
13
  import { deviceServerSilentError, readProcessState, } from "../shared/enable-diagnosis.js";
@@ -13,7 +15,7 @@ import { cleanupPulledDatabases, initializeDatabasePath, listDatabases, pullData
13
15
  import { listPrefsFiles, readPrefsFile, parsePrefsXml, searchPrefs, } from "../shared/prefs.js";
14
16
  import { LogSession } from "./log-session.js";
15
17
  import { BLANK_SPEC, coerceSpec, validateSpec } from "./spec.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";
18
+ import { grantScreenConsent, hasScreenConsent, detectDisplay, startLive, addViewer, removeViewer, reapLiveIfIdle, primeIfNeeded, capturePath, ffmpegInstallHint, SCREEN_BOUNDARY, } from "../shared/screen.js";
17
19
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
18
20
  const WEB_PORT = Number(process.env.SLACK_RADAR_WEB_PORT ?? WEB_PORT_DEFAULT);
19
21
  const INDEX_PATH = path.join(__dirname, "public", "index.html");
@@ -61,7 +63,20 @@ const SPEC_PATH = path.join(SPEC_DIR, `web-spec-${WEB_PORT}.json`);
61
63
  // (JSON.stringify of the body) on every poll, and adding fields here would perturb that
62
64
  // fingerprint every launch for a reason unrelated to the actual spec.
63
65
  const SELF_HEAL_PATH = path.join(SPEC_DIR, "self-heal.json");
64
- const transport = new AndroidTransport();
66
+ const transport = createTransport();
67
+ const dashboardScreen = createDashboardScreenController(transport);
68
+ // The serial THIS route last armed, and whether it has already done a full screen teardown.
69
+ // Keyed to what this handler itself armed rather than `selection.switched`, so the decision cannot
70
+ // be perturbed by anything that clears ANDROID_SERIAL or by a reconcile change. The two also
71
+ // DIFFER on a null pin: `switched` is absent when nothing is attached, while this keeps the last
72
+ // real arm across an empty-device enable, which turns out to be the interesting case.
73
+ let screenResetThisProcess = false;
74
+ let lastArmedSerial = null;
75
+ // The ONE ceiling for every device ping this file makes (boot-arm, /health, /enable all go
76
+ // through pingDevice). A shorter one turns ordinary latency into a false negative: boot would
77
+ // read a live-but-slow session as absent, and /health would flap the connection dot. Observed
78
+ // latency reaches past 2.2 seconds against an unauthorized device, so this must stay above that.
79
+ const PING_PROBE_MS = 2500;
65
80
  // Reassert the shared adb forward before every HTTP-based device read. Mirrors
66
81
  // mcp/index.ts's forwardForRead(): this process's own portForwarded cache cannot see a
67
82
  // repoint made by a SEPARATE process (the MCP server) sharing the same host-global
@@ -77,12 +92,15 @@ function forwardForRead() {
77
92
  // log history instead of only lines that arrive after the reconnect, matching
78
93
  // how Android Studio retains logcat for the whole session. Spawn + parse are
79
94
  // injected so the capture logic is unit-testable without a real `adb logcat`.
80
- const logSession = new LogSession(() => spawn(resolveAdbPath() ?? "adb", ["logcat", "-v", "threadtime", "-T", "1"], {
81
- stdio: ["ignore", "pipe", "ignore"],
82
- }), (line) => parseLogcat(line));
95
+ // Only spawn when the transport supports local device access (i.e. Android).
96
+ const logSession = transport.supportsLocalFileAccess
97
+ ? new LogSession(() => spawn(resolveAdbPath() ?? "adb", ["logcat", "-v", "threadtime", "-T", "1"], {
98
+ stdio: ["ignore", "pipe", "ignore"],
99
+ }), (line) => parseLogcat(line))
100
+ : null;
83
101
  // Kill the persistent logcat child on process exit so it does not orphan when the
84
102
  // dashboard is spawned and later terminated by the open_radar_dashboard MCP tool.
85
- logSession.registerCleanup();
103
+ logSession?.registerCleanup();
86
104
  // By design the capture is NOT stopped when the last log stream disconnects (e.g.
87
105
  // switching to the Network tab): it keeps filling the session ring so returning to
88
106
  // a log tab — even much later — still shows the full history, the way Android
@@ -321,18 +339,16 @@ const shuttingDown = new WeakSet();
321
339
  * actually exiting the process.
322
340
  */
323
341
  export async function shutdownDashboard(server, deps = {}) {
324
- const _getLive = deps.getLive ?? getLive;
325
- const _stopRecording = deps.stopRecording ?? stopRecording;
342
+ const screen = deps.screen ?? dashboardScreen;
326
343
  const _exit = deps.exit ?? ((code) => process.exit(code));
327
344
  const _log = deps.log ?? ((msg) => console.log(msg));
328
345
  if (shuttingDown.has(server))
329
346
  return;
330
347
  shuttingDown.add(server);
331
348
  _log("\nShutting down…");
332
- const live = _getLive();
333
- if (live && live.recording) {
349
+ if (screen.isRecording()) {
334
350
  try {
335
- await _stopRecording(live);
351
+ await screen.stopRecording();
336
352
  }
337
353
  catch {
338
354
  // Best-effort finalize; proceed with shutdown even if the stop failed.
@@ -354,6 +370,176 @@ export async function shutdownDashboard(server, deps = {}) {
354
370
  fallback = setTimeout(finish, 2000);
355
371
  fallback.unref();
356
372
  }
373
+ /**
374
+ * The ONE device ping every probe site uses: boot-arm's armed check, /health, and /enable's
375
+ * verify step. One function rather than three inline copies so the three-state rules below hold
376
+ * everywhere at once, and so the ceiling cannot be lowered at one site while the others keep the
377
+ * old value. The default ceiling sits inside observed latency: a health read against an
378
+ * unauthorized device has been measured at over 2.2 seconds.
379
+ *
380
+ * The classification rules, each load-bearing:
381
+ * - Anything that ANSWERS is "armed": something we must not clobber. A 200 is Radar; another
382
+ * status still means a live server on the socket, which is not ours to re-arm out from under.
383
+ * - Only a clean REFUSAL is "unarmed": ECONNREFUSED means nothing is listening on the local
384
+ * port at all. Through a built adb forward that hardly ever happens: the HOST adb server
385
+ * accepts every connection first and only then discovers whether the device side exists, so
386
+ * an absent device-side socket presents as a RESET, not a refusal.
387
+ * - A timeout, a reset, or a mid-response error is "unknown": not an answer. A reset in
388
+ * particular is ambiguous by construction here (an absent socket and a misbehaving live
389
+ * session read identically through the forward), so the boot chain resolves it against the
390
+ * device's own socket table instead of guessing at this layer.
391
+ */
392
+ function pingDevice(timeoutMs = PING_PROBE_MS) {
393
+ return new Promise((resolve) => {
394
+ let settled = false;
395
+ const done = (state, status = null, body = "") => {
396
+ if (settled)
397
+ return;
398
+ settled = true;
399
+ resolve({ state, status, body });
400
+ };
401
+ const req = http.request({ host: RADAR_HOST, port: RADAR_PORT, path: "/api/ping", method: "GET", timeout: timeoutMs }, (up) => {
402
+ // The ping body is the device's own small JSON status. Bound the accumulation anyway so a
403
+ // misbehaving local endpoint cannot grow it without limit; a truncated body simply fails
404
+ // the caller's JSON.parse, which every caller treats as "no extra detail".
405
+ const MAX_PING_BODY = 64 * 1024;
406
+ let body = "";
407
+ up.on("data", (c) => {
408
+ if (body.length < MAX_PING_BODY)
409
+ body += c;
410
+ });
411
+ up.on("end", () => done("armed", up.statusCode ?? null, body));
412
+ up.on("error", () => done("unknown"));
413
+ });
414
+ req.on("error", (e) => done(e.code === "ECONNREFUSED" ? "unarmed" : "unknown"));
415
+ req.on("timeout", () => {
416
+ req.destroy();
417
+ done("unknown");
418
+ });
419
+ req.end();
420
+ });
421
+ }
422
+ /**
423
+ * Arm Radar once, at dashboard boot, so a launch against a freshly restarted app does not land on
424
+ * "waiting for device" until the human finds the Reconnect button. Called by bin.ts from the listen
425
+ * callback, for the same reason startAutoCloseSweep is: only the process that actually WON the port
426
+ * may touch the device, so a second launcher that adopts a running dashboard never re-arms someone
427
+ * else's session.
428
+ *
429
+ * The work itself runs OFF the event loop entirely (see armDevice), because an
430
+ * attached-but-unauthorised or locked device can hold a single adb call at its 5 second ceiling,
431
+ * and a chain of them can run 15 seconds or more. A server that cannot answer meanwhile breaks
432
+ * the adopt path this file otherwise protects carefully: a second launcher hits EADDRINUSE,
433
+ * probes the loopback /spec with a 2 second timeout to recognise this dashboard, and declares
434
+ * the port foreign and exits if that probe does not answer.
435
+ *
436
+ * NOT routed through handleEnable, which is written around an HTTP response. Two of the steps it
437
+ * additionally performs really are no-ops in a fresh process (resetState and resetDbState only clear
438
+ * in-process fields that are already at their defaults), but two are NOT, and this is deliberately
439
+ * left as a known gap rather than claimed away: resetScreenState() kills orphaned device-side
440
+ * screenrecord processes left by a crashed prior dashboard, and the switched-device branch
441
+ * (cleanupPulledDatabases + logSession.restart) is gated on a serial inherited from the environment,
442
+ * so a boot carrying a stale ANDROID_SERIAL can legitimately be a switch. Pressing Reconnect still
443
+ * performs both. If a third step is ever needed here, extract the shared core instead of copying it.
444
+ */
445
+ export function armOnBoot() {
446
+ // An agent-spawned dashboard must not reach the device on its own. open_radar_dashboard is exempt
447
+ // from the MCP session gate precisely BECAUSE opening a dashboard could not arm anything without a
448
+ // human pressing Reconnect, and arming here would quietly remove the premise that exemption rests
449
+ // on: an agent call would arm a device and begin logcat capture to disk with no human action, and
450
+ // its child is detached with stdio ignored so even a failure line would reach nobody. A human
451
+ // launch, whether a terminal `slack-radar web` or the dock app, sets no marker and does arm.
452
+ if (process.env.SLACK_RADAR_AGENT_LAUNCH)
453
+ return;
454
+ // Escape hatch, matching this file's other automatic-on-boot behaviours (SLACK_RADAR_NO_OPEN,
455
+ // SLACK_RADAR_NO_AUTO_CLOSE, SLACK_RADAR_NO_FFMPEG). This is the first one that touches the
456
+ // physical device, so it is the one that most deserves an opt-out.
457
+ if (process.env.SLACK_RADAR_NO_ARM)
458
+ return;
459
+ void armDevice();
460
+ }
461
+ /**
462
+ * The deferred body of armOnBoot. Never throws: every call below reports through the transport.
463
+ *
464
+ * Every adb step runs through the transport's *Async methods (promisified execFile), so each adb
465
+ * call lives in its own child process and the event loop stays free WHILE a call is in flight,
466
+ * not merely between calls. The bound this buys: the server can accept and answer at any point
467
+ * in the chain, including the middle of a single wedged 5 second adb call, so a second
468
+ * launcher's 2 second /spec probe is answered no matter how slow the device is. An earlier
469
+ * version ran synchronous transport calls with yields between them, which still left each
470
+ * individual call as an unanswerable window at its own ceiling.
471
+ *
472
+ * A detached child was also considered and rejected, but not for the reason once claimed here
473
+ * (that a child's logcat capture would die with it: the dashboard's Logs tab actually reads
474
+ * logSession, spawned per /stream, and startCapture's file is only read by the MCP side's
475
+ * getRecentLogs and snapshot). The real problem is state: selectDevice pins ANDROID_SERIAL and
476
+ * activate records radarEnabled and the timeout, and a child would set all three in its own
477
+ * process and exit, leaving THIS server unpinned and unaware of what it just armed.
478
+ */
479
+ async function armDevice() {
480
+ // One macrotask before any adb child spawns, so armOnBoot's caller provably returns with zero
481
+ // device work started in its own tick (execFile spawns its child synchronously even though the
482
+ // result is awaited).
483
+ await new Promise((resolve) => setImmediate(resolve));
484
+ // Two DIFFERENT situations return not-ok here and both are deliberately silent: a genuinely
485
+ // ambiguous host (two or more devices, which the header's picker must ask about rather than have
486
+ // answered for the user), and a device list that could not be read at all. The second is a real
487
+ // condition, and it is not left unreported: /_control/devices polls separately and distinguishes
488
+ // adb_error from zero devices, which the header's device chip renders as "device: adb error".
489
+ if (!transport.selectDeviceAsync)
490
+ return;
491
+ const selection = await transport.selectDeviceAsync(null);
492
+ if (!selection.ok)
493
+ return;
494
+ // The forward could not be built. Nothing to arm, and the dashboard is still usable for a
495
+ // device plugged in later, but the REASON is printed rather than swallowed: an attached device
496
+ // that is unauthorized or offline fails exactly here, and silence on that path is what left
497
+ // people staring at "waiting for device" with no idea a launch had already tried and why it
498
+ // stopped.
499
+ if (!transport.reassertForwardAsync)
500
+ return;
501
+ if (!(await transport.reassertForwardAsync())) {
502
+ const reason = transport.getLastForwardError?.() ?? null;
503
+ // Only when something is on the cable: an empty desk fails the forward too ("no
504
+ // devices/emulators found"), and that is the deliberately quiet case. An attached but
505
+ // unauthorized device also selects nothing, so the gate is the raw listing, which keeps
506
+ // exactly that case loud.
507
+ if (reason && selection.devices.length > 0) {
508
+ console.log(`Radar could not be armed at startup: ${reason}`);
509
+ }
510
+ return;
511
+ }
512
+ // ALREADY ARMED, so leave it alone. This is not just an optimisation. activate()'s own skip guard
513
+ // is per-instance state and this process is brand new, so without this check boot would
514
+ // re-broadcast on every launch -- and the timeout it would send is this fresh instance's own
515
+ // default, which can be SHORTER than one another process explicitly asked for. An MCP session that
516
+ // armed for 30 minutes would have its idle window silently cut to the default by someone merely
517
+ // opening a dashboard to look, with no error surfaced to either side.
518
+ if ((await pingDevice()).state === "armed")
519
+ return;
520
+ // Anything else the ping says is inconclusive HERE, including a reset: the probe travels the
521
+ // adb forward, and the host adb server accepts every connection before discovering whether the
522
+ // device side exists, so an absent socket and a misbehaving live session read identically. The
523
+ // device's own socket table is the authority the forward cannot distort: ABSENT means no server
524
+ // is bound anywhere, so a broadcast cannot take another session's window. Anything else skips,
525
+ // because the cost of guessing wrong is another process's window while the cost of not arming
526
+ // is one press of a button that is already on screen.
527
+ if (!transport.radarSocketPresentAsync)
528
+ return;
529
+ if ((await transport.radarSocketPresentAsync()) !== "absent")
530
+ return;
531
+ if (transport.activateAsync) {
532
+ await transport.activateAsync(transport.getTimeoutMinutes());
533
+ }
534
+ else {
535
+ transport.activate(transport.getTimeoutMinutes());
536
+ }
537
+ // A device WAS reachable and the broadcast still failed, which is worth printing. Silence here is
538
+ // what left people staring at "waiting for device" with no idea a launch had already tried.
539
+ const error = transport.getLastActivateError?.() ?? null;
540
+ if (error)
541
+ console.log(`Radar could not be armed at startup: ${error}`);
542
+ }
357
543
  /**
358
544
  * Start the periodic auto-close sweep. Called once by bin.ts AFTER a successful listen bind, not
359
545
  * from createServer, so importing this module (or spinning a throwaway server in a test) never
@@ -379,7 +565,7 @@ export function startAutoCloseSweep(server) {
379
565
  * exercise the route without exiting the process. bin.ts calls createServer() with no args.
380
566
  */
381
567
  export function createServer(onShutdown) {
382
- registerScreenCleanup(); // tear down any live screen cast on process exit/signals
568
+ dashboardScreen.registerCleanup();
383
569
  const server = http.createServer((req, res) => {
384
570
  // One chokepoint for every route: a request whose Host is not this loopback dashboard is a
385
571
  // rebound foreign origin, not our client (see isLocalHostHeader). Rejected before routing so
@@ -461,7 +647,8 @@ export function createServer(onShutdown) {
461
647
  if (tab)
462
648
  touchTab(tab);
463
649
  }
464
- handleHealth(res);
650
+ // Deliberately not awaited; handleHealth answers res itself and never rejects.
651
+ void handleHealth(res);
465
652
  return;
466
653
  }
467
654
  if (urlPath === "/shutdown" && req.method === "POST") {
@@ -470,13 +657,23 @@ export function createServer(onShutdown) {
470
657
  }
471
658
  if (urlPath === "/enable" && req.method === "POST") {
472
659
  const serial = new URL(url, `http://localhost:${WEB_PORT}`).searchParams.get("device_serial");
473
- handleEnable(res, serial, isAuthoredRequest(req.headers));
660
+ // Deliberately not awaited; handleEnable answers res itself and never rejects.
661
+ void handleEnable(res, serial, isAuthoredRequest(req.headers));
474
662
  return;
475
663
  }
476
664
  if (url === "/stream" && req.method === "GET") {
477
665
  handleStream(req, res);
478
666
  return;
479
667
  }
668
+ if (url.startsWith("/backfill") || url.startsWith("/detail") || url.startsWith("/api/") ||
669
+ url.startsWith("/dbs") || url.startsWith("/dbtables") || url.startsWith("/dbquery") ||
670
+ url.startsWith("/flags") || url.split("?")[0] === "/prefs" ||
671
+ url.startsWith("/prefsread") || url.startsWith("/prefssearch")) {
672
+ if (!transport.supportsLocalFileAccess) {
673
+ sendJson(res, 400, { error: `Not supported on ${transport.platform}` });
674
+ return;
675
+ }
676
+ }
480
677
  if (url.startsWith("/backfill")) {
481
678
  handleBackfill(req, res);
482
679
  return;
@@ -714,7 +911,7 @@ function handleShutdown(req, res, fire) {
714
911
  * is built. Drives the connection dot even on a blank dashboard. Reuses the same
715
912
  * forward/proxy base as the rest of the server.
716
913
  */
717
- function handleHealth(res) {
914
+ async function handleHealth(res) {
718
915
  // Reassert before reading: see forwardForRead's doc comment. Without this, a foreign
719
916
  // repoint of the shared port (the MCP process switching devices) makes /health probe
720
917
  // the WRONG device while still labeling the reply with THIS process's own (correct)
@@ -723,80 +920,43 @@ function handleHealth(res) {
723
920
  // the cost low on the 2s poll cadence; it only pays for a real rebuild when the shared
724
921
  // port is actually pointed somewhere else.
725
922
  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;
923
+ const ping = await pingDevice();
924
+ const ok = ping.state === "armed" && ping.status === 200;
730
925
  // The bound profile, read from the device ping body. This is the TRUTH about which
731
926
  // profile owns the socket (the app that bound first), unlike the host-side activate
732
927
  // guess in getActiveUserId() which can drift. The dashboard shows this so it never
733
928
  // 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);
929
+ let uid = null;
930
+ let profile = null;
931
+ let sources = null;
932
+ // Only trust the body on a healthy 200. A device 5xx-ing with a stale ping body must NOT
933
+ // surface a bound profile while device:false -- that would let the dashboard show a
934
+ // confident profile label for an unhealthy device.
935
+ if (ok) {
936
+ try {
937
+ const p = JSON.parse(ping.body);
938
+ if (p.android_user_id != null)
939
+ uid = String(p.android_user_id);
940
+ if (typeof p.profile === "string")
941
+ profile = p.profile;
942
+ if (Array.isArray(p.sources))
943
+ sources = p.sources;
944
+ }
945
+ catch {
946
+ // non-JSON / partial body: device is up but we cannot name the profile
947
+ }
948
+ }
949
+ const selected = transport.getSelectedDevice?.() ?? null;
950
+ sendJson(res, 200, {
951
+ device: ok,
952
+ screen: dashboardScreen.capabilities(),
953
+ boundUserId: uid,
954
+ boundProfile: profile,
955
+ device_serial: selected?.serial ?? null,
956
+ device_label: selected?.label ?? null,
957
+ // Capture sources the build declares on ping (seam builds only); null on older builds.
958
+ sources,
798
959
  });
799
- probe.end();
800
960
  }
801
961
  /**
802
962
  * The /enable response body for a completed device probe, plus its one side effect: a
@@ -974,12 +1134,12 @@ processState = "unknown") {
974
1134
  * user never has to drop to a terminal. Delegates entirely to AndroidTransport;
975
1135
  * no adb shelling here.
976
1136
  */
977
- function handleEnable(res, deviceSerial, authored) {
1137
+ async function handleEnable(res, deviceSerial, authored) {
978
1138
  transport.resetState();
979
1139
  // A reconnect may be a different device / re-armed profile, so drop the cached DB user
980
1140
  // set + sqlite path; the next /dbs re-detects the profiles fresh.
981
1141
  resetDbState();
982
- // Pin the target device BEFORE any adb call, including resetScreenState's pkill below --
1142
+ // Pin the target device BEFORE any platform screen reset below --
983
1143
  // that call has no serial of its own and would otherwise target whatever `adb` defaults
984
1144
  // to (or fail ambiguously) on a multi-device host, running one adb call outside the
985
1145
  // "pin before any adb call" invariant every other call site in this handler honors. An
@@ -994,7 +1154,41 @@ function handleEnable(res, deviceSerial, authored) {
994
1154
  });
995
1155
  return;
996
1156
  }
997
- resetScreenState(); // re-detect the active display + clear any stale cast on re-arm
1157
+ // The serial pinned at REPLY time, which under an overlapping /enable can differ from the pin
1158
+ // this press made -- and reply time is the correct read: the verify probe rode the forward as
1159
+ // it is NOW, readProcessState reads the same current pin, and the next /health poll reports
1160
+ // this serial, so the reply stays consistent with its own diagnosis and with the poll that
1161
+ // follows. Echoed on every reply past this point so the store can advance its serial baseline
1162
+ // from the reply itself, instead of discovering the pin from a later health poll whose serial
1163
+ // edge would retire the very reason the reply carries.
1164
+ const pinnedSerial = () => transport.getSelectedDevice?.()?.serial ?? null;
1165
+ // Screen state: the SAFE SUBSET unless this is a real session boundary. The controller's full
1166
+ // reset() is destructive on every platform -- Android's kills radar's device-side screenrecord,
1167
+ // deletes the saved recordings, and tears down a live cast the user may be watching this second;
1168
+ // iOS's deletes the saved recordings on disk. Running that on every enable meant a plain re-arm
1169
+ // of the SAME device destroyed work nobody asked it to, and it made the enable route unsafe to
1170
+ // call from anything automatic. So the full teardown is now earned by one of two things:
1171
+ // - the pin moved to DIFFERENT hardware, so every piece of per-device screen state is stale, or
1172
+ // - this is the first enable in this PROCESS with a device actually attached, which is where an
1173
+ // orphaned screenrecord left by a crashed previous dashboard gets cleaned up.
1174
+ // Everything else gets the detection reset only, which is all a same-device re-arm actually needs.
1175
+ const pinned = selection && selection.ok ? (selection.serial ?? null) : null;
1176
+ // A null pin means "nothing attached", not "the hardware changed".
1177
+ const switched = pinned !== null && lastArmedSerial !== null && pinned !== lastArmedSerial;
1178
+ // The one-shot orphan reap is spent only on an enable that HAS a device; an empty-device press
1179
+ // would fire it at nothing and leave the real orphan alive for the life of the process.
1180
+ if (switched || (pinned !== null && !screenResetThisProcess)) {
1181
+ screenResetThisProcess = true;
1182
+ dashboardScreen.reset();
1183
+ }
1184
+ else {
1185
+ dashboardScreen.resetDetection();
1186
+ }
1187
+ // Only remember a serial we actually ARMED. selectDevice returns { ok: true, serial: null } when
1188
+ // nothing is attached (android.ts path d), and letting that null overwrite the memory would make a
1189
+ // later pin of DIFFERENT hardware look like a first pin, so a real swap would take the light path.
1190
+ if (pinned)
1191
+ lastArmedSerial = pinned;
998
1192
  // On a switch to a different device, drop this device's pulled DB scratch AND the
999
1193
  // retained logcat capture -- both are per-device state resetDbState()/resetScreenState()
1000
1194
  // above do not cover. logSession.restart() (not stop()) is deliberate here: stop() alone
@@ -1004,9 +1198,9 @@ function handleEnable(res, deviceSerial, authored) {
1004
1198
  // which resets its own local buffers/spool/capture on the same switch signal). start() is
1005
1199
  // idempotent, so a still-open Logs tab just keeps polling and picks the new child back up
1006
1200
  // on its next /stream reconnect; nothing here needs to force-restart it eagerly.
1007
- if (selection && selection.ok && selection.switched) {
1201
+ if (switched) {
1008
1202
  cleanupPulledDatabases();
1009
- logSession.restart();
1203
+ logSession?.restart();
1010
1204
  }
1011
1205
  // Reassert the forward is pointed at the selected device before reading. On a device
1012
1206
  // switch or after a multi-process repoint (e.g., MCP server switched to a different
@@ -1024,53 +1218,44 @@ function handleEnable(res, deviceSerial, authored) {
1024
1218
  sendJson(res, 200, {
1025
1219
  enabled: false,
1026
1220
  error: reason ?? "ADB forward failed. Is a device connected?",
1221
+ device_serial: pinnedSerial(),
1027
1222
  });
1028
1223
  return;
1029
1224
  }
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());
1225
+ // activateAsync() never throws; a failed broadcast is recorded on the transport.
1226
+ // Surfacing it here gives the dashboard user the actual adb error instead of a bare
1227
+ // enabled:false after the ping probe times out. Async for the same reason as the boot chain:
1228
+ // the broadcast waits for ordered delivery under a 15 second ceiling, and a Reconnect press
1229
+ // must not hold the event loop for it.
1230
+ if (transport.activateAsync) {
1231
+ await transport.activateAsync(transport.getTimeoutMinutes());
1232
+ }
1233
+ else {
1234
+ transport.activate(transport.getTimeoutMinutes());
1235
+ }
1034
1236
  const activateError = transport.getLastActivateError?.() ?? null;
1035
1237
  if (activateError) {
1036
1238
  sendJson(res, 200, {
1037
1239
  enabled: false,
1038
1240
  error: `Broadcast failed: ${activateError}. Is the device connected?`,
1241
+ device_serial: pinnedSerial(),
1039
1242
  });
1040
1243
  return;
1041
1244
  }
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);
1245
+ // Verify by pinging the device the same way /health does (the shared pingDevice, so the
1246
+ // ceiling and the three-state rules cannot drift from the other probe sites).
1247
+ const ping = await pingDevice();
1248
+ const enabled = ping.state === "armed" && ping.status === 200;
1249
+ // Probe the process state only on the failure path: a successful enable needs no diagnosis,
1250
+ // and the probe is a real adb round trip. Capped short, because by this point the failure is
1251
+ // already established and the user is watching a request that has stalled their SSE tabs; an
1252
+ // explanation must not cost more than the operation it explains. The MCP path keeps the
1253
+ // patient default, where seconds of ping retries have already elapsed and a real answer
1254
+ // beats a fast "unknown".
1255
+ sendJson(res, 200, {
1256
+ ...enableResultBody(enabled, keepAliveHookFor(authored), enabled ? "unknown" : readProcessState(transport, DIAGNOSTIC_PS_TIMEOUT_MS)),
1257
+ device_serial: pinnedSerial(),
1072
1258
  });
1073
- probe.end();
1074
1259
  }
1075
1260
  // The device-buffered source kinds, in one table so a new source is one row here: the
1076
1261
  // device API route segment (clog and trace pluralize; the rest match the kind name) and
@@ -1199,7 +1384,7 @@ function handleDetail(req, res) {
1199
1384
  // (no paging), so nothing to inject. Response is buffered so a device error becomes a clean 200
1200
1385
  // {error} the Feature Flags tab renders in-place rather than a half-streamed body.
1201
1386
  //
1202
- // Device list shape: { feature_flags: [{ key, enabled, is_overridden }], total }. `enabled` is
1387
+ // Device list shape: { feature_flags: [{ key, scope, org_id, type, enabled | group_name, is_overridden, timestamp }], total_captured }. `enabled` is
1203
1388
  // the effective value (override if set, else the server value). Live changes arrive separately
1204
1389
  // as `feature_flag` frames on /api/stream (the on-device observer). Builds predating the plugin
1205
1390
  // 404, surfaced as a friendly message client-side.
@@ -1444,20 +1629,26 @@ function handleScreen(req, res) {
1444
1629
  const refresh = new URL(url, "http://localhost").searchParams.get("refresh") === "1";
1445
1630
  if (refresh) {
1446
1631
  void (async () => {
1447
- // refreshScreenCapabilities cannot throw today, but a future edit that lets a rejection
1632
+ // A platform capability refresh should never leave the request hanging if it fails.
1448
1633
  // escape would leave this request hanging until the client's 3s timeout. Guard it: on a
1449
1634
  // failed re-probe, still answer with the (cached) capabilities rather than nothing.
1450
1635
  try {
1451
- await refreshScreenCapabilities();
1636
+ await dashboardScreen.refreshCapabilities();
1452
1637
  }
1453
1638
  catch {
1454
1639
  // fall through to the cached capabilities below
1455
1640
  }
1456
- sendJson(res, 200, { ...screenCapabilities(), consent: hasScreenConsent() });
1641
+ sendJson(res, 200, {
1642
+ ...dashboardScreen.capabilities(),
1643
+ consent: hasScreenConsent(),
1644
+ });
1457
1645
  })();
1458
1646
  }
1459
1647
  else {
1460
- sendJson(res, 200, { ...screenCapabilities(), consent: hasScreenConsent() });
1648
+ sendJson(res, 200, {
1649
+ ...dashboardScreen.capabilities(),
1650
+ consent: hasScreenConsent(),
1651
+ });
1461
1652
  }
1462
1653
  return;
1463
1654
  }
@@ -1482,24 +1673,35 @@ function handleScreen(req, res) {
1482
1673
  // rejection would leave this request hanging until the client times out, and a route whose
1483
1674
  // whole purpose is reporting the outcome must not have a silent way to report nothing.
1484
1675
  try {
1485
- await detectDisplay();
1486
- const shot = await saveScreenshot();
1487
- if (!shot.ok) {
1488
- // Name the half that failed. A write failure is a host problem (no space, a dir mode the
1489
- // process cannot write); calling it a capture failure would send the user to check a
1490
- // phone that answered perfectly well.
1491
- sendJson(res, 502, { ok: false, error: screenshotSaveErrorMessage(shot) });
1676
+ await dashboardScreen.refreshCapabilities();
1677
+ const png = await dashboardScreen.captureScreenshot();
1678
+ if (!png) {
1679
+ sendJson(res, 502, { ok: false, error: "screencap failed; is the device awake and connected?" });
1680
+ return;
1681
+ }
1682
+ const SC_TMP = path.join(os.homedir(), ".slack-radar", "screen");
1683
+ const safe = new Date().toISOString().replace(/[:.]/g, "-");
1684
+ const out = path.join(SC_TMP, `radar_screen_${safe}.png`);
1685
+ try {
1686
+ fs.mkdirSync(SC_TMP, { recursive: true, mode: 0o700 });
1687
+ try {
1688
+ fs.chmodSync(SC_TMP, 0o700);
1689
+ }
1690
+ catch { /* best-effort */ }
1691
+ fs.writeFileSync(out, png, { mode: 0o600 });
1692
+ }
1693
+ catch (e) {
1694
+ sendJson(res, 502, { ok: false, error: "could not write the screenshot to disk: " + e.message });
1492
1695
  return;
1493
1696
  }
1494
- const p = shot.path;
1495
1697
  let sizeBytes = 0;
1496
1698
  try {
1497
- sizeBytes = fs.statSync(p).size;
1699
+ sizeBytes = fs.statSync(out).size;
1498
1700
  }
1499
1701
  catch {
1500
1702
  sizeBytes = 0;
1501
1703
  }
1502
- const file = path.basename(p);
1704
+ const file = path.basename(out);
1503
1705
  sendJson(res, 200, {
1504
1706
  ok: true,
1505
1707
  file,
@@ -1522,15 +1724,17 @@ function handleScreen(req, res) {
1522
1724
  return;
1523
1725
  }
1524
1726
  void (async () => {
1525
- await detectDisplay();
1526
- const png = await captureScreenshot();
1727
+ const png = await dashboardScreen.captureScreenshot();
1527
1728
  if (!png) {
1528
- sendJson(res, 502, { error: "screencap failed; is the device awake and connected?" });
1729
+ sendJson(res, 502, { error: "screen capture failed; is the device running and awake?" });
1529
1730
  return;
1530
1731
  }
1732
+ const inline = new URL(url, `http://localhost:${WEB_PORT}`).searchParams.get("inline") === "1";
1531
1733
  res.writeHead(200, {
1532
1734
  "Content-Type": "image/png",
1533
- "Content-Disposition": `attachment; filename="radar-screen-${Date.now()}.png"`,
1735
+ ...(inline
1736
+ ? { "Cache-Control": "no-store" }
1737
+ : { "Content-Disposition": `attachment; filename="radar-screen-${Date.now()}.png"` }),
1534
1738
  });
1535
1739
  res.end(png);
1536
1740
  })();
@@ -1542,8 +1746,11 @@ function handleScreen(req, res) {
1542
1746
  sendJson(res, 403, { error: "screen consent required" });
1543
1747
  return;
1544
1748
  }
1545
- if (!resolveFfmpeg()) {
1546
- sendJson(res, 501, { error: "ffmpeg not installed", installHint: ffmpegInstallHint() });
1749
+ const capabilities = dashboardScreen.capabilities();
1750
+ if (!capabilities.liveCast) {
1751
+ sendJson(res, 501, capabilities.installHint
1752
+ ? { error: "ffmpeg not installed", installHint: capabilities.installHint }
1753
+ : { error: `live mirroring is not supported for ${capabilities.platform} yet` });
1547
1754
  return;
1548
1755
  }
1549
1756
  const fps = Number(new URL(url, `http://localhost:${WEB_PORT}`).searchParams.get("fps")) || 20;
@@ -1585,39 +1792,47 @@ function handleScreen(req, res) {
1585
1792
  return;
1586
1793
  }
1587
1794
  void (async () => {
1588
- await detectDisplay();
1589
- if (!startLive(20)) {
1590
- sendJson(res, 501, { error: "ffmpeg not installed", installHint: ffmpegInstallHint() });
1591
- return;
1795
+ try {
1796
+ const recording = await dashboardScreen.startRecording();
1797
+ if (!recording) {
1798
+ const capabilities = dashboardScreen.capabilities();
1799
+ sendJson(res, 501, capabilities.installHint
1800
+ ? { error: "screen recording dependency unavailable", installHint: capabilities.installHint }
1801
+ : { error: `screen recording is not supported for ${capabilities.platform}` });
1802
+ return;
1803
+ }
1804
+ sendJson(res, 200, { ok: true, file: path.basename(recording) });
1805
+ }
1806
+ catch (error) {
1807
+ sendJson(res, 502, { error: error instanceof Error ? error.message : String(error) });
1592
1808
  }
1593
- const p = startRecording();
1594
- sendJson(res, 200, { ok: p !== null, file: p ? path.basename(p) : null });
1595
1809
  })();
1596
1810
  return;
1597
1811
  }
1598
1812
  if (url === "/screen/record/stop" && req.method === "POST") {
1599
1813
  void (async () => {
1600
- const p = await stopRecording();
1601
- // If the viewer already left (the close-while-recording path drops the <img> before
1602
- // this POST lands), the recording was the only thing keeping the cast alive — reap it
1603
- // now so screenrecord + ffmpeg do not run on with no viewer.
1604
- reapLiveIfIdle();
1605
- const file = p ? path.basename(p) : null;
1606
- let sizeBytes = 0;
1607
- if (p) {
1608
- try {
1609
- sizeBytes = fs.statSync(p).size;
1610
- }
1611
- catch {
1612
- sizeBytes = 0;
1814
+ try {
1815
+ const p = await dashboardScreen.stopRecording();
1816
+ const file = p ? path.basename(p) : null;
1817
+ let sizeBytes = 0;
1818
+ if (p) {
1819
+ try {
1820
+ sizeBytes = fs.statSync(p).size;
1821
+ }
1822
+ catch {
1823
+ sizeBytes = 0;
1824
+ }
1613
1825
  }
1826
+ sendJson(res, 200, {
1827
+ ok: true,
1828
+ file,
1829
+ sizeBytes,
1830
+ download: file ? "/screen/download?f=" + encodeURIComponent(file) : null,
1831
+ });
1832
+ }
1833
+ catch (error) {
1834
+ sendJson(res, 502, { error: error instanceof Error ? error.message : String(error) });
1614
1835
  }
1615
- sendJson(res, 200, {
1616
- ok: true,
1617
- file,
1618
- sizeBytes,
1619
- download: file ? "/screen/download?f=" + encodeURIComponent(file) : null,
1620
- });
1621
1836
  })();
1622
1837
  return;
1623
1838
  }
@@ -1664,8 +1879,11 @@ function handleScreen(req, res) {
1664
1879
  return;
1665
1880
  }
1666
1881
  if (url === "/screen/redetect") {
1667
- resetScreenState();
1668
- void detectDisplay().then(() => sendJson(res, 200, { display: displayNote() }));
1882
+ void dashboardScreen.redetect()
1883
+ .then((display) => sendJson(res, 200, { display }))
1884
+ .catch((error) => sendJson(res, 502, {
1885
+ error: error instanceof Error ? error.message : String(error),
1886
+ }));
1669
1887
  return;
1670
1888
  }
1671
1889
  res.writeHead(404);
@@ -1788,7 +2006,7 @@ function handleStream(req, res) {
1788
2006
  const armLogcat = () => {
1789
2007
  if (!wantsLogs || closed)
1790
2008
  return;
1791
- const ok = logSession.start();
2009
+ const ok = logSession?.start() ?? false;
1792
2010
  if (!ok) {
1793
2011
  // Spawn failed (e.g. no adb on PATH). The capture is a named session-scoped
1794
2012
  // thing now, so surface the reason rather than showing silent emptiness.
@@ -1867,7 +2085,7 @@ function handleStream(req, res) {
1867
2085
  if (wantsLogs) {
1868
2086
  refreshPidMap(); // warm PID->package so the first log rows resolve their app
1869
2087
  armLogcat(); // idempotent start; surfaces a status frame if spawn fails
1870
- unsubscribeLogs = logSession.subscribe((ev, replay) => {
2088
+ unsubscribeLogs = logSession?.subscribe((ev, replay) => {
1871
2089
  if (closed)
1872
2090
  return;
1873
2091
  // Backpressure guard: if this client is slow or its tab is backgrounded
@@ -1913,13 +2131,13 @@ function handleStream(req, res) {
1913
2131
  });
1914
2132
  }
1915
2133
  function listProfiles(res) {
1916
- const profiles = transport.listProfiles();
2134
+ const profiles = transport.listProfiles?.() ?? [];
1917
2135
  const activeUserId = transport.getActiveUserId();
1918
2136
  sendJson(res, 200, { profiles, active_user_id: activeUserId });
1919
2137
  }
1920
2138
  // The attached-device list + the currently pinned device, for the dashboard's device picker.
1921
- // listDevices() returns null when the adb listing itself failed (not "zero attached"); surface
1922
- // that as adb_error:true with an empty list so the client can say why instead of showing "none".
2139
+ // listDevices() returns null when the platform listing itself failed (not "zero attached"). Keep
2140
+ // the legacy adb_error response for the existing client; the iOS happy path uses the same list.
1923
2141
  function listDevices(res) {
1924
2142
  // Distinguish null (adb listing failed) from [] (no devices): null means we cannot tell what
1925
2143
  // is attached, so tell the client with adb_error instead of a bare "none". A transport with no
@@ -1945,7 +2163,7 @@ function activateRadar(res, userId) {
1945
2163
  return;
1946
2164
  }
1947
2165
  try {
1948
- if (userId) {
2166
+ if (userId && transport.activateForUser) {
1949
2167
  transport.activateForUser(userId, 5);
1950
2168
  }
1951
2169
  else {