@slack/radar-mcp 1.17.1 → 1.18.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 (36) hide show
  1. package/README.md +31 -10
  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 +32 -4
  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/shared/android-dashboard-screen.d.ts +15 -0
  9. package/dist/shared/android-dashboard-screen.js +48 -0
  10. package/dist/shared/android.d.ts +1 -0
  11. package/dist/shared/android.js +12 -1
  12. package/dist/shared/dashboard-screen.d.ts +35 -0
  13. package/dist/shared/dashboard-screen.js +12 -0
  14. package/dist/shared/ios-dashboard-screen.d.ts +32 -0
  15. package/dist/shared/ios-dashboard-screen.js +266 -0
  16. package/dist/shared/ios.d.ts +72 -0
  17. package/dist/shared/ios.js +313 -0
  18. package/dist/shared/platform.d.ts +3 -0
  19. package/dist/shared/platform.js +16 -0
  20. package/dist/shared/screen-artifacts.d.ts +27 -0
  21. package/dist/shared/screen-artifacts.js +73 -0
  22. package/dist/shared/screen.d.ts +20 -11
  23. package/dist/shared/screen.js +47 -70
  24. package/dist/shared/transport.d.ts +38 -0
  25. package/dist/shared/webapp.d.ts +1 -0
  26. package/dist/shared/webapp.js +2 -0
  27. package/dist/web/bin.js +13 -9
  28. package/dist/web/public/index.html +63 -12
  29. package/dist/web/public/next/app.js +24 -1
  30. package/dist/web/public/next/db.js +292 -39
  31. package/dist/web/public/next/flags.js +306 -48
  32. package/dist/web/public/next/screen.js +219 -73
  33. package/dist/web/public/next/store.js +63 -1
  34. package/dist/web/server.d.ts +19 -9
  35. package/dist/web/server.js +330 -84
  36. 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,10 @@ 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";
19
+ // The disk half of the screen reap, imported from the module that owns the only implementation of
20
+ // it. screen.js re-exports the same function for its own callers.
21
+ import { SCREEN_DIRECTORY, cleanupRecordings } from "../shared/screen-artifacts.js";
17
22
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
18
23
  const WEB_PORT = Number(process.env.SLACK_RADAR_WEB_PORT ?? WEB_PORT_DEFAULT);
19
24
  const INDEX_PATH = path.join(__dirname, "public", "index.html");
@@ -61,7 +66,79 @@ const SPEC_PATH = path.join(SPEC_DIR, `web-spec-${WEB_PORT}.json`);
61
66
  // (JSON.stringify of the body) on every poll, and adding fields here would perturb that
62
67
  // fingerprint every launch for a reason unrelated to the actual spec.
63
68
  const SELF_HEAL_PATH = path.join(SPEC_DIR, "self-heal.json");
64
- const transport = new AndroidTransport();
69
+ // mcp/index.ts overwrites this on every MCP server boot. Per-machine like self-heal.json (not
70
+ // port-scoped): the question is "has any MCP server booted on this machine", which is not a
71
+ // property of a port. Unlike self-heal.json the writer is a SEPARATE process that can be a
72
+ // different version, so a missing marker means "not seen yet", never "the tools are missing".
73
+ // Resolved per call, not at module load like SPEC_DIR: os.homedir() reads HOME at call time,
74
+ // which lets an in-process test point the read at a scratch home instead of touching the
75
+ // developer's real marker.
76
+ function mcpSeenPath() {
77
+ return path.join(os.homedir(), ".slack-radar", "mcp-last-seen.json");
78
+ }
79
+ const transport = createTransport();
80
+ const dashboardScreen = createDashboardScreenController(transport);
81
+ // The serial this process last did screen housekeeping for: seeded by boot's orphan reap
82
+ // (armDevice) and advanced by every /enable that pins real hardware. Kept here rather than
83
+ // trusting `selection.switched`, so the decision cannot be perturbed by anything that clears
84
+ // ANDROID_SERIAL or by a reconcile change. The two also DIFFER on a null pin: `switched` is
85
+ // absent when nothing is attached, while this keeps the last real arm across an empty-device
86
+ // enable, which turns out to be the interesting case.
87
+ let lastArmedSerial = null;
88
+ // Whether the orphan reap has run AT ALL in this process. The one-shot itself is decided in one
89
+ // place, reapScreenOnce below, so boot and /enable cannot drift on the question "has this process
90
+ // reaped yet". handleEnable's device-switch teardown also marks the flag spent, because a switch
91
+ // earns a teardown on every switch rather than once per process, so it is deliberately not a
92
+ // caller of the one-shot.
93
+ let reapedThisProcess = false;
94
+ // Only the dashboard on the DEFAULT port reaps unprompted at boot. The pkill matches by cmdline
95
+ // device-wide, and handlePortInUse hands people `SLACK_RADAR_WEB_PORT=8101 slack-radar web` in an
96
+ // error message, so a sidecar launched on that advice would kill the primary dashboard's live cast
97
+ // with nobody pressing anything. A sidecar leaves reapedThisProcess false, so its /enable fallback
98
+ // still reaps on a press, which is where the responsibility belongs.
99
+ const MAY_REAP_AT_BOOT = WEB_PORT === WEB_PORT_DEFAULT;
100
+ /**
101
+ * The one full screen teardown a process performs on its own initiative: kill any orphaned
102
+ * device-side screenrecord a crashed predecessor left running, and delete its stale clips.
103
+ *
104
+ * Owns the one-shot decision on `reapedThisProcess`, so boot and /enable cannot drift on "has
105
+ * this process reaped yet", and returns whether it performed the teardown so a caller with
106
+ * nothing else to do can fall back to a detection reset. (The device-switch teardown in
107
+ * handleEnable marks the flag spent without calling this; see the flag's own comment.)
108
+ *
109
+ * The switch memory is deliberately NOT its business: `lastArmedSerial` records what a process
110
+ * ARMED, which happens on boots this function never runs for.
111
+ *
112
+ * `serial` null means no device to reap ON: zero attached, an ambiguous multi-device desk, an
113
+ * unauthorized device, or a listing adb could not read. The pkill needs a serial, so it waits for
114
+ * a later call; `clearFilesWithoutDevice` lets BOOT still delete a killed predecessor's clips in
115
+ * that state, which needs no device. /enable passes false, because by then the clips on disk can
116
+ * be this process's own work.
117
+ *
118
+ * Callers that cannot reach this at boot, and therefore depend on the /enable fallback:
119
+ * - iOS never reaps at boot: armDevice needs selectDeviceAsync and only AndroidTransport
120
+ * implements it, so /enable is iOS's only session-boundary screen cleanup. Permanent.
121
+ * - SLACK_RADAR_NO_ARM / SLACK_RADAR_AGENT_LAUNCH return in armOnBoot before armDevice.
122
+ * - A dashboard on a non-default port, per MAY_REAP_AT_BOOT above.
123
+ */
124
+ function reapScreenOnce(serial, clearFilesWithoutDevice) {
125
+ if (reapedThisProcess)
126
+ return false;
127
+ if (serial === null) {
128
+ // Disk half only. Deliberately does NOT set the flag: no orphaned screenrecord has been
129
+ // killed yet, so a later pin still has its teardown to spend.
130
+ //
131
+ // Reach worth knowing: ~/.slack-radar/screen is per USER, not per port, so this deletes a
132
+ // second dashboard's captures too, while the pkill behind the serial gate leaves its cast
133
+ // running and writing to an unlinked file, so its save reports a name it cannot serve.
134
+ if (clearFilesWithoutDevice)
135
+ cleanupRecordings();
136
+ return false;
137
+ }
138
+ dashboardScreen.reset();
139
+ reapedThisProcess = true;
140
+ return true;
141
+ }
65
142
  // The ONE ceiling for every device ping this file makes (boot-arm, /health, /enable all go
66
143
  // through pingDevice). A shorter one turns ordinary latency into a false negative: boot would
67
144
  // read a live-but-slow session as absent, and /health would flap the connection dot. Observed
@@ -82,12 +159,15 @@ function forwardForRead() {
82
159
  // log history instead of only lines that arrive after the reconnect, matching
83
160
  // how Android Studio retains logcat for the whole session. Spawn + parse are
84
161
  // injected so the capture logic is unit-testable without a real `adb logcat`.
85
- const logSession = new LogSession(() => spawn(resolveAdbPath() ?? "adb", ["logcat", "-v", "threadtime", "-T", "1"], {
86
- stdio: ["ignore", "pipe", "ignore"],
87
- }), (line) => parseLogcat(line));
162
+ // Only spawn when the transport supports local device access (i.e. Android).
163
+ const logSession = transport.supportsLocalFileAccess
164
+ ? new LogSession(() => spawn(resolveAdbPath() ?? "adb", ["logcat", "-v", "threadtime", "-T", "1"], {
165
+ stdio: ["ignore", "pipe", "ignore"],
166
+ }), (line) => parseLogcat(line))
167
+ : null;
88
168
  // Kill the persistent logcat child on process exit so it does not orphan when the
89
169
  // dashboard is spawned and later terminated by the open_radar_dashboard MCP tool.
90
- logSession.registerCleanup();
170
+ logSession?.registerCleanup();
91
171
  // By design the capture is NOT stopped when the last log stream disconnects (e.g.
92
172
  // switching to the Network tab): it keeps filling the session ring so returning to
93
173
  // a log tab — even much later — still shows the full history, the way Android
@@ -124,6 +204,20 @@ function loadSelfHeal() {
124
204
  return {};
125
205
  }
126
206
  }
207
+ // mcpSeen false is the normal "no MCP client has ever connected" state the header's setup hint
208
+ // keys off, so a missing or corrupt marker must read that way rather than as an error. Only the
209
+ // boolean rides the wire: the marker's timestamp is validity evidence for THIS read, and the
210
+ // header renders nothing in the state where a timestamp exists to show.
211
+ function loadSetupHint() {
212
+ try {
213
+ const parsed = JSON.parse(fs.readFileSync(mcpSeenPath(), "utf8"));
214
+ // A timestamp is the whole marker, so a parseable file without one is not evidence of a boot.
215
+ return { mcpSeen: typeof parsed.seenAt === "string" };
216
+ }
217
+ catch {
218
+ return { mcpSeen: false };
219
+ }
220
+ }
127
221
  // Start every run from a clean slate so a refresh/restart opens blank — UNLESS the
128
222
  // process was spawned with an initial spec (SLACK_RADAR_INITIAL_SPEC). The MCP
129
223
  // open_radar_dashboard handler sets that env on a cold spawn so the spec file is
@@ -173,6 +267,16 @@ export function cleanupOnBind() {
173
267
  process.once(sig, cleanupPulledDatabases);
174
268
  }
175
269
  }
270
+ /**
271
+ * Arm the screen cleanup-on-exit handlers for THIS process. Same post-bind discipline, and the
272
+ * same reason, as cleanupOnBind and seedInitialSpec: the handler deletes ~/.slack-radar/screen
273
+ * captures, which are per USER rather than per port, so a second launcher that LOSES the bind
274
+ * would delete the running dashboard's clips on its way out. Registered from createServer()
275
+ * before, which is exactly the window that made adopting a dashboard cost the winner its saves.
276
+ */
277
+ export function registerScreenCleanupOnBind() {
278
+ dashboardScreen.registerCleanup();
279
+ }
176
280
  // --- Dashboard presence + auto-close ------------------------------------------
177
281
  //
178
282
  // The dashboard never tore itself down: closing every browser tab left this Node
@@ -326,18 +430,16 @@ const shuttingDown = new WeakSet();
326
430
  * actually exiting the process.
327
431
  */
328
432
  export async function shutdownDashboard(server, deps = {}) {
329
- const _getLive = deps.getLive ?? getLive;
330
- const _stopRecording = deps.stopRecording ?? stopRecording;
433
+ const screen = deps.screen ?? dashboardScreen;
331
434
  const _exit = deps.exit ?? ((code) => process.exit(code));
332
435
  const _log = deps.log ?? ((msg) => console.log(msg));
333
436
  if (shuttingDown.has(server))
334
437
  return;
335
438
  shuttingDown.add(server);
336
439
  _log("\nShutting down…");
337
- const live = _getLive();
338
- if (live && live.recording) {
440
+ if (screen.isRecording()) {
339
441
  try {
340
- await _stopRecording(live);
442
+ await screen.stopRecording();
341
443
  }
342
444
  catch {
343
445
  // Best-effort finalize; proceed with shutdown even if the stop failed.
@@ -424,12 +526,15 @@ function pingDevice(timeoutMs = PING_PROBE_MS) {
424
526
  *
425
527
  * NOT routed through handleEnable, which is written around an HTTP response. Two of the steps it
426
528
  * 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.
529
+ * in-process fields that are already at their defaults). The screen teardown is NOT a no-op and runs
530
+ * here instead (see armDevice): boot owns the orphan reap, which is what lets /enable reserve its
531
+ * own teardown for a genuine device switch rather than spend one on its first press. /enable still
532
+ * reaps as a fallback when boot could not pin a serial to reap for, so a launch that cannot arm
533
+ * does not leave the orphan alive for the whole process. One gap is deliberately left rather than
534
+ * claimed away: the switched-device branch (cleanupPulledDatabases + logSession.restart) is gated
535
+ * on a serial inherited from the environment, so a boot carrying a stale ANDROID_SERIAL can
536
+ * legitimately be a switch, and only Reconnect performs that part. If a third step is ever needed
537
+ * here, extract the shared core instead of copying it.
433
538
  */
434
539
  export function armOnBoot() {
435
540
  // An agent-spawned dashboard must not reach the device on its own. open_radar_dashboard is exempt
@@ -475,7 +580,41 @@ async function armDevice() {
475
580
  // answered for the user), and a device list that could not be read at all. The second is a real
476
581
  // condition, and it is not left unreported: /_control/devices polls separately and distinguishes
477
582
  // adb_error from zero devices, which the header's device chip renders as "device: adb error".
583
+ if (!transport.selectDeviceAsync)
584
+ return;
478
585
  const selection = await transport.selectDeviceAsync(null);
586
+ // Reap what a crashed predecessor left behind, before any user work exists in THIS process. The
587
+ // pkill's device-wide reach (it matches the `output-format=h264` cmdline, so a hand-run
588
+ // `screenrecord --output-format=h264` is matched too) is why MAY_REAP_AT_BOOT keeps this to the
589
+ // canonical dashboard; the orphans it clears congest the single adb transport for everyone.
590
+ //
591
+ // Ahead of the already-armed check below on purpose: the reap must happen even when boot has
592
+ // nothing to arm, or a crashed dashboard whose device-side session is still live is never
593
+ // cleaned up. reapScreenOnce owns the rest, including deferring to an /enable that landed
594
+ // inside this function's own adb chain and already reaped.
595
+ //
596
+ // A boot that clears files but pins nothing does not make the consent panel's promise
597
+ // unconditional, and that promise is the outgoing process's job anyway (its exit handler
598
+ // deletes the same files with no device involved). The boots listed on reapScreenOnce still
599
+ // leave a KILLED predecessor's clips for one more restart, which is reachable rather than
600
+ // academic: /screen/* gates on consent alone and needs no arm.
601
+ const bootPin = selection.ok ? (selection.serial ?? null) : null;
602
+ if (MAY_REAP_AT_BOOT)
603
+ reapScreenOnce(bootPin, true);
604
+ // Seed the switch memory on EVERY boot that pinned something, outside the reap gate: this
605
+ // records what this process armed, which a sidecar does just as much as the canonical dashboard,
606
+ // while the gate above is only about who may fire a device-wide kill unprompted. Coupling the
607
+ // two would leave a sidecar's first /enable onto DIFFERENT hardware reading as a first pin, so
608
+ // the switch would skip cleanupPulledDatabases and logSession.restart and hand device B device
609
+ // A's retained logcat ring. The first /enable of the SAME hardware still takes the light path.
610
+ //
611
+ // Only when nothing has seeded yet: a deliberate /enable can land inside this function's own
612
+ // adb listing, and its pin is the newer of the two. armDevice runs once per process and
613
+ // handleEnable is the only other writer, so a non-null value here can only be that enable's,
614
+ // and letting a late-resolving boot overwrite it would make the next plain re-arm of the
615
+ // enable's device read as a switch and spend a full teardown on live work.
616
+ if (bootPin && lastArmedSerial === null)
617
+ lastArmedSerial = bootPin;
479
618
  if (!selection.ok)
480
619
  return;
481
620
  // The forward could not be built. Nothing to arm, and the dashboard is still usable for a
@@ -483,6 +622,8 @@ async function armDevice() {
483
622
  // that is unauthorized or offline fails exactly here, and silence on that path is what left
484
623
  // people staring at "waiting for device" with no idea a launch had already tried and why it
485
624
  // stopped.
625
+ if (!transport.reassertForwardAsync)
626
+ return;
486
627
  if (!(await transport.reassertForwardAsync())) {
487
628
  const reason = transport.getLastForwardError?.() ?? null;
488
629
  // Only when something is on the cable: an empty desk fails the forward too ("no
@@ -509,9 +650,16 @@ async function armDevice() {
509
650
  // is bound anywhere, so a broadcast cannot take another session's window. Anything else skips,
510
651
  // because the cost of guessing wrong is another process's window while the cost of not arming
511
652
  // is one press of a button that is already on screen.
653
+ if (!transport.radarSocketPresentAsync)
654
+ return;
512
655
  if ((await transport.radarSocketPresentAsync()) !== "absent")
513
656
  return;
514
- await transport.activateAsync(transport.getTimeoutMinutes());
657
+ if (transport.activateAsync) {
658
+ await transport.activateAsync(transport.getTimeoutMinutes());
659
+ }
660
+ else {
661
+ transport.activate(transport.getTimeoutMinutes());
662
+ }
515
663
  // A device WAS reachable and the broadcast still failed, which is worth printing. Silence here is
516
664
  // what left people staring at "waiting for device" with no idea a launch had already tried.
517
665
  const error = transport.getLastActivateError?.() ?? null;
@@ -543,7 +691,6 @@ export function startAutoCloseSweep(server) {
543
691
  * exercise the route without exiting the process. bin.ts calls createServer() with no args.
544
692
  */
545
693
  export function createServer(onShutdown) {
546
- registerScreenCleanup(); // tear down any live screen cast on process exit/signals
547
694
  const server = http.createServer((req, res) => {
548
695
  // One chokepoint for every route: a request whose Host is not this loopback dashboard is a
549
696
  // rebound foreign origin, not our client (see isLocalHostHeader). Rejected before routing so
@@ -600,6 +747,10 @@ export function createServer(onShutdown) {
600
747
  sendJson(res, 200, loadSelfHeal());
601
748
  return;
602
749
  }
750
+ if (url === "/setup-hint" && req.method === "GET") {
751
+ sendJson(res, 200, loadSetupHint());
752
+ return;
753
+ }
603
754
  if (url === "/setspec" && req.method === "POST") {
604
755
  handleSetSpec(req, res, isAuthoredRequest(req.headers));
605
756
  return;
@@ -643,6 +794,15 @@ export function createServer(onShutdown) {
643
794
  handleStream(req, res);
644
795
  return;
645
796
  }
797
+ if (url.startsWith("/backfill") || url.startsWith("/detail") || url.startsWith("/api/") ||
798
+ url.startsWith("/dbs") || url.startsWith("/dbtables") || url.startsWith("/dbquery") ||
799
+ url.startsWith("/flags") || url.split("?")[0] === "/prefs" ||
800
+ url.startsWith("/prefsread") || url.startsWith("/prefssearch")) {
801
+ if (!transport.supportsLocalFileAccess) {
802
+ sendJson(res, 400, { error: `Not supported on ${transport.platform}` });
803
+ return;
804
+ }
805
+ }
646
806
  if (url.startsWith("/backfill")) {
647
807
  handleBackfill(req, res);
648
808
  return;
@@ -918,7 +1078,7 @@ async function handleHealth(res) {
918
1078
  const selected = transport.getSelectedDevice?.() ?? null;
919
1079
  sendJson(res, 200, {
920
1080
  device: ok,
921
- screen: screenCapabilities(),
1081
+ screen: dashboardScreen.capabilities(),
922
1082
  boundUserId: uid,
923
1083
  boundProfile: profile,
924
1084
  device_serial: selected?.serial ?? null,
@@ -965,6 +1125,7 @@ const READ_ONLY_EXACT = new Set([
965
1125
  "/health",
966
1126
  "/spec",
967
1127
  "/self-heal",
1128
+ "/setup-hint", // reads a boolean marker; never touches the device
968
1129
  "/stream", // EventSource cannot set headers, so this must stay open
969
1130
  "/backfill",
970
1131
  "/detail",
@@ -1108,7 +1269,7 @@ async function handleEnable(res, deviceSerial, authored) {
1108
1269
  // A reconnect may be a different device / re-armed profile, so drop the cached DB user
1109
1270
  // set + sqlite path; the next /dbs re-detects the profiles fresh.
1110
1271
  resetDbState();
1111
- // Pin the target device BEFORE any adb call, including resetScreenState's pkill below --
1272
+ // Pin the target device BEFORE any platform screen reset below --
1112
1273
  // that call has no serial of its own and would otherwise target whatever `adb` defaults
1113
1274
  // to (or fail ambiguously) on a multi-device host, running one adb call outside the
1114
1275
  // "pin before any adb call" invariant every other call site in this handler honors. An
@@ -1131,7 +1292,53 @@ async function handleEnable(res, deviceSerial, authored) {
1131
1292
  // from the reply itself, instead of discovering the pin from a later health poll whose serial
1132
1293
  // edge would retire the very reason the reply carries.
1133
1294
  const pinnedSerial = () => transport.getSelectedDevice?.()?.serial ?? null;
1134
- resetScreenState(); // re-detect the active display + clear any stale cast on re-arm
1295
+ // Screen state: the SAFE SUBSET unless this is a real session boundary. The controller's full
1296
+ // reset() is destructive on every platform -- Android's kills radar's device-side screenrecord,
1297
+ // deletes the saved recordings, and tears down a live cast the user may be watching this second;
1298
+ // iOS's deletes the saved recordings on disk. Running that on every enable meant a plain re-arm
1299
+ // of the SAME device destroyed work nobody asked it to, and it made the enable route unsafe to
1300
+ // call from anything automatic. So the full teardown is earned by one of two things:
1301
+ // - the pin moved to DIFFERENT hardware, so every piece of per-device screen state is stale, or
1302
+ // - nothing has reaped in this process yet, which reapScreenOnce answers: boot never pinned a
1303
+ // serial, never ran at all, or was a sidecar on a non-default port.
1304
+ //
1305
+ // The second is not the old per-process one-shot back: that spent a teardown on the first enable
1306
+ // even when boot had already reaped. reapScreenOnce fires only when boot did not, and without it
1307
+ // such a process never reaps for its whole lifetime, because the switch gate needs a prior armed
1308
+ // serial and only an arm can set one.
1309
+ //
1310
+ // Live work IS in reach on that path, and iOS is where it matters. armDevice returns before the
1311
+ // reap unless the transport implements selectDeviceAsync, and only AndroidTransport does
1312
+ // (src/shared/ios.ts has the sync selectDevice alone), so boot never reaps on iOS and this
1313
+ // fallback is the only session-boundary screen cleanup iOS gets. An iOS recording also needs no
1314
+ // /enable to exist: startRecording only needs ensureForward, which selects the booted simulator
1315
+ // itself. So a first /enable there can stop a recording the user started. Kept anyway, because
1316
+ // deleting this branch would remove screen cleanup from iOS entirely. Android reaches less far:
1317
+ // the common ambiguous host cannot resolve a device for screenrecord without a pin, so no cast
1318
+ // can have started, and only a single-device host with the boot arm suppressed can hold live work.
1319
+ //
1320
+ // Everything else gets the detection reset only, which is all a same-device re-arm actually needs.
1321
+ const pinned = selection && selection.ok ? (selection.serial ?? null) : null;
1322
+ // A null pin means "nothing attached", not "the hardware changed".
1323
+ const switched = pinned !== null && lastArmedSerial !== null && pinned !== lastArmedSerial;
1324
+ if (switched) {
1325
+ // A real hardware change earns the teardown every time, not once per process, so this is the
1326
+ // one reap that does not go through reapScreenOnce. Setting the flag here still tells a later
1327
+ // caller that this process has reaped.
1328
+ reapedThisProcess = true;
1329
+ dashboardScreen.reset();
1330
+ }
1331
+ else if (!reapScreenOnce(pinned, false)) {
1332
+ // No teardown was owed. false covers the empty-cable enable for the same reason the seed
1333
+ // below needs a real pin: there is no device to reap on, so spending the one-shot there would
1334
+ // leave a later real pin with nothing left to earn a teardown with.
1335
+ dashboardScreen.resetDetection();
1336
+ }
1337
+ // Only remember a serial we actually ARMED. selectDevice returns { ok: true, serial: null } when
1338
+ // nothing is attached (android.ts path d), and letting that null overwrite the memory would make a
1339
+ // later pin of DIFFERENT hardware look like a first pin, so a real swap would take the light path.
1340
+ if (pinned)
1341
+ lastArmedSerial = pinned;
1135
1342
  // On a switch to a different device, drop this device's pulled DB scratch AND the
1136
1343
  // retained logcat capture -- both are per-device state resetDbState()/resetScreenState()
1137
1344
  // above do not cover. logSession.restart() (not stop()) is deliberate here: stop() alone
@@ -1141,9 +1348,9 @@ async function handleEnable(res, deviceSerial, authored) {
1141
1348
  // which resets its own local buffers/spool/capture on the same switch signal). start() is
1142
1349
  // idempotent, so a still-open Logs tab just keeps polling and picks the new child back up
1143
1350
  // on its next /stream reconnect; nothing here needs to force-restart it eagerly.
1144
- if (selection && selection.ok && selection.switched) {
1351
+ if (switched) {
1145
1352
  cleanupPulledDatabases();
1146
- logSession.restart();
1353
+ logSession?.restart();
1147
1354
  }
1148
1355
  // Reassert the forward is pointed at the selected device before reading. On a device
1149
1356
  // switch or after a multi-process repoint (e.g., MCP server switched to a different
@@ -1170,7 +1377,12 @@ async function handleEnable(res, deviceSerial, authored) {
1170
1377
  // enabled:false after the ping probe times out. Async for the same reason as the boot chain:
1171
1378
  // the broadcast waits for ordered delivery under a 15 second ceiling, and a Reconnect press
1172
1379
  // must not hold the event loop for it.
1173
- await transport.activateAsync(transport.getTimeoutMinutes());
1380
+ if (transport.activateAsync) {
1381
+ await transport.activateAsync(transport.getTimeoutMinutes());
1382
+ }
1383
+ else {
1384
+ transport.activate(transport.getTimeoutMinutes());
1385
+ }
1174
1386
  const activateError = transport.getLastActivateError?.() ?? null;
1175
1387
  if (activateError) {
1176
1388
  sendJson(res, 200, {
@@ -1322,7 +1534,7 @@ function handleDetail(req, res) {
1322
1534
  // (no paging), so nothing to inject. Response is buffered so a device error becomes a clean 200
1323
1535
  // {error} the Feature Flags tab renders in-place rather than a half-streamed body.
1324
1536
  //
1325
- // Device list shape: { feature_flags: [{ key, enabled, is_overridden }], total }. `enabled` is
1537
+ // Device list shape: { feature_flags: [{ key, scope, org_id, type, enabled | group_name, is_overridden, timestamp }], total_captured }. `enabled` is
1326
1538
  // the effective value (override if set, else the server value). Live changes arrive separately
1327
1539
  // as `feature_flag` frames on /api/stream (the on-device observer). Builds predating the plugin
1328
1540
  // 404, surfaced as a friendly message client-side.
@@ -1567,20 +1779,26 @@ function handleScreen(req, res) {
1567
1779
  const refresh = new URL(url, "http://localhost").searchParams.get("refresh") === "1";
1568
1780
  if (refresh) {
1569
1781
  void (async () => {
1570
- // refreshScreenCapabilities cannot throw today, but a future edit that lets a rejection
1782
+ // A platform capability refresh should never leave the request hanging if it fails.
1571
1783
  // escape would leave this request hanging until the client's 3s timeout. Guard it: on a
1572
1784
  // failed re-probe, still answer with the (cached) capabilities rather than nothing.
1573
1785
  try {
1574
- await refreshScreenCapabilities();
1786
+ await dashboardScreen.refreshCapabilities();
1575
1787
  }
1576
1788
  catch {
1577
1789
  // fall through to the cached capabilities below
1578
1790
  }
1579
- sendJson(res, 200, { ...screenCapabilities(), consent: hasScreenConsent() });
1791
+ sendJson(res, 200, {
1792
+ ...dashboardScreen.capabilities(),
1793
+ consent: hasScreenConsent(),
1794
+ });
1580
1795
  })();
1581
1796
  }
1582
1797
  else {
1583
- sendJson(res, 200, { ...screenCapabilities(), consent: hasScreenConsent() });
1798
+ sendJson(res, 200, {
1799
+ ...dashboardScreen.capabilities(),
1800
+ consent: hasScreenConsent(),
1801
+ });
1584
1802
  }
1585
1803
  return;
1586
1804
  }
@@ -1605,24 +1823,34 @@ function handleScreen(req, res) {
1605
1823
  // rejection would leave this request hanging until the client times out, and a route whose
1606
1824
  // whole purpose is reporting the outcome must not have a silent way to report nothing.
1607
1825
  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) });
1826
+ await dashboardScreen.refreshCapabilities();
1827
+ const png = await dashboardScreen.captureScreenshot();
1828
+ if (!png) {
1829
+ sendJson(res, 502, { ok: false, error: "screencap failed; is the device awake and connected?" });
1830
+ return;
1831
+ }
1832
+ const safe = new Date().toISOString().replace(/[:.]/g, "-");
1833
+ const out = path.join(SCREEN_DIRECTORY, `radar_screen_${safe}.png`);
1834
+ try {
1835
+ fs.mkdirSync(SCREEN_DIRECTORY, { recursive: true, mode: 0o700 });
1836
+ try {
1837
+ fs.chmodSync(SCREEN_DIRECTORY, 0o700);
1838
+ }
1839
+ catch { /* best-effort */ }
1840
+ fs.writeFileSync(out, png, { mode: 0o600 });
1841
+ }
1842
+ catch (e) {
1843
+ sendJson(res, 502, { ok: false, error: "could not write the screenshot to disk: " + e.message });
1615
1844
  return;
1616
1845
  }
1617
- const p = shot.path;
1618
1846
  let sizeBytes = 0;
1619
1847
  try {
1620
- sizeBytes = fs.statSync(p).size;
1848
+ sizeBytes = fs.statSync(out).size;
1621
1849
  }
1622
1850
  catch {
1623
1851
  sizeBytes = 0;
1624
1852
  }
1625
- const file = path.basename(p);
1853
+ const file = path.basename(out);
1626
1854
  sendJson(res, 200, {
1627
1855
  ok: true,
1628
1856
  file,
@@ -1645,15 +1873,17 @@ function handleScreen(req, res) {
1645
1873
  return;
1646
1874
  }
1647
1875
  void (async () => {
1648
- await detectDisplay();
1649
- const png = await captureScreenshot();
1876
+ const png = await dashboardScreen.captureScreenshot();
1650
1877
  if (!png) {
1651
- sendJson(res, 502, { error: "screencap failed; is the device awake and connected?" });
1878
+ sendJson(res, 502, { error: "screen capture failed; is the device running and awake?" });
1652
1879
  return;
1653
1880
  }
1881
+ const inline = new URL(url, `http://localhost:${WEB_PORT}`).searchParams.get("inline") === "1";
1654
1882
  res.writeHead(200, {
1655
1883
  "Content-Type": "image/png",
1656
- "Content-Disposition": `attachment; filename="radar-screen-${Date.now()}.png"`,
1884
+ ...(inline
1885
+ ? { "Cache-Control": "no-store" }
1886
+ : { "Content-Disposition": `attachment; filename="radar-screen-${Date.now()}.png"` }),
1657
1887
  });
1658
1888
  res.end(png);
1659
1889
  })();
@@ -1665,8 +1895,11 @@ function handleScreen(req, res) {
1665
1895
  sendJson(res, 403, { error: "screen consent required" });
1666
1896
  return;
1667
1897
  }
1668
- if (!resolveFfmpeg()) {
1669
- sendJson(res, 501, { error: "ffmpeg not installed", installHint: ffmpegInstallHint() });
1898
+ const capabilities = dashboardScreen.capabilities();
1899
+ if (!capabilities.liveCast) {
1900
+ sendJson(res, 501, capabilities.installHint
1901
+ ? { error: "ffmpeg not installed", installHint: capabilities.installHint }
1902
+ : { error: `live mirroring is not supported for ${capabilities.platform} yet` });
1670
1903
  return;
1671
1904
  }
1672
1905
  const fps = Number(new URL(url, `http://localhost:${WEB_PORT}`).searchParams.get("fps")) || 20;
@@ -1708,39 +1941,47 @@ function handleScreen(req, res) {
1708
1941
  return;
1709
1942
  }
1710
1943
  void (async () => {
1711
- await detectDisplay();
1712
- if (!startLive(20)) {
1713
- sendJson(res, 501, { error: "ffmpeg not installed", installHint: ffmpegInstallHint() });
1714
- return;
1944
+ try {
1945
+ const recording = await dashboardScreen.startRecording();
1946
+ if (!recording) {
1947
+ const capabilities = dashboardScreen.capabilities();
1948
+ sendJson(res, 501, capabilities.installHint
1949
+ ? { error: "screen recording dependency unavailable", installHint: capabilities.installHint }
1950
+ : { error: `screen recording is not supported for ${capabilities.platform}` });
1951
+ return;
1952
+ }
1953
+ sendJson(res, 200, { ok: true, file: path.basename(recording) });
1954
+ }
1955
+ catch (error) {
1956
+ sendJson(res, 502, { error: error instanceof Error ? error.message : String(error) });
1715
1957
  }
1716
- const p = startRecording();
1717
- sendJson(res, 200, { ok: p !== null, file: p ? path.basename(p) : null });
1718
1958
  })();
1719
1959
  return;
1720
1960
  }
1721
1961
  if (url === "/screen/record/stop" && req.method === "POST") {
1722
1962
  void (async () => {
1723
- const p = await stopRecording();
1724
- // If the viewer already left (the close-while-recording path drops the <img> before
1725
- // this POST lands), the recording was the only thing keeping the cast alive — reap it
1726
- // now so screenrecord + ffmpeg do not run on with no viewer.
1727
- reapLiveIfIdle();
1728
- const file = p ? path.basename(p) : null;
1729
- let sizeBytes = 0;
1730
- if (p) {
1731
- try {
1732
- sizeBytes = fs.statSync(p).size;
1733
- }
1734
- catch {
1735
- sizeBytes = 0;
1963
+ try {
1964
+ const p = await dashboardScreen.stopRecording();
1965
+ const file = p ? path.basename(p) : null;
1966
+ let sizeBytes = 0;
1967
+ if (p) {
1968
+ try {
1969
+ sizeBytes = fs.statSync(p).size;
1970
+ }
1971
+ catch {
1972
+ sizeBytes = 0;
1973
+ }
1736
1974
  }
1975
+ sendJson(res, 200, {
1976
+ ok: true,
1977
+ file,
1978
+ sizeBytes,
1979
+ download: file ? "/screen/download?f=" + encodeURIComponent(file) : null,
1980
+ });
1981
+ }
1982
+ catch (error) {
1983
+ sendJson(res, 502, { error: error instanceof Error ? error.message : String(error) });
1737
1984
  }
1738
- sendJson(res, 200, {
1739
- ok: true,
1740
- file,
1741
- sizeBytes,
1742
- download: file ? "/screen/download?f=" + encodeURIComponent(file) : null,
1743
- });
1744
1985
  })();
1745
1986
  return;
1746
1987
  }
@@ -1769,13 +2010,15 @@ function handleScreen(req, res) {
1769
2010
  // Drop the server-side copy once it has been handed over. A capture is a full frame of
1770
2011
  // whatever is on the phone, and the download is the point of making it, so keeping it after
1771
2012
  // 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.
2013
+ // session -- cleanupRecordings only runs on a session boundary (dashboard boot, a device
2014
+ // switch, a first enable boot could not reap for, a deliberate re-detect) and on exit. The
2015
+ // user's own copy is untouched, and reveal in the packaged app points at that copy in
2016
+ // ~/Downloads, not at this one. Unlinking a file mid-read is safe, this stream keeps its
2017
+ // descriptor.
1775
2018
  //
1776
2019
  // Hung off "close" rather than "finish" so an ABORTED transfer drops the file too. Nothing
1777
2020
  // 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.
2021
+ // screen in the tmp dir until the next session boundary, which is the leftover this removes.
1779
2022
  res.on("close", () => {
1780
2023
  try {
1781
2024
  fs.unlinkSync(p);
@@ -1787,8 +2030,11 @@ function handleScreen(req, res) {
1787
2030
  return;
1788
2031
  }
1789
2032
  if (url === "/screen/redetect") {
1790
- resetScreenState();
1791
- void detectDisplay().then(() => sendJson(res, 200, { display: displayNote() }));
2033
+ void dashboardScreen.redetect()
2034
+ .then((display) => sendJson(res, 200, { display }))
2035
+ .catch((error) => sendJson(res, 502, {
2036
+ error: error instanceof Error ? error.message : String(error),
2037
+ }));
1792
2038
  return;
1793
2039
  }
1794
2040
  res.writeHead(404);
@@ -1911,7 +2157,7 @@ function handleStream(req, res) {
1911
2157
  const armLogcat = () => {
1912
2158
  if (!wantsLogs || closed)
1913
2159
  return;
1914
- const ok = logSession.start();
2160
+ const ok = logSession?.start() ?? false;
1915
2161
  if (!ok) {
1916
2162
  // Spawn failed (e.g. no adb on PATH). The capture is a named session-scoped
1917
2163
  // thing now, so surface the reason rather than showing silent emptiness.
@@ -1990,7 +2236,7 @@ function handleStream(req, res) {
1990
2236
  if (wantsLogs) {
1991
2237
  refreshPidMap(); // warm PID->package so the first log rows resolve their app
1992
2238
  armLogcat(); // idempotent start; surfaces a status frame if spawn fails
1993
- unsubscribeLogs = logSession.subscribe((ev, replay) => {
2239
+ unsubscribeLogs = logSession?.subscribe((ev, replay) => {
1994
2240
  if (closed)
1995
2241
  return;
1996
2242
  // Backpressure guard: if this client is slow or its tab is backgrounded
@@ -2036,13 +2282,13 @@ function handleStream(req, res) {
2036
2282
  });
2037
2283
  }
2038
2284
  function listProfiles(res) {
2039
- const profiles = transport.listProfiles();
2285
+ const profiles = transport.listProfiles?.() ?? [];
2040
2286
  const activeUserId = transport.getActiveUserId();
2041
2287
  sendJson(res, 200, { profiles, active_user_id: activeUserId });
2042
2288
  }
2043
2289
  // The attached-device list + the currently pinned device, for the dashboard's device picker.
2044
- // listDevices() returns null when the adb listing itself failed (not "zero attached"); surface
2045
- // that as adb_error:true with an empty list so the client can say why instead of showing "none".
2290
+ // listDevices() returns null when the platform listing itself failed (not "zero attached"). Keep
2291
+ // the legacy adb_error response for the existing client; the iOS happy path uses the same list.
2046
2292
  function listDevices(res) {
2047
2293
  // Distinguish null (adb listing failed) from [] (no devices): null means we cannot tell what
2048
2294
  // is attached, so tell the client with adb_error instead of a bare "none". A transport with no
@@ -2068,7 +2314,7 @@ function activateRadar(res, userId) {
2068
2314
  return;
2069
2315
  }
2070
2316
  try {
2071
- if (userId) {
2317
+ if (userId && transport.activateForUser) {
2072
2318
  transport.activateForUser(userId, 5);
2073
2319
  }
2074
2320
  else {