@slack/radar-mcp 1.18.0 → 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.
@@ -16,6 +16,9 @@ import { listPrefsFiles, readPrefsFile, parsePrefsXml, searchPrefs, } from "../s
16
16
  import { LogSession } from "./log-session.js";
17
17
  import { BLANK_SPEC, coerceSpec, validateSpec } from "./spec.js";
18
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";
19
22
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
20
23
  const WEB_PORT = Number(process.env.SLACK_RADAR_WEB_PORT ?? WEB_PORT_DEFAULT);
21
24
  const INDEX_PATH = path.join(__dirname, "public", "index.html");
@@ -63,15 +66,79 @@ const SPEC_PATH = path.join(SPEC_DIR, `web-spec-${WEB_PORT}.json`);
63
66
  // (JSON.stringify of the body) on every poll, and adding fields here would perturb that
64
67
  // fingerprint every launch for a reason unrelated to the actual spec.
65
68
  const SELF_HEAL_PATH = path.join(SPEC_DIR, "self-heal.json");
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
+ }
66
79
  const transport = createTransport();
67
80
  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;
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.
74
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
+ }
75
142
  // The ONE ceiling for every device ping this file makes (boot-arm, /health, /enable all go
76
143
  // through pingDevice). A shorter one turns ordinary latency into a false negative: boot would
77
144
  // read a live-but-slow session as absent, and /health would flap the connection dot. Observed
@@ -137,6 +204,20 @@ function loadSelfHeal() {
137
204
  return {};
138
205
  }
139
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
+ }
140
221
  // Start every run from a clean slate so a refresh/restart opens blank — UNLESS the
141
222
  // process was spawned with an initial spec (SLACK_RADAR_INITIAL_SPEC). The MCP
142
223
  // open_radar_dashboard handler sets that env on a cold spawn so the spec file is
@@ -186,6 +267,16 @@ export function cleanupOnBind() {
186
267
  process.once(sig, cleanupPulledDatabases);
187
268
  }
188
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
+ }
189
280
  // --- Dashboard presence + auto-close ------------------------------------------
190
281
  //
191
282
  // The dashboard never tore itself down: closing every browser tab left this Node
@@ -435,12 +526,15 @@ function pingDevice(timeoutMs = PING_PROBE_MS) {
435
526
  *
436
527
  * NOT routed through handleEnable, which is written around an HTTP response. Two of the steps it
437
528
  * 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.
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.
444
538
  */
445
539
  export function armOnBoot() {
446
540
  // An agent-spawned dashboard must not reach the device on its own. open_radar_dashboard is exempt
@@ -489,6 +583,38 @@ async function armDevice() {
489
583
  if (!transport.selectDeviceAsync)
490
584
  return;
491
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;
492
618
  if (!selection.ok)
493
619
  return;
494
620
  // The forward could not be built. Nothing to arm, and the dashboard is still usable for a
@@ -565,7 +691,6 @@ export function startAutoCloseSweep(server) {
565
691
  * exercise the route without exiting the process. bin.ts calls createServer() with no args.
566
692
  */
567
693
  export function createServer(onShutdown) {
568
- dashboardScreen.registerCleanup();
569
694
  const server = http.createServer((req, res) => {
570
695
  // One chokepoint for every route: a request whose Host is not this loopback dashboard is a
571
696
  // rebound foreign origin, not our client (see isLocalHostHeader). Rejected before routing so
@@ -622,6 +747,10 @@ export function createServer(onShutdown) {
622
747
  sendJson(res, 200, loadSelfHeal());
623
748
  return;
624
749
  }
750
+ if (url === "/setup-hint" && req.method === "GET") {
751
+ sendJson(res, 200, loadSetupHint());
752
+ return;
753
+ }
625
754
  if (url === "/setspec" && req.method === "POST") {
626
755
  handleSetSpec(req, res, isAuthoredRequest(req.headers));
627
756
  return;
@@ -996,6 +1125,7 @@ const READ_ONLY_EXACT = new Set([
996
1125
  "/health",
997
1126
  "/spec",
998
1127
  "/self-heal",
1128
+ "/setup-hint", // reads a boolean marker; never touches the device
999
1129
  "/stream", // EventSource cannot set headers, so this must stay open
1000
1130
  "/backfill",
1001
1131
  "/detail",
@@ -1167,21 +1297,41 @@ async function handleEnable(res, deviceSerial, authored) {
1167
1297
  // deletes the saved recordings, and tears down a live cast the user may be watching this second;
1168
1298
  // iOS's deletes the saved recordings on disk. Running that on every enable meant a plain re-arm
1169
1299
  // 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:
1300
+ // call from anything automatic. So the full teardown is earned by one of two things:
1171
1301
  // - 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.
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
+ //
1174
1320
  // Everything else gets the detection reset only, which is all a same-device re-arm actually needs.
1175
1321
  const pinned = selection && selection.ok ? (selection.serial ?? null) : null;
1176
1322
  // A null pin means "nothing attached", not "the hardware changed".
1177
1323
  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;
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;
1182
1329
  dashboardScreen.reset();
1183
1330
  }
1184
- else {
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.
1185
1335
  dashboardScreen.resetDetection();
1186
1336
  }
1187
1337
  // Only remember a serial we actually ARMED. selectDevice returns { ok: true, serial: null } when
@@ -1679,13 +1829,12 @@ function handleScreen(req, res) {
1679
1829
  sendJson(res, 502, { ok: false, error: "screencap failed; is the device awake and connected?" });
1680
1830
  return;
1681
1831
  }
1682
- const SC_TMP = path.join(os.homedir(), ".slack-radar", "screen");
1683
1832
  const safe = new Date().toISOString().replace(/[:.]/g, "-");
1684
- const out = path.join(SC_TMP, `radar_screen_${safe}.png`);
1833
+ const out = path.join(SCREEN_DIRECTORY, `radar_screen_${safe}.png`);
1685
1834
  try {
1686
- fs.mkdirSync(SC_TMP, { recursive: true, mode: 0o700 });
1835
+ fs.mkdirSync(SCREEN_DIRECTORY, { recursive: true, mode: 0o700 });
1687
1836
  try {
1688
- fs.chmodSync(SC_TMP, 0o700);
1837
+ fs.chmodSync(SCREEN_DIRECTORY, 0o700);
1689
1838
  }
1690
1839
  catch { /* best-effort */ }
1691
1840
  fs.writeFileSync(out, png, { mode: 0o600 });
@@ -1861,13 +2010,15 @@ function handleScreen(req, res) {
1861
2010
  // Drop the server-side copy once it has been handed over. A capture is a full frame of
1862
2011
  // whatever is on the phone, and the download is the point of making it, so keeping it after
1863
2012
  // delivery just leaves device-screen content sitting in the tmp dir for the rest of the
1864
- // session -- cleanupRecordings only runs on re-enable and exit. The user's own copy is
1865
- // untouched, and reveal in the packaged app points at that copy in ~/Downloads, not at this
1866
- // 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.
1867
2018
  //
1868
2019
  // Hung off "close" rather than "finish" so an ABORTED transfer drops the file too. Nothing
1869
2020
  // retries a download, so keeping it after an abort just leaves a full frame of the device
1870
- // 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.
1871
2022
  res.on("close", () => {
1872
2023
  try {
1873
2024
  fs.unlinkSync(p);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slack/radar-mcp",
3
- "version": "1.18.0",
3
+ "version": "1.18.1",
4
4
  "description": "MCP server and web dashboard for debugging Slack on Android and iOS Simulator",
5
5
  "type": "module",
6
6
  "main": "dist/mcp/index.js",