@slack/radar-mcp 1.23.0 → 1.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -108,6 +108,7 @@ All optional. Set them on the process that runs the MCP server or the dashboard.
108
108
  |---|---|
109
109
  | `SLACK_RADAR_WEB_PORT` | Port the dashboard listens on. Default `8100`. The dock app bakes it in at install time, so set it when you run `install-app`. |
110
110
  | `SLACK_RADAR_DEVICE_PORT` | Host port forwarded to the device-side server. Default `8099`. |
111
+ | `SLACK_RADAR_DEBUG_PACKAGE` | The Slack debug package to arm, like `com.Slack.intune.debug`. Set it when two Slack debug builds run on one profile; it must be a Slack debug app id, like `com.Slack.intune.debug` or `com.Slack.debug`. Auto-detect knows the four shipped ids (`com.Slack.internal.debug`, `com.Slack.intune.debug`, `com.Slack.prototype.debug`, `com.Slack.debug`); any other debug app id needs this variable. Unset, Radar uses the one shipped debug build running, else `com.Slack.internal.debug`. The build is decided when the session enables or switches profile and held through re-arms; if it has gone by a re-arm, the re-arm sends nothing to another build, and when nothing else answers the session asks you to enable again. |
111
112
  | `SLACK_RADAR_NO_AUTO_CLOSE=1` | Keep the dashboard running forever instead of closing it once every tab is gone. |
112
113
  | `SLACK_RADAR_ALLOWED_HOSTS` | Extra `Host` values the dashboard will answer, comma-separated (`radar.local,myhost:8100`). Only needed when you reach it by a name other than localhost. See Security. |
113
114
  | `SLACK_RADAR_NO_ARM=1` | Never arm the device without a press: skips the arm at launch and turns off a tab's automatic re-enable. A Reconnect press still arms. |
@@ -161,7 +162,7 @@ Radar starts **disabled** each session. All tools except `ping` return an error
161
162
  | `list_prefs` | List the app's on-device SharedPreferences files. Read-only. |
162
163
  | `get_prefs` | Read a preferences file's keys and values, optionally filtered to specific keys. |
163
164
  | `search_prefs` | Search preference keys and values across every file by a substring. |
164
- | `list_feature_flags` | List every feature flag with its live effective value and override status. Optionally filtered to just the overridden ones. Boolean toggles carry `enabled`; multi-variant experiments carry `type: "experiment"` and a `group_name` string (the effective variant, e.g. `"treatment_a"`) instead. |
165
+ | `list_feature_flags` | List every feature flag with its latest effective value and override status; toggle rows also carry `session_enabled`, the flag's own value fixed for this session. Optionally filtered to just the overridden ones. Boolean toggles carry `enabled`; multi-variant experiments carry `type: "experiment"` and a `group_name` string (the effective variant, e.g. `"treatment_a"`) instead. |
165
166
  | `search_feature_flags` | Case-insensitive substring search on feature flag names, against the same live list as `list_feature_flags`. Rows carry the same `type`/`group_name` fields for experiments. |
166
167
  | `get_feature_flag` | Look up one feature flag by its exact key. Returns one row per scope (authenticated/unauthenticated) and per signed-in org, since each workspace resolves its own value; pass `org_id` to narrow to one workspace. An experiment row carries `type: "experiment"` and its `group_name` variant rather than a boolean `enabled`. |
167
168
  | `run_test_case` | Replay a built-in or hand-written case. Pass `case`, optional `repeat` and `rate_per_second` (null for burst). Requires a debug build serving `test_runs`. |
@@ -236,10 +237,16 @@ All device-specific logic lives behind the `DeviceTransport` interface (`src/sha
236
237
  ## Security
237
238
 
238
239
  * **No TCP port on device.** Uses platform-specific local sockets, only reachable via port forwarding. Requires physical USB or explicit debug pairing.
239
- * **Per-user device token.** The first Radar process that needs the token (MCP or dashboard) mints it at `~/.slack-radar/radar-token`, mode 0600, one per OS user, and every enable hands it to the device in the enable broadcast. Every request then carries it as `X-Radar-Token`. A device build with the token check answers 401 to anything else; older device builds ignore the extra and stay in open mode without saying so.
240
+ * **Per-user device token.** The first Radar process that needs the token (MCP or dashboard) mints it at `~/.slack-radar/radar-token`, mode 0600, one per OS user. Every request carries it as `X-Radar-Token`; a device build with the token check answers 401 to anything else. How an enable hands it to the device:
241
+ * First Radar checks `ps` for a debug build running as the target Android user. Nothing running there: nothing is written or sent, and the enable fails with "no debug build of the Slack app is running in Android user N; open it there and retry" (just "...is running; open it and retry" when ps saw no build and no user was asked for), from `/radar-enable`, `activate_for_user` and the dashboard alike. Open Slack in that profile first; `activate_for_user` only picks the profile, it cannot start the app.
242
+ * File path (the default): the token goes over stdin with `run-as` into the app's private `files/slack-radar/enable-token` (mode 0600), then `slack.debug.ENABLE_RADAR_TOKEN_FILE` is sent with no token extra; the app reads and deletes the file inside the broadcast. This path keeps the token off every command line.
243
+ * Argv fallback, the old `ENABLE_RADAR --es radar_token` enable, visible in `ps` and adbd's log while it runs, when a debug build is running (or `ps` could not tell) and one of these holds:
244
+ * the `run-as` write failed, timed out or printed no `written` verdict (the build is not debuggable in that profile, or this adb cannot run `run-as --user`); Radar removes anything that landed first. The device's ping says nothing about this case: `token_file: true` only means the build has the action;
245
+ * the file was still there after the broadcast: the build predates the action, or the app failed to delete it; Radar removes it, checks `ps` once more, and sends nothing if the app has stopped meanwhile. The enable result (`_radar_session_enable`, `activate_for_user`) carries `token_via_argv` with the reason when the token rode argv; the key is absent when it did not.
246
+ * One argv enable exposes the long-lived token. `token_via_argv` covers only the enable that returned it; a background re-arm (any Radar tool call, the dashboard boot arm) or a dashboard enable can fall back too, and an argv broadcast that fails after `am` ran can still have exposed the token. To check from outside, watch `adb shell ps -A | grep radar_token` during the enable.
240
247
  * What it stops: a browser page that reaches the forwarded port (DNS rebinding, or any page you visit), and another app on the device connecting to the abstract socket. Neither can read your `~/.slack-radar`.
241
- * What it does not stop: anything with adb access. The adb server on `127.0.0.1:5037` has no auth, so any local process can send a tokenless enable and put the device back in open mode, read the token from host or device `ps` while the broadcast runs, or read it off the debuggable app with `run-as`. Processes running as you can read the file. The token keeps honest sessions apart; it does not lock out adb.
242
- * Open mode is deliberate: an enable with no `radar_token` extra (an older Radar MCP or dashboard, or a hand-typed `am broadcast`) turns the check off so older builds keep working. The MCP warns on every enable result and every `ping` that finds the device in open mode. The dashboard does not warn.
248
+ * What it does not stop: anything with adb access. The adb server on `127.0.0.1:5037` has no auth, so any local process can send a tokenless `ENABLE_RADAR` and put the device back in open mode, read the private token file with `run-as` in the moment before the app consumes it, or see the token in host or device `ps` during an argv fallback. Processes running as you can read the host file. The token keeps honest sessions apart; it does not lock out adb.
249
+ * Open mode is deliberate: an `ENABLE_RADAR` broadcast with no `radar_token` extra (an older Radar MCP or dashboard, or a hand-typed `am broadcast`) turns the check off so older builds keep working. `ENABLE_RADAR_TOKEN_FILE` never opens a tokenless session: a refused file is logged and the session kept as it was, and a build that predates the action drops the broadcast. The MCP warns on every enable result and every `ping` that finds the device in open mode. The dashboard does not warn.
243
250
  * The token is never logged and never appears in an error. A failed broadcast reports adb's exit code and the first line of its stderr, with any token-shaped text redacted.
244
251
  * The file is never replaced on a 401. Delete it only when a message says the file itself is unusable; then re-enable every other Radar session so they pick up the new one.
245
252
  * Known limit: the dashboard forwards every device route (`/api`, `/flags`, `/backfill`, `/detail`) to the device with the token attached. Reads need only a local Host header; writes need an `X-Radar-Dashboard: 1` header or a JSON Content-Type. Any local process can send all of these, so while a dashboard runs, any local process reaches the device through it, writes included. Stop the dashboard when you are not using it.
@@ -263,7 +270,7 @@ What gets captured depends on the in-app server implementation. The MCP server i
263
270
  * **Test runs**: Made-up RTM replay frames sent to the app's handler. The device keeps the last ten run summaries, with settled counts and per-type timings.
264
271
  * **SQLite database** (Database tab, web dashboard only): when you open a database, a read-only **plaintext** copy of that on-device store (message text, request/response bodies, user/channel/team IDs) is pulled to a temp directory **on your own machine** (`os.tmpdir()/slack-radar-db-<port>`, files mode 0600). Auto-deleted when the dashboard process stops.
265
272
  * **SharedPreferences** (`list_prefs`/`get_prefs`/`search_prefs`, and the Preferences tab): read directly off the device over `adb`, no local copy written. Files can contain feature flag overrides, cached team/org/channel IDs, and other app state.
266
- * **Feature flags** (`list_feature_flags`/`search_feature_flags`/`get_feature_flag`): read directly off the device over `adb`, no local copy written. Shows every flag's live effective value and whether it is locally overridden.
273
+ * **Feature flags** (`list_feature_flags`/`search_feature_flags`/`get_feature_flag`): read directly off the device over `adb`, no local copy written. Shows every flag's latest effective value, the flag's own value fixed for this session where the build reports it, and whether it is locally overridden.
267
274
 
268
275
  The network, RTM, clog, and trace captures are in-memory ring buffers. The Database tab is the exception: it writes a plaintext copy of the selected on-device database to a temp file on your host for the duration of the session. Review before sharing anything from it.
269
276
 
@@ -355,7 +362,7 @@ An older Radar MCP or dashboard, or a manual `am broadcast`, enabled the device
355
362
  Another Radar session enabled the device after you did: another machine or OS user, a session using a token file you deleted, or Radar enabled in a different profile. Stop that session, or run `/radar-enable` in it so it picks up the new file, or make sure the Slack debug build runs in the profile you want (`list_profiles` shows which do), then run `/radar-enable` here (on the dashboard, press Reconnect). Deleting `~/.slack-radar/radar-token` never fixes this.
356
363
 
357
364
  **Devices with more than one user (e.g. a work profile)**
358
- The MCP server auto-detects the Android user ID via `ps` and targets the broadcast accordingly. No manual `--user` flag needed. In the dashboard's Logs tab, the package filter narrows logcat to the Slack app; clear the chip or pick another package to widen it.
365
+ The MCP server auto-detects the Android user ID via `ps` and targets the broadcast accordingly. No manual `--user` flag needed while `ps` finds the app running in that profile; open it there first, and use `activate_for_user` when `ps` cannot tell. When Slack debug builds run in several profiles, `SLACK_RADAR_DEBUG_PACKAGE` wins in every one. Unset, an enable arms the build the last enable chose (`com.Slack.internal.debug` on the first enable) wherever it runs, a non-zero profile first, and takes another shipped debug build only when that preferred one runs in no profile. Re-arms stay on the build the enable armed, and `activate_for_user` arms another profile. In the dashboard's Logs tab, the package filter narrows logcat to the Slack app; clear the chip or pick another package to widen it.
359
366
 
360
367
  **Tools not appearing after setup**
361
368
  Restart your Claude Code session. MCP servers are registered at session start.
@@ -1,6 +1,16 @@
1
1
  export interface DashboardHealthIdentity {
2
2
  platform?: string;
3
3
  device_serial?: string | null;
4
+ log_package?: string;
5
+ device?: boolean;
4
6
  }
5
7
  /** Whether an existing dashboard process belongs to this MCP transport and selected device. */
6
8
  export declare function dashboardMatchesDevice(platform: string, selectedSerial: string | null | undefined, health: DashboardHealthIdentity): boolean;
9
+ /**
10
+ * Error text when a running dashboard reads a different Slack debug build than this armed MCP,
11
+ * else null. Unarmed, the MCP has no fresher answer than the dashboard (a human-launched one may
12
+ * have detected its own build), and a dashboard that does not report log_package is older. A dashboard
13
+ * that could not see the socket has no build to be wrong about, and its next poll adopts the owner,
14
+ * but only a shipped id: an override build is never adopted, so that case is refused as before.
15
+ */
16
+ export declare function dashboardDebugPackageError(armed: boolean, ourPackage: string, health: DashboardHealthIdentity): string | null;
@@ -1,3 +1,4 @@
1
+ import { DEBUG_PACKAGE_ENV, SHIPPED_DEBUG_PACKAGES } from "../shared/constants.js";
1
2
  /** Whether an existing dashboard process belongs to this MCP transport and selected device. */
2
3
  export function dashboardMatchesDevice(platform, selectedSerial, health) {
3
4
  // A dashboard started before /health carried `platform` (1.21.0 and earlier) is Android-only,
@@ -9,3 +10,22 @@ export function dashboardMatchesDevice(platform, selectedSerial, health) {
9
10
  }
10
11
  return true;
11
12
  }
13
+ /**
14
+ * Error text when a running dashboard reads a different Slack debug build than this armed MCP,
15
+ * else null. Unarmed, the MCP has no fresher answer than the dashboard (a human-launched one may
16
+ * have detected its own build), and a dashboard that does not report log_package is older. A dashboard
17
+ * that could not see the socket has no build to be wrong about, and its next poll adopts the owner,
18
+ * but only a shipped id: an override build is never adopted, so that case is refused as before.
19
+ */
20
+ export function dashboardDebugPackageError(armed, ourPackage, health) {
21
+ if (!armed || !health.log_package || health.log_package === ourPackage)
22
+ return null;
23
+ if (health.device !== true && SHIPPED_DEBUG_PACKAGES.includes(ourPackage))
24
+ return null;
25
+ // A restart adopts the armed build at boot, but only for a shipped id; any other id came from
26
+ // an override, so the restarted dashboard needs it in its own environment.
27
+ const restart = SHIPPED_DEBUG_PACKAGES.includes(ourPackage)
28
+ ? "Restart the dashboard or use a separate SLACK_RADAR_WEB_PORT."
29
+ : `Restart the dashboard with ${DEBUG_PACKAGE_ENV}=${ourPackage} in its environment, or use a separate SLACK_RADAR_WEB_PORT.`;
30
+ return `The dashboard reads ${health.log_package} but this session armed ${ourPackage}. ${restart}`;
31
+ }
@@ -0,0 +1,5 @@
1
+ export declare function createDebugPackageReset(currentPackage: () => string, reset: () => void, startSpool: () => void): {
2
+ check: () => void;
3
+ startSpool(): void;
4
+ forget(): void;
5
+ };
@@ -0,0 +1,28 @@
1
+ // Session data (ring buffers, the event spool, cached flags) belongs to one Slack debug build.
2
+ // A re-enable or profile switch on the same device can land on another build, whose event ids restart from zero
3
+ // and would collide with the old ones in the spool's have-set. Kept out of index.ts (which
4
+ // connects stdio at load) so it is testable; the effects are injected. Only the enable and the
5
+ // profile switch check; a re-arm targets the held build and never lands here.
6
+ export function createDebugPackageReset(currentPackage, reset, startSpool) {
7
+ let held = null;
8
+ // Reads the package at call time, never captured, since an arm can change it.
9
+ const check = () => {
10
+ const pkg = currentPackage();
11
+ if (held !== null && held !== pkg)
12
+ reset();
13
+ held = pkg;
14
+ };
15
+ return {
16
+ check,
17
+ // The enable's spool start: reset first, so the spool opens on a fresh file and the backfill
18
+ // that follows builds its have-set from it.
19
+ startSpool() {
20
+ check();
21
+ startSpool();
22
+ },
23
+ // A device switch already resets everything, so the next arm must not reset twice.
24
+ forget() {
25
+ held = null;
26
+ },
27
+ };
28
+ }
@@ -17,6 +17,8 @@ export interface FeatureFlagRow {
17
17
  enabled?: boolean | string;
18
18
  group_name?: string;
19
19
  is_overridden?: boolean;
20
+ session_enabled?: boolean | string;
21
+ restart_note?: string;
20
22
  org_id?: string;
21
23
  timestamp?: number;
22
24
  }
@@ -54,7 +54,21 @@ function wellFormedRows(response) {
54
54
  return [];
55
55
  return raw
56
56
  .filter((f) => typeof f === "object" && f !== null && typeof f.key === "string")
57
- .map(dropEmptyOrg);
57
+ .map(dropEmptyOrg)
58
+ .map(withRestartNote);
59
+ }
60
+ // A flag the app read once keeps that value until restart, so `enabled` (latest or override) can
61
+ // differ from what the app runs. Only two real booleans that differ earn a note: an absent or
62
+ // non-boolean session_enabled is "not known", and saying nothing there is the honest answer.
63
+ function withRestartNote(f) {
64
+ // Dropped first so a device that sent its own note cannot pass it through: only this function
65
+ // writes it, and only for a real mismatch.
66
+ const { restart_note: _dropped, ...row } = f;
67
+ const { enabled, session_enabled: session } = row;
68
+ if (typeof enabled !== "boolean" || typeof session !== "boolean" || enabled === session)
69
+ return row;
70
+ const source = isOverridden(f) ? "override" : "fetched";
71
+ return { ...row, restart_note: `app uses ${session} until restart, ${source} ${enabled}` };
58
72
  }
59
73
  // An empty org id means the same thing as no org id, so it is dropped rather than treated as a
60
74
  // distinct org a caller could match or that an error message would render as a blank name. Same
package/dist/mcp/index.js CHANGED
@@ -9,10 +9,11 @@ import os from "os";
9
9
  import path from "path";
10
10
  import { fileURLToPath } from "url";
11
11
  import { AndroidTransport } from "../shared/android.js";
12
+ import { BareEnableError, tokenViaArgvField } from "../shared/enable-diagnosis.js";
12
13
  import { IosSimulatorTransport } from "../shared/ios.js";
13
14
  import { WebappTransport } from "../shared/webapp.js";
14
15
  import { webChildEnv } from "./web-child-env.js";
15
- import { RADAR_HOST, RADAR_PORT, RADAR_VERSION, WEB_PORT_DEFAULT, WEBAPP_DEFAULT_PORT, setRadarPort, } from "../shared/constants.js";
16
+ import { RADAR_HOST, RADAR_PORT, RADAR_VERSION, WEB_PORT_DEFAULT, WEBAPP_DEFAULT_PORT, slackDebugPackage, resetSlackDebugPackage, setRadarPort, } from "../shared/constants.js";
16
17
  import { dashboardPlatformError, decidePlatform, pingLooksLikeWebappRadar, quickAndroidDeviceState, unsupportedCapabilityError, } from "./platform-detect.js";
17
18
  import { stopCapture } from "../shared/logcat-capture.js";
18
19
  import { getSpoolFilePath, epochFromSpoolPath, initializeSpoolDir, readSpool, startSpool, stopSpool, writeFrame, registerCleanup as registerSpoolCleanup, } from "../shared/event-spool.js";
@@ -27,6 +28,7 @@ import { resolveDetailById } from "./session-detail.js";
27
28
  import { decorateToolResult } from "./network-detail.js";
28
29
  import { createEnabler } from "./session-enable.js";
29
30
  import { applyEnableOutcome, clearSources, sourceGate } from "./sources-gate.js";
31
+ import { createDebugPackageReset } from "./debug-package-reset.js";
30
32
  import { computeDispatch } from "./dispatch.js";
31
33
  import { backfillSpool, BACKFILL_SOURCES, makeSerializedRunner, } from "./session-backfill.js";
32
34
  import { handleListDatabases, handleListTables, handleQueryDatabase, } from "./db-tools.js";
@@ -34,9 +36,9 @@ import { handleListPrefs, handleGetPrefs, handleSearchPrefs, } from "./prefs-too
34
36
  import { listFeatureFlags, searchFeatureFlags, getFeatureFlag, normalizeOverriddenArg, createFeatureFlagsCache, } from "./flags-tools.js";
35
37
  import { cleanupPulledDatabases, initializeDatabasePath, resetDbState, } from "../shared/db.js";
36
38
  import { TOOL_DEFINITIONS, serverInstructions, sessionGate } from "./tools.js";
37
- import { dashboardMatchesDevice } from "./dashboard-identity.js";
39
+ import { dashboardDebugPackageError, dashboardMatchesDevice } from "./dashboard-identity.js";
38
40
  import { buildApiPath } from "./api-paths.js";
39
- import { dispatchExportSwitchboardSession, handleGetSwitchboardSession, handleGetSwitchboardSessions, shouldExportSwitchboardOffline, } from "./switchboard-tools.js";
41
+ import { dispatchExportSwitchboardSession, handleGetSwitchboardSession, handleGetSwitchboardSessions, sessionDisabledLine, shouldExportSwitchboardOffline, } from "./switchboard-tools.js";
40
42
  import { getSpoolSwitchboardRecords, markSwitchboardSpoolCleared, newestSpoolSwitchboardSessionId } from "./switchboard-spool.js";
41
43
  import { nonNegativeIntArg, SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES, SWITCHBOARD_EXPORT_IDLE_MS, SWITCHBOARD_EXPORT_OVERALL_MS } from "../shared/switchboard.js";
42
44
  import { unauthorizedResponse } from "./radar-response.js";
@@ -169,7 +171,7 @@ function getSpecTitle() {
169
171
  req.end();
170
172
  });
171
173
  }
172
- async function openDashboardSpec(device, spec) {
174
+ async function openDashboardSpec(device, spec, armed) {
173
175
  const cold = !(await webAlive());
174
176
  if (cold) {
175
177
  // Seed the spec into the spawned server so it is the startup writer and the browser's
@@ -190,6 +192,11 @@ async function openDashboardSpec(device, spec) {
190
192
  if (!dashboardMatchesDevice(device.platform, selected, health)) {
191
193
  throw new Error("The dashboard port belongs to a different platform or device. Use a separate SLACK_RADAR_WEB_PORT.");
192
194
  }
195
+ const packageError = device.platform === "android"
196
+ ? dashboardDebugPackageError(armed, slackDebugPackage(), health)
197
+ : null;
198
+ if (packageError)
199
+ throw new Error(packageError);
193
200
  // A dashboard keeps the version it started with, so read its version on both the cold and warm paths.
194
201
  const fingerprint = await readDashboardFingerprint(WEB_BASE);
195
202
  const r = await postSpec(spec);
@@ -417,6 +424,8 @@ async function runMcpServer() {
417
424
  return device.reassertForward?.() ?? device.ensureForward();
418
425
  }
419
426
  const REARM_BUDGET_MS = 30_000;
427
+ // Counts recovery re-arms so requests that fail together (a backfill fans out five) share one.
428
+ let recoveryRearms = 0;
420
429
  async function callRadar(requestPath, init = {}) {
421
430
  if (!device.supportsRadarHttpTools) {
422
431
  return {
@@ -448,6 +457,7 @@ async function runMcpServer() {
448
457
  };
449
458
  const mismatch = (response) => unauthorizedResponse(response, device);
450
459
  device.activate(device.getTimeoutMinutes());
460
+ const rearmsAtSend = recoveryRearms;
451
461
  try {
452
462
  return mismatch(await requestFromVerifiedPeer());
453
463
  }
@@ -459,17 +469,28 @@ async function runMcpServer() {
459
469
  device.resetState();
460
470
  return { error: `${REQUEST_LOST_PREFIX}${error.message}. Call again.`, request_lost: true };
461
471
  }
462
- device.resetState();
463
- destroyStream();
464
- if (!device.ensureForward()) {
465
- sessionEnabled = false;
466
- return {
467
- error: "Device not connected or radar not running. Session disabled. Use /radar-enable to reconnect.",
468
- };
472
+ // A sibling request already re-armed since this one went out; a second broadcast would only restart it.
473
+ if (recoveryRearms === rearmsAtSend) {
474
+ device.resetState();
475
+ destroyStream();
476
+ if (!device.ensureForward()) {
477
+ sessionEnabled = false;
478
+ return {
479
+ error: "Device not connected or radar not running. Session disabled. Use /radar-enable to reconnect.",
480
+ };
481
+ }
482
+ // The re-arm is a fresh claim on the device, so a refusal from before it is stale.
483
+ clearStreamRejected();
484
+ recoveryRearms++;
469
485
  }
486
+ // Also for a skipper: a no-op on an armed device, its own try if the sibling's arm failed.
487
+ // When that try is the one that lands, it is the re-arm, so the refusal it leaves behind is stale too.
488
+ const armFailedBefore = Boolean(device.getLastActivateError?.());
470
489
  device.activate(device.getTimeoutMinutes());
471
- // The re-arm is a fresh claim on the device, so a refusal from before it is stale.
472
- clearStreamRejected();
490
+ if (armFailedBefore && !device.getLastActivateError?.()) {
491
+ destroyStream();
492
+ clearStreamRejected();
493
+ }
473
494
  try {
474
495
  return mismatch(await requestFromVerifiedPeer());
475
496
  }
@@ -478,9 +499,7 @@ async function runMcpServer() {
478
499
  if (init.reportLost && e2.message === REQUEST_TIMED_OUT)
479
500
  return { error: `${REQUEST_LOST_PREFIX}${e2.message}. Call again.`, request_lost: true };
480
501
  sessionEnabled = false;
481
- return {
482
- error: `Radar not responding: ${e2.message}. Session disabled. Use /radar-enable to reconnect.`,
483
- };
502
+ return { error: sessionDisabledLine(device, `Radar not responding: ${e2.message}.`) };
484
503
  }
485
504
  }
486
505
  }
@@ -530,6 +549,16 @@ async function runMcpServer() {
530
549
  };
531
550
  }
532
551
  // --- Tool handlers ---
552
+ // Not stopCapture (logcat is device-wide) and not cleanupPulledDatabases (pulled file names
553
+ // already carry the package).
554
+ const debugPackageReset = createDebugPackageReset(() => slackDebugPackage(), () => {
555
+ // Both callers run with a session that is, or is about to be, enabled, so the spool reopens.
556
+ stopSpool();
557
+ startSpool();
558
+ clearLocalBuffers();
559
+ clearSources();
560
+ featureFlagsCache.clear();
561
+ }, startSpool);
533
562
  async function handleSessionEnable(args) {
534
563
  const deviceSerial = args?.device_serial || null;
535
564
  // The enabler owns the choice, counters and flag updates without starting stdio.
@@ -542,7 +571,9 @@ async function runMcpServer() {
542
571
  isStreamConnected,
543
572
  wasStreamRejected,
544
573
  resetDbState,
545
- startSpool,
574
+ // After the arm and before the backfill: the spool reopens fresh and the backfill's have-set
575
+ // is built from the new file.
576
+ startSpool: () => debugPackageReset.startSpool(),
546
577
  runBackfill: runBackfillSerialized,
547
578
  // A health ping does not need the default 10s: a half-alive server
548
579
  // (accepts TCP, never answers) would otherwise stretch the verify loop
@@ -551,9 +582,16 @@ async function runMcpServer() {
551
582
  // under that ceiling.
552
583
  ping: () => peerPing(),
553
584
  sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
585
+ onForeignOwnerAfterBackfill: () => {
586
+ debugPackageReset.forget();
587
+ // The backfill filled the rings from the foreign build too.
588
+ clearLocalBuffers();
589
+ stopSpool();
590
+ },
554
591
  // Only fires on a switch to a different device: the prior device's buffers,
555
592
  // spool, capture, and pulled DBs are stale for the new hardware.
556
593
  onDeviceSwitch: () => {
594
+ debugPackageReset.forget();
557
595
  clearLocalBuffers();
558
596
  // Closing the spool is also what keeps the old device's switchboard records out of
559
597
  // export_switchboard_session's device-free fallback.
@@ -563,6 +601,8 @@ async function runMcpServer() {
563
601
  // The old device's declared sources and cached flags do not describe the new one.
564
602
  clearSources();
565
603
  featureFlagsCache.clear();
604
+ // The new device may run a different Slack debug build; the next arm re-detects it.
605
+ resetSlackDebugPackage();
566
606
  },
567
607
  };
568
608
  const outcome = await enabler.enable(args?.timeout_minutes, deviceSerial, deps);
@@ -671,6 +711,8 @@ async function runMcpServer() {
671
711
  const timeout = args?.timeout_minutes || device.getTimeoutMinutes() || 5;
672
712
  clearRadarTokenCache();
673
713
  enabler.switchProfile(() => activateForUser.call(device, args.user_id, timeout));
714
+ // The switch can land on another build; reset before its frames reach the old buffers.
715
+ debugPackageReset.check();
674
716
  // Restart the SSE stream so network/RTM/clog events from the newly
675
717
  // activated profile start flowing again.
676
718
  destroyStream();
@@ -684,12 +726,13 @@ async function runMcpServer() {
684
726
  return textResult({
685
727
  user_id: args.user_id,
686
728
  timeout_minutes: timeout,
729
+ ...tokenViaArgvField(device),
687
730
  capture_file: device.getCaptureFilePath?.() ?? null,
688
731
  note: "Profile activated. Log capture restarted on a new file; old capture preserved for 7 days.",
689
732
  });
690
733
  }
691
734
  catch (e) {
692
- return textResult({ error: e instanceof TokenFileError ? tokenFileMessage(e, "profile") : `Profile activation failed: ${e.message}. Is the device connected? Check adb devices.` }, true);
735
+ return textResult({ error: e instanceof TokenFileError ? tokenFileMessage(e, "profile") : e instanceof BareEnableError ? e.message : `Profile activation failed: ${e.message}. Is the device connected? Check adb devices.` }, true);
693
736
  }
694
737
  }
695
738
  async function handleCaptureSnapshot(args) {
@@ -812,18 +855,25 @@ async function runMcpServer() {
812
855
  const result = await callRadar("/api/clear");
813
856
  return textResult(result, !!result.error);
814
857
  }
858
+ function dashboardUrlField() {
859
+ return dashboardPlatformError(device) ? {} : { dashboard_url: WEB_BASE };
860
+ }
815
861
  async function handlePing(args) {
816
862
  if (args?.timeout_minutes) {
817
863
  device.activate(args.timeout_minutes);
818
864
  const tokenFileError = device.getLastActivateTokenFileError?.();
819
- if (tokenFileError)
820
- return textResult({ error: tokenFileError.message, mcp_version: RADAR_VERSION }, true);
865
+ if (tokenFileError) {
866
+ return textResult({ error: tokenFileError.message, mcp_version: RADAR_VERSION, ...dashboardUrlField() }, true);
867
+ }
821
868
  }
822
869
  const result = await callRadar("/api/ping");
823
870
  // Version is a property of this process, not the device, so it is reported
824
871
  // even when the device probe fails — the error path is exactly when a
825
872
  // reviewer needs to correlate a report against a known-bad release.
826
873
  result.mcp_version = RADAR_VERSION;
874
+ // Same reasoning: the dashboard address comes from this process's port setting, so it is
875
+ // reported even when the device is down. It says where the dashboard lives, not whether it runs.
876
+ Object.assign(result, dashboardUrlField());
827
877
  if (!result.error) {
828
878
  result.stream_connected = isStreamConnected();
829
879
  result.local_network_buffer = localNetworkBuffer.length;
@@ -850,7 +900,7 @@ async function runMcpServer() {
850
900
  // The web server runs its own coerce+validate on /setspec, so a thin pass of
851
901
  // the authored args is enough; a bad spec comes back as an HTTP 400 with its
852
902
  // reason, which we surface verbatim rather than rendering silent zeros.
853
- const out = await openDashboardSpec(device, args);
903
+ const out = await openDashboardSpec(device, args, sessionEnabled);
854
904
  return textResult(buildOpenDashboardResult({ ...out, title: out.title ?? args.title }, out.fingerprint, RADAR_VERSION, WEB_BASE));
855
905
  }
856
906
  catch (e) {
@@ -861,7 +911,7 @@ async function runMcpServer() {
861
911
  }
862
912
  }
863
913
  // --- MCP Server ---
864
- const server = new Server({ name: "slack-radar", version: "1.23.0" }, { capabilities: { tools: {} }, instructions: serverInstructions(device.platform) });
914
+ const server = new Server({ name: "slack-radar", version: "1.24.0" }, { capabilities: { tools: {} }, instructions: serverInstructions(device.platform) });
865
915
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
866
916
  tools: TOOL_DEFINITIONS,
867
917
  }));
@@ -23,8 +23,10 @@ export function radarHttpRequest({ host, port, path, method = "GET", body, timeo
23
23
  clearTimeout(overallTimer);
24
24
  reject(error);
25
25
  };
26
+ // agent: false so no request rides a pooled socket the device already closed; that reads as
27
+ // a dead device (ECONNRESET) and costs a re-arm.
26
28
  const req = http.request({
27
- host, port, path, method, timeout: timeoutMs,
29
+ host, port, path, method, timeout: timeoutMs, agent: false,
28
30
  headers: {
29
31
  ...radarTokenHeaderFor(transport),
30
32
  ...(body === undefined ? {} : {
@@ -12,6 +12,7 @@ export interface EnableDeps {
12
12
  ping: () => Promise<Record<string, unknown>>;
13
13
  sleep: (ms: number) => Promise<void>;
14
14
  onDeviceSwitch: () => void;
15
+ onForeignOwnerAfterBackfill?: () => void;
15
16
  }
16
17
  export interface EnableOutcome {
17
18
  body: Record<string, unknown>;
@@ -8,7 +8,7 @@
8
8
  // an adb-level broadcast failure (previously swallowed entirely), and a broadcast
9
9
  // that exits 0 with no receiver (radar modules missing, wrong profile), which the
10
10
  // old code reported as enabled:true with a failing ping.
11
- import { deviceServerSilentError, readProcessState, } from "../shared/enable-diagnosis.js";
11
+ import { deviceServerSilentError, foreignRadarOwnerMessage, readProcessState, tokenViaArgvField, } from "../shared/enable-diagnosis.js";
12
12
  import { ENABLE_PING_WAITS_MS } from "../shared/constants.js";
13
13
  import { clearRadarTokenCache, openModeWarningAfterEnable, tokenFileMessage, unauthorizedMessageFor, } from "../shared/radar-token.js";
14
14
  // The device answered the ping with HTTP 401: the token is refused, the app is not down.
@@ -30,6 +30,16 @@ async function verifiedPing(device, ping) {
30
30
  }
31
31
  return status;
32
32
  }
33
+ function foreignOwnerOutcome(device, owner) {
34
+ return {
35
+ enabled: false,
36
+ body: {
37
+ error: foreignRadarOwnerMessage(device.logPackage ?? "the armed build", owner),
38
+ enabled: false,
39
+ platform: device.platform,
40
+ },
41
+ };
42
+ }
33
43
  function isArmed(status) {
34
44
  return status.http_status === undefined && (status.status === "ok" || status.ok === true);
35
45
  }
@@ -140,6 +150,9 @@ export async function refreshEnabledSession(timeoutMinutes, deviceSerial, deps)
140
150
  const activeUserId = device.getActiveUserId?.();
141
151
  if (status.android_user_id != null && activeUserId != null && String(status.android_user_id) !== String(activeUserId))
142
152
  return null;
153
+ // Another build holding the socket answers healthy, so only the full flow can refuse it.
154
+ if (device.foreignRadarOwner?.(status) != null)
155
+ return null;
143
156
  // The caller starts the capture after confirming the session is still current.
144
157
  return {
145
158
  enabled: true,
@@ -172,6 +185,8 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
172
185
  // always reset for the same reason; the MCP path was missing it.
173
186
  destroyStream();
174
187
  device.resetState();
188
+ // A fresh enable decides the build again, so drop the one a past arm held.
189
+ device.releaseDebugBuild?.();
175
190
  // A re-enable may be a different device or a re-armed profile, so drop the cached DB
176
191
  // user set + sqlite path; the next DB tool call re-detects the profiles fresh.
177
192
  resetDbState();
@@ -285,11 +300,7 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
285
300
  };
286
301
  }
287
302
  if (activateError) {
288
- // The broadcast failed at the adb level. The device server may STILL be alive
289
- // (armed by a prior session, or the broadcast timed out on a loaded device
290
- // after landing), so probe before failing: a working server beats a pedantic
291
- // error, and a dead one gets a real error instead of the old silent
292
- // enabled:true + failing tools.
303
+ // A prior server may still answer despite the failed enable.
293
304
  try {
294
305
  await verifiedPing(device, ping);
295
306
  }
@@ -297,7 +308,7 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
297
308
  return {
298
309
  enabled: false,
299
310
  body: {
300
- error: error instanceof PingRefused
311
+ error: device.getLastActivateBareError?.() ? activateError : error instanceof PingRefused
301
312
  ? `Radar activation broadcast failed: ${activateError}. ${unauthorizedMessageFor(device)}`
302
313
  : device.radarListenerHint
303
314
  ? `Radar activation failed: ${activateError}. ${device.radarListenerHint}`
@@ -308,6 +319,23 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
308
319
  };
309
320
  }
310
321
  }
322
+ // The broadcast cannot move a socket another build already holds. Ask before any spool or
323
+ // stream work so nothing is written under the wrong build. No answer yet is fine, the verify
324
+ // loop below asks again.
325
+ if (device.foreignRadarOwner) {
326
+ let early = null;
327
+ try {
328
+ early = await ping();
329
+ }
330
+ catch {
331
+ // Nothing bound yet.
332
+ }
333
+ const owner = early ? device.foreignRadarOwner(early) : null;
334
+ if (owner !== null) {
335
+ destroyStream();
336
+ return foreignOwnerOutcome(device, owner);
337
+ }
338
+ }
311
339
  // Open the session event spool, then backfill the device rings into it. The live
312
340
  // SSE push can start DURING the backfill (the backfill pulls via the injected
313
341
  // fetch, which opens the stream on its first call), so the trailing
@@ -325,10 +353,18 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
325
353
  // declaring it dead.
326
354
  let status = null;
327
355
  let saw401 = false;
356
+ let foreignOwner = null;
328
357
  for (const waitMs of ENABLE_PING_WAITS_MS) {
329
358
  await sleep(waitMs);
330
359
  try {
331
- status = await verifiedPing(device, ping);
360
+ const answer = await verifiedPing(device, ping);
361
+ // A foreign owner does not go away by waiting, so stop at once.
362
+ foreignOwner = device.foreignRadarOwner?.(answer) ?? null;
363
+ if (foreignOwner === null) {
364
+ status = answer;
365
+ // Holds the build that answered even when this enable's own broadcast failed.
366
+ device.adoptRadarOwner?.(answer);
367
+ }
332
368
  break;
333
369
  }
334
370
  catch (error) {
@@ -336,6 +372,11 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
336
372
  saw401 = true;
337
373
  }
338
374
  }
375
+ if (foreignOwner !== null) {
376
+ destroyStream();
377
+ deps.onForeignOwnerAfterBackfill?.();
378
+ return foreignOwnerOutcome(device, foreignOwner);
379
+ }
339
380
  if (status === null) {
340
381
  destroyStream();
341
382
  if (saw401) {
@@ -345,6 +386,7 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
345
386
  error: unauthorizedMessageFor(device),
346
387
  enabled: false,
347
388
  platform: device.platform,
389
+ ...tokenViaArgvField(device),
348
390
  },
349
391
  };
350
392
  }
@@ -361,6 +403,7 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
361
403
  error,
362
404
  enabled: false,
363
405
  platform: device.platform,
406
+ ...tokenViaArgvField(device),
364
407
  },
365
408
  };
366
409
  }
@@ -392,6 +435,7 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
392
435
  }
393
436
  : {}),
394
437
  ...status,
438
+ ...tokenViaArgvField(device),
395
439
  ...(openModeWarning ? { warning: openModeWarning } : {}),
396
440
  },
397
441
  };
@@ -1,4 +1,5 @@
1
1
  import type { RadarTokenSender } from "../shared/radar-token.js";
2
+ import type { DeviceTransport } from "../shared/transport.js";
2
3
  import { type SwitchboardExportGet } from "../shared/switchboard.js";
3
4
  import { type RadarResponse } from "./radar-response.js";
4
5
  export interface HandlerResult {
@@ -10,9 +11,11 @@ export declare const SWITCHBOARD_BUDGET_HINT = "Pass kind or lower limit; for th
10
11
  export declare function handleGetSwitchboardSessions(fetch: RadarFetch): Promise<HandlerResult>;
11
12
  export declare function handleGetSwitchboardSession(args: Record<string, unknown>, fetch: RadarFetch): Promise<HandlerResult>;
12
13
  export declare const SESSION_DISABLED_SUFFIX_LINE = "Session disabled. Use /radar-enable to reconnect.";
14
+ type EnableErrorSource = Partial<Pick<DeviceTransport, "getLastActivateBareError">>;
15
+ export declare function sessionDisabledLine(transport?: EnableErrorSource, fallback?: string): string;
13
16
  export declare const RECONNECT_ONLY_SUFFIX_LINE = "Use /radar-enable to reconnect.";
14
- export declare function appendSessionDisabledSuffix(message: string, sessionJustDisabled: boolean): string;
15
17
  export declare function handleExportSwitchboardSession(args: Record<string, unknown>, get: SwitchboardExportGet, sender: RadarTokenSender, now?: number, exportRoot?: string): Promise<HandlerResult>;
16
18
  export declare function shouldExportSwitchboardOffline(requestedId: number | null, getHostRecords: (sessionId: number) => Record<string, unknown>[], getNewestHostSessionId: () => number | null): boolean;
17
19
  export declare function handleExportSwitchboardSessionOffline(args: Record<string, unknown>, now?: number, exportRoot?: string): HandlerResult;
18
- export declare function dispatchExportSwitchboardSession(args: Record<string, unknown>, isSessionEnabled: () => boolean, get: SwitchboardExportGet, sender: RadarTokenSender, now?: number, exportRoot?: string): Promise<HandlerResult>;
20
+ export declare function dispatchExportSwitchboardSession(args: Record<string, unknown>, isSessionEnabled: () => boolean, get: SwitchboardExportGet, sender: (RadarTokenSender & EnableErrorSource) | undefined, now?: number, exportRoot?: string): Promise<HandlerResult>;
21
+ export {};