@slack/radar-mcp 1.17.0 → 1.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp/index.js CHANGED
@@ -9,6 +9,7 @@ import path from "path";
9
9
  import { fileURLToPath } from "url";
10
10
  import { AndroidTransport } from "../shared/android.js";
11
11
  import { WebappTransport } from "../shared/webapp.js";
12
+ import { webChildEnv } from "./web-child-env.js";
12
13
  import { RADAR_HOST, RADAR_PORT, RADAR_VERSION, WEB_PORT_DEFAULT, WEBAPP_DEFAULT_PORT, MAX_RADAR_RESPONSE_BYTES, setRadarPort, } from "../shared/constants.js";
13
14
  import { dashboardPlatformError, decidePlatform, pingLooksLikeWebappRadar, quickAndroidDeviceState, unsupportedCapabilityError, } from "./platform-detect.js";
14
15
  import { stopCapture } from "../shared/logcat-capture.js";
@@ -86,12 +87,7 @@ function startWeb(initialSpec) {
86
87
  const child = spawn(process.execPath, [WEB_BIN], {
87
88
  detached: true,
88
89
  stdio: "ignore",
89
- env: {
90
- ...process.env,
91
- SLACK_RADAR_NO_OPEN: "1",
92
- SLACK_RADAR_DEVICE_PORT: String(RADAR_PORT),
93
- ...(initialSpec ? { SLACK_RADAR_INITIAL_SPEC: JSON.stringify(initialSpec) } : {}),
94
- },
90
+ env: webChildEnv(initialSpec),
95
91
  });
96
92
  child.unref();
97
93
  }
@@ -786,7 +782,7 @@ async function runMcpServer() {
786
782
  }
787
783
  }
788
784
  // --- MCP Server ---
789
- const server = new Server({ name: "slack-radar", version: "1.17.0" }, { capabilities: { tools: {} }, instructions: serverInstructions(device.platform) });
785
+ const server = new Server({ name: "slack-radar", version: "1.17.1" }, { capabilities: { tools: {} }, instructions: serverInstructions(device.platform) });
790
786
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
791
787
  tools: TOOL_DEFINITIONS,
792
788
  }));
@@ -0,0 +1 @@
1
+ export declare function webChildEnv(initialSpec?: Record<string, unknown>): NodeJS.ProcessEnv;
@@ -0,0 +1,32 @@
1
+ // The environment a bridge-spawned dashboard runs with.
2
+ //
3
+ // Its own module, and that is the point: SLACK_RADAR_AGENT_LAUNCH is the enforcing half of a consent
4
+ // boundary, and while the value lived inline in the spawn call the whole boundary could be deleted
5
+ // with the suite still green. It cannot live in index.ts either, because that module connects a stdio
6
+ // transport at import time, so a test importing it would hang rather than exit. Keeping the builder
7
+ // here makes the boundary assertable without importing a server.
8
+ import { RADAR_PORT } from "../shared/constants.js";
9
+ export function webChildEnv(initialSpec) {
10
+ return {
11
+ ...process.env,
12
+ // A bridge-spawned dashboard must not pop a window unbidden: the Claude Code session returns the
13
+ // URL instead, which is what the /radar-ui server instructions promise.
14
+ SLACK_RADAR_NO_OPEN: "1",
15
+ // Suppress the dashboard's boot-arm. open_radar_dashboard is deliberately EXEMPT from the MCP
16
+ // session gate, and the stated reason for that exemption is that opening the dashboard cannot by
17
+ // itself reach the device, because arming needs a human to press its Reconnect button. Boot arming
18
+ // would silently invalidate that reasoning: an agent call would arm a real device and start logcat
19
+ // capture to disk with no human in the loop and, since this child is detached with stdio ignored,
20
+ // no visible output either. A HUMAN launch, a terminal `slack-radar web` or the dock app, does not
21
+ // set this and does arm.
22
+ SLACK_RADAR_AGENT_LAUNCH: "1",
23
+ // Passed explicitly rather than inherited. RADAR_PORT is a mutable binding, so a setRadarPort()
24
+ // call in this process is invisible to a child that re-evaluates the same expression from env: it
25
+ // would fall back to the default and talk to the wrong server.
26
+ SLACK_RADAR_DEVICE_PORT: String(RADAR_PORT),
27
+ // Seed the spec so the freshly-spawned server writes it at startup, BEFORE the browser runs
28
+ // bootDefault(). Otherwise bootDefault, which fires only on a blank spec, races a /setspec POST,
29
+ // and a lost race leaves the Live preset showing after the Custom tab was reported live.
30
+ ...(initialSpec ? { SLACK_RADAR_INITIAL_SPEC: JSON.stringify(initialSpec) } : {}),
31
+ };
32
+ }
@@ -45,8 +45,36 @@ export declare class AndroidTransport implements DeviceTransport {
45
45
  ensureForward(): boolean;
46
46
  private rebuildForward;
47
47
  reassertForward(): boolean;
48
+ private recordForwardIfListed;
49
+ /**
50
+ * reassertForward, off the event loop. Same listing-first-then-rebuild logic and the same
51
+ * state fields, but every adb call runs through execFileAsync so a caller that must keep
52
+ * serving HTTP while adb is slow (the dashboard's boot-arm chain) is never blocked, even
53
+ * inside a single call. The sync twin stays for the MCP request paths, which have nothing
54
+ * else to do while adb runs.
55
+ */
56
+ reassertForwardAsync(): Promise<boolean>;
57
+ private rebuildForwardAsync;
48
58
  getLastForwardError(): string | null;
49
59
  activate(timeoutMinutes: number): void;
60
+ /**
61
+ * activate, off the event loop. Same skip guard, the same broadcast argv, and the same
62
+ * state recording as the sync twin, but the `ps` user detection and the broadcast run
63
+ * through execFileAsync so a caller serving HTTP (the dashboard's boot-arm chain) keeps
64
+ * answering while adb runs.
65
+ */
66
+ activateAsync(timeoutMinutes: number): Promise<void>;
67
+ /**
68
+ * Whether the device-side Radar server's abstract socket exists right now, read from the
69
+ * device's own socket table so the answer does not travel through the adb forward. Through a
70
+ * forward every failure collapses to a connection reset, because the HOST adb server accepts
71
+ * the TCP connection unconditionally and only then discovers the device side is absent, so a
72
+ * ping cannot tell "no session exists" from "a session exists and the probe failed". This read
73
+ * can. "unknown" (adb missing, or the table could not be read) leaves the caller its safe branch.
74
+ */
75
+ radarSocketPresentAsync(): Promise<"present" | "absent" | "unknown">;
76
+ private recordActivateSuccess;
77
+ private recordActivateFailure;
50
78
  getLastActivateError(): string | null;
51
79
  resetState(): void;
52
80
  dropForward(): void;
@@ -72,16 +100,34 @@ export declare class AndroidTransport implements DeviceTransport {
72
100
  }[];
73
101
  activateForUser(userId: string, timeoutMinutes: number): void;
74
102
  listDevices(): DeviceInfo[] | null;
103
+ listDevicesAsync(): Promise<DeviceInfo[] | null>;
75
104
  private reconcileSelectedDevice;
76
105
  selectDevice(serial: string | null): {
77
106
  ok: true;
78
107
  serial: string | null;
79
108
  switched?: boolean;
109
+ devices: DeviceInfo[];
80
110
  } | {
81
111
  ok: false;
82
112
  error: string;
83
113
  devices: DeviceInfo[];
84
114
  };
115
+ /**
116
+ * selectDevice, off the event loop. The listing runs through execFileAsync; the pick
117
+ * itself is the exact code the sync twin runs (pickFromListing), so the two cannot
118
+ * disagree about which device wins.
119
+ */
120
+ selectDeviceAsync(serial: string | null): Promise<{
121
+ ok: true;
122
+ serial: string | null;
123
+ switched?: boolean;
124
+ devices: DeviceInfo[];
125
+ } | {
126
+ ok: false;
127
+ error: string;
128
+ devices: DeviceInfo[];
129
+ }>;
130
+ private pickFromListing;
85
131
  getSelectedDevice(): {
86
132
  serial: string;
87
133
  label: string;
@@ -109,9 +155,12 @@ export declare class AndroidTransport implements DeviceTransport {
109
155
  * failure should pass something short; see DIAGNOSTIC_PS_TIMEOUT_MS in web/server.ts.
110
156
  */
111
157
  private psDebugBuildProbe;
158
+ private psDebugBuildProbeAsync;
112
159
  /** Raw `ps` lines for running debug-build Slack processes, or null if there are none. */
113
160
  private psDebugBuildLine;
114
161
  private detectDebugBuildUser;
162
+ private detectDebugBuildUserAsync;
163
+ private cacheUserFromPs;
115
164
  /**
116
165
  * State of the debug-build Slack process, checked fresh via `ps` (independent of
117
166
  * detectDebugBuildUser's cache, so a process that died after the cache was set still
@@ -1,7 +1,8 @@
1
- import { execSync, execFileSync } from "child_process";
1
+ import { execFile, execSync, execFileSync } from "child_process";
2
2
  import fs from "fs";
3
3
  import os from "os";
4
4
  import path from "path";
5
+ import { promisify } from "util";
5
6
  import { readDebugLogBuffer } from "./debug-log.js";
6
7
  import { filterLogLines, getCaptureFilePath, isCapturing, readRecentLogs, registerCleanup, rotateCaptureIfNeeded, startCapture, stopCapture, } from "./logcat-capture.js";
7
8
  import { RADAR_PORT, RADAR_VERSION } from "./constants.js";
@@ -66,6 +67,35 @@ export function resolveAdbPath() {
66
67
  // Module-level resolution, done once at import time. The MCP process lifetime
67
68
  // is short enough (session-scoped) that we do not need to re-resolve.
68
69
  const ADB = resolveAdbPath();
70
+ // Promisified execFile for the *Async transport methods below. argv form (no shell), so an
71
+ // interpolated value can never break out of a command string, and stdout/stderr are captured
72
+ // rather than inherited, matching the stdio discipline execsync-stdio.test.mjs pins.
73
+ const execFileAsync = promisify(execFile);
74
+ // One wording for a missing adb on the forward path, shared by the sync and async rebuilds so
75
+ // the two cannot drift.
76
+ const ADB_NOT_FOUND_FORWARD_ERROR = "adb binary not found. Set ANDROID_HOME or install Android SDK platform-tools. Searched: PATH, $ANDROID_HOME/platform-tools/adb, ~/Library/Android/sdk/platform-tools/adb, ~/Android/Sdk/platform-tools/adb, /usr/local/bin/adb, /opt/homebrew/bin/adb.";
77
+ // The device-side `ps` pipeline both debug-build probes run. See psDebugBuildProbe's doc
78
+ // comment for why the `|| exit 9` and the trailing `|| true` are each load-bearing.
79
+ const PS_DEBUG_BUILD_SCRIPT = 'out=$(ps -A -o USER,NAME) || exit 9; echo "$out" | grep Slack | grep debug || true';
80
+ // The enable broadcast, in argv form so the sync and async activate paths send the exact
81
+ // same command.
82
+ function enableBroadcastArgs(userId, timeoutMinutes) {
83
+ return [
84
+ "shell",
85
+ "am",
86
+ "broadcast",
87
+ "--user",
88
+ userId,
89
+ "-a",
90
+ ENABLE_ACTION,
91
+ "--ei",
92
+ "timeout_minutes",
93
+ String(timeoutMinutes),
94
+ "--es",
95
+ "mcp_version",
96
+ RADAR_VERSION,
97
+ ];
98
+ }
69
99
  /**
70
100
  * Parse the output of `ps -A -o USER,NAME` to extract the Android user ID
71
101
  * for the debug build process. When multiple profiles are running, prefers
@@ -154,8 +184,7 @@ export class AndroidTransport {
154
184
  // never trust the cache (see reassertForward's doc comment on shared-transport.ts).
155
185
  rebuildForward() {
156
186
  if (!ADB) {
157
- this.lastForwardError =
158
- "adb binary not found. Set ANDROID_HOME or install Android SDK platform-tools. Searched: PATH, $ANDROID_HOME/platform-tools/adb, ~/Library/Android/sdk/platform-tools/adb, ~/Android/Sdk/platform-tools/adb, /usr/local/bin/adb, /opt/homebrew/bin/adb.";
187
+ this.lastForwardError = ADB_NOT_FOUND_FORWARD_ERROR;
159
188
  return false;
160
189
  }
161
190
  // Drop any existing mapping first. Re-issuing `adb forward` over a stale mapping
@@ -203,12 +232,8 @@ export class AndroidTransport {
203
232
  encoding: "utf-8",
204
233
  stdio: ["ignore", "pipe", "ignore"],
205
234
  });
206
- const wanted = `${serial} tcp:${RADAR_PORT} localabstract:${SOCKET_NAME}`;
207
- if (list.split("\n").some((line) => line.trim() === wanted)) {
208
- this.portForwarded = true;
209
- this.lastForwardError = null;
235
+ if (this.recordForwardIfListed(list, serial))
210
236
  return true;
211
- }
212
237
  }
213
238
  catch {
214
239
  // Listing failed; fall through to the unconditional rebuild below, which
@@ -217,6 +242,66 @@ export class AndroidTransport {
217
242
  }
218
243
  return this.rebuildForward();
219
244
  }
245
+ // The listing check reassertForward and reassertForwardAsync share: when the live mapping
246
+ // already points our RADAR_PORT at our pinned serial, record it good and skip the rebuild.
247
+ recordForwardIfListed(list, serial) {
248
+ const wanted = `${serial} tcp:${RADAR_PORT} localabstract:${SOCKET_NAME}`;
249
+ if (!list.split("\n").some((line) => line.trim() === wanted))
250
+ return false;
251
+ this.portForwarded = true;
252
+ this.lastForwardError = null;
253
+ return true;
254
+ }
255
+ /**
256
+ * reassertForward, off the event loop. Same listing-first-then-rebuild logic and the same
257
+ * state fields, but every adb call runs through execFileAsync so a caller that must keep
258
+ * serving HTTP while adb is slow (the dashboard's boot-arm chain) is never blocked, even
259
+ * inside a single call. The sync twin stays for the MCP request paths, which have nothing
260
+ * else to do while adb runs.
261
+ */
262
+ async reassertForwardAsync() {
263
+ const serial = process.env.ANDROID_SERIAL;
264
+ if (serial && ADB) {
265
+ try {
266
+ const { stdout } = await execFileAsync(ADB, ["forward", "--list"], {
267
+ timeout: 5000,
268
+ encoding: "utf-8",
269
+ });
270
+ if (this.recordForwardIfListed(stdout, serial))
271
+ return true;
272
+ }
273
+ catch {
274
+ // Listing failed; fall through to the rebuild, exactly like the sync twin.
275
+ }
276
+ }
277
+ return this.rebuildForwardAsync();
278
+ }
279
+ // rebuildForward, off the event loop. Mirrors the sync twin step for step: drop any
280
+ // existing mapping (failure is harmless), then add ours and record the outcome.
281
+ async rebuildForwardAsync() {
282
+ if (!ADB) {
283
+ this.lastForwardError = ADB_NOT_FOUND_FORWARD_ERROR;
284
+ return false;
285
+ }
286
+ try {
287
+ await execFileAsync(ADB, ["forward", "--remove", `tcp:${RADAR_PORT}`], { timeout: 5000 });
288
+ }
289
+ catch {
290
+ // No existing mapping, or adb hiccup; the add below surfaces real failures.
291
+ }
292
+ try {
293
+ await execFileAsync(ADB, ["forward", `tcp:${RADAR_PORT}`, `localabstract:${SOCKET_NAME}`], {
294
+ timeout: 5000,
295
+ });
296
+ this.portForwarded = true;
297
+ this.lastForwardError = null;
298
+ return true;
299
+ }
300
+ catch (e) {
301
+ this.lastForwardError = e.message;
302
+ return false;
303
+ }
304
+ }
220
305
  getLastForwardError() {
221
306
  return this.lastForwardError;
222
307
  }
@@ -230,25 +315,86 @@ export class AndroidTransport {
230
315
  return;
231
316
  try {
232
317
  const userId = this.detectDebugBuildUser();
233
- execSync(`${ADB} shell am broadcast --user ${userId} -a ${ENABLE_ACTION} --ei timeout_minutes ${timeout} --es mcp_version ${RADAR_VERSION}`, { timeout: 5000, stdio: ["ignore", "ignore", "pipe"] });
234
- this.currentTimeoutMinutes = timeout;
235
- this.radarEnabled = true;
236
- this.lastActivateError = null;
237
- // Start streaming logcat to a session-scoped file so reads are not
238
- // subject to the device ring buffer rotating under load.
239
- registerCleanup();
240
- startCapture(ADB);
318
+ // Same taller ceiling as the async twin: the broadcast waits for ordered delivery and a
319
+ // cold debug build can hold completion past 5 seconds.
320
+ execFileSync(ADB, enableBroadcastArgs(userId, timeout), {
321
+ timeout: 15000,
322
+ stdio: ["ignore", "ignore", "pipe"],
323
+ });
324
+ this.recordActivateSuccess(timeout);
325
+ }
326
+ catch (e) {
327
+ this.recordActivateFailure(e);
328
+ }
329
+ }
330
+ /**
331
+ * activate, off the event loop. Same skip guard, the same broadcast argv, and the same
332
+ * state recording as the sync twin, but the `ps` user detection and the broadcast run
333
+ * through execFileAsync so a caller serving HTTP (the dashboard's boot-arm chain) keeps
334
+ * answering while adb runs.
335
+ */
336
+ async activateAsync(timeoutMinutes) {
337
+ if (!ADB) {
338
+ this.lastActivateError = "adb binary not found";
339
+ return;
340
+ }
341
+ const timeout = timeoutMinutes || this.currentTimeoutMinutes;
342
+ if (this.radarEnabled && timeout === this.currentTimeoutMinutes)
343
+ return;
344
+ try {
345
+ const userId = await this.detectDebugBuildUserAsync();
346
+ // The broadcast waits for ordered delivery, and a cold debug build has been observed to
347
+ // hold completion past 5 seconds; a killed broadcast reads as a failed arm, so this one
348
+ // call gets a taller ceiling than the quick adb queries.
349
+ await execFileAsync(ADB, enableBroadcastArgs(userId, timeout), { timeout: 15000 });
350
+ this.recordActivateSuccess(timeout);
241
351
  }
242
352
  catch (e) {
243
- // Broadcast failed, device may not be connected. Recorded so the enable
244
- // path can report it instead of claiming success with a failing ping.
245
- // radarEnabled drops too: a prior success no longer proves the device
246
- // side is armed, and leaving it true would make every later activate()
247
- // early-return and never re-send the broadcast.
248
- this.radarEnabled = false;
249
- this.lastActivateError = e.message;
353
+ this.recordActivateFailure(e);
250
354
  }
251
355
  }
356
+ /**
357
+ * Whether the device-side Radar server's abstract socket exists right now, read from the
358
+ * device's own socket table so the answer does not travel through the adb forward. Through a
359
+ * forward every failure collapses to a connection reset, because the HOST adb server accepts
360
+ * the TCP connection unconditionally and only then discovers the device side is absent, so a
361
+ * ping cannot tell "no session exists" from "a session exists and the probe failed". This read
362
+ * can. "unknown" (adb missing, or the table could not be read) leaves the caller its safe branch.
363
+ */
364
+ async radarSocketPresentAsync() {
365
+ if (!ADB)
366
+ return "unknown";
367
+ try {
368
+ const { stdout } = await execFileAsync(ADB, ["shell", "cat", "/proc/net/unix"], {
369
+ timeout: 5000,
370
+ });
371
+ // The @ pins the match to the abstract-namespace entry the forward targets (the table
372
+ // renders abstract sockets as @name), not any path merely containing the name.
373
+ return stdout.includes(`@${SOCKET_NAME}`) ? "present" : "absent";
374
+ }
375
+ catch {
376
+ return "unknown";
377
+ }
378
+ }
379
+ // A broadcast landed: record the session state and start streaming logcat to a
380
+ // session-scoped file so reads are not subject to the device ring buffer rotating
381
+ // under load. Shared by activate and activateAsync so the two cannot drift.
382
+ recordActivateSuccess(timeout) {
383
+ this.currentTimeoutMinutes = timeout;
384
+ this.radarEnabled = true;
385
+ this.lastActivateError = null;
386
+ registerCleanup();
387
+ if (ADB)
388
+ startCapture(ADB);
389
+ }
390
+ // Broadcast failed, device may not be connected. Recorded so the enable path can report
391
+ // it instead of claiming success with a failing ping. radarEnabled drops too: a prior
392
+ // success no longer proves the device side is armed, and leaving it true would make every
393
+ // later activate() early-return and never re-send the broadcast.
394
+ recordActivateFailure(e) {
395
+ this.radarEnabled = false;
396
+ this.lastActivateError = e.message;
397
+ }
252
398
  getLastActivateError() {
253
399
  return this.lastActivateError;
254
400
  }
@@ -396,7 +542,12 @@ export class AndroidTransport {
396
542
  // scoped to a profile we could not detect, and appending this profile's
397
543
  // run to it would mix profiles in one file. Rotating is the safe default.
398
544
  const profileChanged = this.detectedUserId !== userId;
399
- execSync(`${ADB} shell am broadcast --user ${userId} -a ${ENABLE_ACTION} --ei timeout_minutes ${timeout} --es mcp_version ${RADAR_VERSION}`, { timeout: 5000, stdio: ["ignore", "ignore", "pipe"] });
545
+ // The same argv and the same tall ceiling as activate's twins: the broadcast waits for
546
+ // ordered delivery and a cold debug build can hold completion past 5 seconds.
547
+ execFileSync(ADB, enableBroadcastArgs(userId, timeout), {
548
+ timeout: 15000,
549
+ stdio: ["ignore", "ignore", "pipe"],
550
+ });
400
551
  this.detectedUserId = userId;
401
552
  this.currentTimeoutMinutes = timeout;
402
553
  this.radarEnabled = true;
@@ -437,6 +588,24 @@ export class AndroidTransport {
437
588
  return null;
438
589
  }
439
590
  }
591
+ // listDevices, off the event loop. Same parse, the same selected-device reconciliation,
592
+ // and the same [] / null distinction as the sync twin.
593
+ async listDevicesAsync() {
594
+ if (!ADB)
595
+ return [];
596
+ try {
597
+ const { stdout } = await execFileAsync(ADB, ["devices", "-l"], {
598
+ timeout: 5000,
599
+ encoding: "utf-8",
600
+ });
601
+ const devices = parseAdbDevicesOutput(stdout);
602
+ this.reconcileSelectedDevice(devices);
603
+ return devices;
604
+ }
605
+ catch {
606
+ return null;
607
+ }
608
+ }
440
609
  // Drop the recorded selection if its serial is no longer in the attached list, so
441
610
  // getSelectedDevice() (read by /health and the dashboard header) never claims a
442
611
  // device that has disconnected. Deliberately does NOT touch process.env.ANDROID_SERIAL
@@ -451,7 +620,18 @@ export class AndroidTransport {
451
620
  this.selectedDevice = null;
452
621
  }
453
622
  selectDevice(serial) {
454
- const devices = this.listDevices();
623
+ return this.pickFromListing(this.listDevices(), serial);
624
+ }
625
+ /**
626
+ * selectDevice, off the event loop. The listing runs through execFileAsync; the pick
627
+ * itself is the exact code the sync twin runs (pickFromListing), so the two cannot
628
+ * disagree about which device wins.
629
+ */
630
+ async selectDeviceAsync(serial) {
631
+ return this.pickFromListing(await this.listDevicesAsync(), serial);
632
+ }
633
+ // Everything selectDevice decides once a listing (or its failure, null) is in hand.
634
+ pickFromListing(devices, serial) {
455
635
  if (devices === null) {
456
636
  return {
457
637
  ok: false,
@@ -474,7 +654,7 @@ export class AndroidTransport {
474
654
  const match = attached.find((d) => d.serial === serial);
475
655
  if (match) {
476
656
  this.pin(match.serial, match.label);
477
- return { ok: true, serial: match.serial, switched: switchedTo(match.serial) };
657
+ return { ok: true, serial: match.serial, switched: switchedTo(match.serial), devices };
478
658
  }
479
659
  const list = attached.length > 0 ? listAttached() : "none";
480
660
  return {
@@ -490,7 +670,7 @@ export class AndroidTransport {
490
670
  const stillAttached = attached.find((d) => d.serial === pinned);
491
671
  if (stillAttached) {
492
672
  this.pin(stillAttached.serial, stillAttached.label);
493
- return { ok: true, serial: stillAttached.serial, switched: switchedTo(stillAttached.serial) };
673
+ return { ok: true, serial: stillAttached.serial, switched: switchedTo(stillAttached.serial), devices };
494
674
  }
495
675
  // The pinned device detached. Drop the stale env pin AND the recorded selection so
496
676
  // /health does not keep claiming a device that is gone.
@@ -500,7 +680,7 @@ export class AndroidTransport {
500
680
  // (c) Exactly one attached device: auto-pin it.
501
681
  if (attached.length === 1) {
502
682
  this.pin(attached[0].serial, attached[0].label);
503
- return { ok: true, serial: attached[0].serial, switched: switchedTo(attached[0].serial) };
683
+ return { ok: true, serial: attached[0].serial, switched: switchedTo(attached[0].serial), devices };
504
684
  }
505
685
  // (d) Zero devices (or a fake adb that does not answer `devices -l`): no-op. The
506
686
  // existing ensureForward failure path reports no-device cleanly, and returning
@@ -508,7 +688,7 @@ export class AndroidTransport {
508
688
  if (attached.length === 0) {
509
689
  // Nothing attached: clear any recorded selection so /health reports no device.
510
690
  this.selectedDevice = null;
511
- return { ok: true, serial: null };
691
+ return { ok: true, serial: null, devices };
512
692
  }
513
693
  // (e) 2+ attached devices with no explicit choice: ambiguous. The transport error stays a
514
694
  // neutral, surface-agnostic core; each caller (MCP, web) appends its own retry guidance.
@@ -553,7 +733,29 @@ export class AndroidTransport {
553
733
  if (!ADB)
554
734
  return { state: "unknown", lines: "" };
555
735
  try {
556
- const ps = execSync(`${ADB} shell 'out=$(ps -A -o USER,NAME) || exit 9; echo "$out" | grep Slack | grep debug || true'`, { timeout: timeoutMs, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] }).trim();
736
+ const ps = execSync(`${ADB} shell '${PS_DEBUG_BUILD_SCRIPT}'`, {
737
+ timeout: timeoutMs,
738
+ encoding: "utf-8",
739
+ stdio: ["ignore", "pipe", "pipe"],
740
+ }).trim();
741
+ return ps.length > 0
742
+ ? { state: "running", lines: ps }
743
+ : { state: "stopped", lines: "" };
744
+ }
745
+ catch {
746
+ return { state: "unknown", lines: "" };
747
+ }
748
+ }
749
+ // psDebugBuildProbe, off the event loop. Same script, same tri-state classification.
750
+ async psDebugBuildProbeAsync(timeoutMs = PS_PROBE_TIMEOUT_MS) {
751
+ if (!ADB)
752
+ return { state: "unknown", lines: "" };
753
+ try {
754
+ const { stdout } = await execFileAsync(ADB, ["shell", PS_DEBUG_BUILD_SCRIPT], {
755
+ timeout: timeoutMs,
756
+ encoding: "utf-8",
757
+ });
758
+ const ps = stdout.trim();
557
759
  return ps.length > 0
558
760
  ? { state: "running", lines: ps }
559
761
  : { state: "stopped", lines: "" };
@@ -570,13 +772,22 @@ export class AndroidTransport {
570
772
  detectDebugBuildUser() {
571
773
  if (this.detectedUserId !== null)
572
774
  return this.detectedUserId;
573
- const ps = this.psDebugBuildLine();
775
+ return this.cacheUserFromPs(this.psDebugBuildLine());
776
+ }
777
+ // detectDebugBuildUser, off the event loop. Same cache, same fallback rules.
778
+ async detectDebugBuildUserAsync() {
779
+ if (this.detectedUserId !== null)
780
+ return this.detectedUserId;
781
+ const probe = await this.psDebugBuildProbeAsync();
782
+ return this.cacheUserFromPs(probe.state === "running" ? probe.lines : null);
783
+ }
784
+ // Cache only when a debug-build process was actually seen. Caching the "0"
785
+ // fallback would pin every later enable to user 0 for the process lifetime,
786
+ // so a work-profile build (user 10) launched after a failed detect would
787
+ // never receive the enable broadcast.
788
+ cacheUserFromPs(ps) {
574
789
  if (!ps)
575
790
  return "0";
576
- // Cache only when a debug-build process was actually seen. Caching the "0"
577
- // fallback would pin every later enable to user 0 for the process lifetime,
578
- // so a work-profile build (user 10) launched after a failed detect would
579
- // never receive the enable broadcast.
580
791
  const match = ps.match(/u(\d+)_/);
581
792
  if (!match)
582
793
  return "0";
package/dist/web/bin.js CHANGED
@@ -3,7 +3,7 @@ import { execSync } from "child_process";
3
3
  import { realpathSync } from "fs";
4
4
  import http from "http";
5
5
  import { fileURLToPath } from "url";
6
- import { cleanupOnBind, createServer, seedInitialSpec, shutdownDashboard, startAutoCloseSweep, WEB_PORT, } from "./server.js";
6
+ import { armOnBoot, cleanupOnBind, createServer, seedInitialSpec, shutdownDashboard, startAutoCloseSweep, WEB_PORT, } from "./server.js";
7
7
  import { RADAR_VERSION } from "../shared/constants.js";
8
8
  /**
9
9
  * One loopback GET against the dashboard's own port, used by the adopt path. Resolves with the
@@ -148,6 +148,10 @@ export function startWebServer() {
148
148
  // in createServer) keeps importing the module — or a second launcher that loses the bind —
149
149
  // from arming a timer that could process.exit. The interval is unref'd inside.
150
150
  startAutoCloseSweep(server);
151
+ // Arm the device now, for the same post-bind reason: only the process that won the port may
152
+ // touch it. A fresh app process starts with Radar off, so without this every launch against
153
+ // one shows "waiting for device" until the human finds the Reconnect button.
154
+ armOnBoot();
151
155
  const url = `http://localhost:${WEB_PORT}`;
152
156
  console.log(`Slack Radar Web running at ${url}`);
153
157
  // Auto-open the browser for the HUMAN launcher (`slack-radar web` / `slack-radar-web`),
@@ -39,7 +39,9 @@ function DeviceChip() {
39
39
  const label = selected?.label ?? (ready.length === 1 ? ready[0].label : "none");
40
40
  // A device-select failure (e.g. an ambiguous /enable 409). Shown in warn styling next to the
41
41
  // picker, which stays usable so the user can pick a valid device (a successful pick clears it).
42
- const deviceError = store.deviceError;
42
+ // Suppressed while a reconnect reason is on screen: two differently worded waiting spans in one
43
+ // header row explain the same outage twice, and the reconnect reason is the later answer.
44
+ const deviceError = store.visibleEnableError ? null : store.deviceError;
43
45
  if (store.devicesError) {
44
46
  return html `<span class="profilewrap" title="adb devices failed; check adb">device: <b>adb error</b></span>`;
45
47
  }
@@ -51,8 +53,12 @@ function DeviceChip() {
51
53
  </select>`;
52
54
  return html `<span class="profilewrap" title="the device Radar is bound to; pick another to switch">device: ${picker}${deviceError ? html `<span class="conn waiting" style="margin-left:6px">${deviceError}</span>` : null}</span>`;
53
55
  }
54
- function Header({ screenOpen, onScreenToggle }) {
56
+ export function Header({ screenOpen, onScreenToggle }) {
55
57
  const conn = useStoreValue(store, "conn", () => store.conn);
58
+ // Why the last Reconnect press failed, shown next to the button that produced it. The store's
59
+ // getter owns both conditions (disconnected, and the reason belongs to THIS outage rather than an
60
+ // earlier one), so there is no gating to get wrong here.
61
+ const enableError = useStoreValue(store, "enable-error", () => store.visibleEnableError);
56
62
  const profile = useStoreValue(store, "profile", () => store.profileLabel);
57
63
  const version = useStoreValue(store, "version", () => store.serverVersion);
58
64
  const selfHeal = useStoreValue(store, "self-heal", () => store.selfHeal);
@@ -119,6 +125,7 @@ function Header({ screenOpen, onScreenToggle }) {
119
125
  <span class="profilewrap" title="the device profile Radar is connected to (first app to launch wins the socket)">profile: <b>${profile}</b></span>
120
126
  <${DeviceChip} />
121
127
  ${!connected ? html `<button class="reconnect" disabled=${busy} onClick=${reconnect}>${busy ? "⟳ enabling…" : "⟳ Reconnect Radar"}</button>` : null}
128
+ ${enableError ? html `<span class="conn waiting">${enableError}</span>` : null}
122
129
  <button class="themebtn" onClick=${toggleTheme} title="Toggle light / dark theme">${theme === "light" ? "🌙 Dark" : "☀ Light"}</button>
123
130
  <button class=${"screenbtn" + (screenOpen ? " on" : "")} onClick=${onScreenToggle} title="Mirror the live device screen">▣ Screen</button>
124
131
  <button class=${"themebtn killbtn" + (killArmed ? " armed" : "")} disabled=${killing} onClick=${kill} title=${killArmed ? "Click again to confirm" : "Stop the dashboard server"}>${killing ? "⏻ stopping…" : killArmed ? "⏻ Confirm stop?" : "⏻ Stop dashboard"}</button>
@@ -323,7 +330,12 @@ function App() {
323
330
  <${ScreenOverlay} open=${screenOpen} onClose=${() => setScreenOpen(false)} />
324
331
  `;
325
332
  }
326
- store.start();
333
+ // Both the poll loops and the render are gated on the mount point existing. The render already was;
334
+ // store.start() was not, so importing this module anywhere without an #app element (a test) began
335
+ // polling /health, /spec and /_control/* against nothing. Starting the loops is only meaningful for a
336
+ // mounted app, so they belong on the same condition, which is also what makes Header testable.
327
337
  const root = document.getElementById("app");
328
- if (root)
338
+ if (root) {
339
+ store.start();
329
340
  render(html `<${App} />`, root);
341
+ }
@@ -34,21 +34,29 @@ export const FIELD_VALUES = {
34
34
  // SOURCE registry: one row per source. `kind` routes the view (streaming feed vs the
35
35
  // point-in-time state browser) without a hardcoded source check.
36
36
  export const SOURCES = {
37
- network: { label: "Network", kind: "stream", hasDetailEndpoint: true, eagerCapture: true, ringSize: 400, detailNoun: "the full request/response body" },
38
- rtm: { label: "RTM", kind: "stream", hasDetailEndpoint: true, eagerCapture: true, ringSize: 2000, detailNoun: "the full payload" },
39
- clog: { label: "Clogs", kind: "stream", hasDetailEndpoint: true, eagerCapture: true, ringSize: 1000, detailNoun: "the full payload" },
40
- trace: { label: "Traces", kind: "stream", hasDetailEndpoint: true, ringSize: 2000, detailNoun: "the span timing and tag detail" },
41
- log: { label: "Logs", kind: "stream", hasDetailEndpoint: false },
42
- all: { label: "Live", kind: "stream" },
43
- db: { label: "Database", kind: "state" },
44
- prefs: { label: "Preferences", kind: "state" },
37
+ network: { label: "Network", kind: "stream", origin: "device", hasDetailEndpoint: true, eagerCapture: true, ringSize: 400, detailNoun: "the full request/response body" },
38
+ rtm: { label: "RTM", kind: "stream", origin: "device", hasDetailEndpoint: true, eagerCapture: true, ringSize: 2000, detailNoun: "the full payload" },
39
+ clog: { label: "Clogs", kind: "stream", origin: "device", hasDetailEndpoint: true, eagerCapture: true, ringSize: 1000, detailNoun: "the full payload" },
40
+ trace: { label: "Traces", kind: "stream", origin: "device", hasDetailEndpoint: true, ringSize: 2000, detailNoun: "the span timing and tag detail" },
41
+ log: { label: "Logs", kind: "stream", origin: "host", hasDetailEndpoint: false },
42
+ all: { label: "Live", kind: "stream", origin: "alias" },
43
+ db: { label: "Database", kind: "state", origin: "device" },
44
+ prefs: { label: "Preferences", kind: "state", origin: "device" },
45
45
  // Feature flags: a point-in-time snapshot like db/prefs (own container, no SSE feed).
46
- flags: { label: "Feature Flags", kind: "state" },
46
+ flags: { label: "Feature Flags", kind: "state", origin: "device" },
47
47
  };
48
48
  // The set of streaming source kinds the store admits off the SSE stream (derived from SOURCES,
49
49
  // excluding the non-stream db + the unified "all" alias).
50
50
  export const STREAM_KINDS = Object.entries(SOURCES)
51
- .filter(([k, v]) => v.kind === "stream" && k !== "all")
51
+ .filter(([, v]) => v.kind === "stream" && v.origin !== "alias")
52
+ .map(([k]) => k);
53
+ // The streaming kinds that come FROM THE DEVICE, so one arriving is proof the device-side Radar
54
+ // server is alive and answering. Selected by asking for "device" rather than by excluding the
55
+ // host-side ones, so there is no default to point the wrong way: a new source without an origin does
56
+ // not compile, and one added as "host" or "alias" stays out of the evidence set without anyone having
57
+ // to remember. The registry test still pins this set exactly, as a second line rather than the only one.
58
+ export const DEVICE_STREAM_KINDS = Object.entries(SOURCES)
59
+ .filter(([, v]) => v.kind === "stream" && v.origin === "device")
52
60
  .map(([k]) => k);
53
61
  // The kinds that have a /detail endpoint (inspector click-fetch). Derived from
54
62
  // hasDetailEndpoint so adding a detailable source is one SOURCES edit.