@slack/radar-mcp 1.22.0 → 1.23.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
@@ -76,7 +76,7 @@ slack claude mcp add -s user slack-radar-mcp -e SLACK_RADAR_WEB_PORT=8101 -- npx
76
76
 
77
77
  If the server is already added, run `slack claude mcp remove -s user slack-radar-mcp` first, since `add` refuses a name that already exists. In a JSON config the port goes in the server entry's `"env"` object, as `"env": { "SLACK_RADAR_WEB_PORT": "8101" }`.
78
78
 
79
- The native app also updates itself: when a newer version of the package is published, a launch rebuilds it in the background, and the update takes effect the next time you open it. That rebuild keeps the port the app was built with, or uses 8100 when that cannot be read. To change the port, run `install-app` again with the new `SLACK_RADAR_WEB_PORT`.
79
+ The native app also updates itself: when a newer version of the package is published, a launch rebuilds it in the background, and the update takes effect the next time you open it. That rebuild keeps the port the app was built with, or uses 8100 when that cannot be read. To change the port, run `install-app` again with the new `SLACK_RADAR_WEB_PORT`. Use **Check for Updates…** in the app's menu to check and install right away instead of waiting for the next launch.
80
80
 
81
81
  Clicking it starts the dashboard if it is not already running (the server auto-closes about 6 minutes after the last tab closes, so this is the usual case), waits for the port, then shows it. If an older dashboard is still holding the port and nobody is using it, the app asks that one to stop first, so an upgrade does not leave you looking at the version you replaced. Quitting the app stops the dashboard it started, unless a Claude Code session or another window is still using it; a dashboard that was already running when the app launched is never stopped. If Xcode's command line tools are installed (`xcode-select --install`), `install-app` compiles a small native window for this: its own dock icon, its own process, no browser tab, no tab bar. Without a Swift toolchain it falls back to opening your default browser instead.
82
82
 
@@ -122,12 +122,12 @@ Radar starts **disabled** each session. All tools except `ping` return an error
122
122
 
123
123
  | Command | Effect |
124
124
  |---|---|
125
- | `/radar-enable` | Activates ADB forwarding, device broadcast, SSE stream. Tools become available. |
125
+ | `/radar-enable` | Activates ADB forwarding, device broadcast, SSE stream. A repeat on a live session checks the device first and runs the full setup again when that check fails or the last activation did not land, the device, token or profile changed, the timeout changes, or Radar is in open mode. For a clean reset run `/radar-disable`, then `/radar-enable`. |
126
126
  | `/radar-disable` | Tears down stream, clears local buffers. Tools return "not active" error. |
127
127
 
128
- **Auto-enable**: When you ask Claude an obvious device question (clogs, network calls, screenshots, app state, RTM events, logs), Claude invokes `/radar-enable` automatically before calling the relevant tool.
128
+ **Auto-enable**: When you ask Claude an obvious device question (clogs, network calls, screenshots, app state, RTM events, logs), Claude calls the tool first and enables only when a tool says Radar is not active or Session disabled. It enables once without asking and retries. If the enable or the retry fails it tells you and stops. One such answer per fresh session is expected.
129
129
 
130
- **Auto-disable**: When the device-side radar shuts down after idle (default 5 min), the next tool call failure flips the session to disabled. Claude will tell you and offer to re-enable. `export_switchboard_session` still works after this: it builds the report from the live stream copy alone, with no device call, as long as this process streamed the call live. An explicit `/radar-disable` or `clear_buffers` wipes that copy.
130
+ **Auto-disable**: When the device-side radar shuts down after idle (default 5 min), the next tool call failure flips the session to disabled. Claude re-enables once without asking, then retries. If the enable or the retry fails it tells you and stops. `export_switchboard_session` still works after this: it builds the report from the live stream copy alone, with no device call, as long as this process streamed the call live. An explicit `/radar-disable` or `clear_buffers` wipes that copy.
131
131
 
132
132
  ## Tools
133
133
 
@@ -164,11 +164,53 @@ Radar starts **disabled** each session. All tools except `ping` return an error
164
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
165
  | `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
166
  | `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
- | `clear_buffers` | Clear all captured buffers (network, RTM, clog, trace) on the device and locally, and the switchboard copy `export_switchboard_session` falls back to. The session event spool `query_session` reads is kept. |
167
+ | `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`. |
168
+ | `get_test_run` | Read `run_id`, or list the last ten when omitted. Optional `wait_seconds` (max 45) polls until settled. It bounds when the last read may start; every read then gets 3 seconds. |
169
+ | `stop_test_run` | Stop `run_id`. Its counts stay readable with `get_test_run`. |
170
+ | `clear_buffers` | Clear all captured buffers (network, RTM, clog, trace, settled test runs) on the device and locally, and the switchboard copy `export_switchboard_session` falls back to. The session event spool `query_session` reads is kept. |
168
171
  | `open_radar_dashboard` | Author or refine a custom live dashboard tab from a spec (source, filters, widgets, alerts). Suggested when a request is not covered by the pre-built tabs; not auto-invoked. Returns the dashboard URL; debug builds only, local only. |
169
- | `_radar_session_enable` | Enable radar for the session. Called by `/radar-enable` skill. |
172
+ | `_radar_session_enable` | Enable radar for the session. A repeat on a live session checks the device first. |
170
173
  | `_radar_session_disable` | Disable radar for the session. Called by `/radar-disable` skill. |
171
174
 
175
+ ### Test cases
176
+
177
+ Replay frames go into the app's own message handler on the device, not over the socket. Use a quiet workspace and a debug build that serves the `test_runs` source. Open a screen in a signed-in team first.
178
+
179
+ `message_changed` and `message_replied` seed a message, then edit it or update its reply count. Each event carries about 4 KB of made-up text. Both default to `repeat: 100`, `rate_per_second: 10`, so they send 200 frames over about 20 seconds. The rate counts every frame, including the seed. Frames per run = repeat × events.
180
+
181
+ Write custom cases to `~/.slack-radar/test-cases/<name>.json`, then pass the name or name.json. A file named like a built-in replaces it. Names use 1 to 64 letters, digits, underscores or hyphens. The file must be regular, at most 256 KB, and contain an object with an `events` array and a required `rate_per_second` key. Null means burst. Repeat defaults to 1. Call arguments override repeat and rate, including a null rate, but cannot rescue a file missing the rate key.
182
+
183
+ | Placeholder | Device fills it with |
184
+ |---|---|
185
+ | `{{test_channel}}` | The test channel |
186
+ | `{{seq_ts}}` | A run timestamp shared by a seed and its update |
187
+ | `{{frame_ts}}` | A timestamp for each frame |
188
+ | `{{seq_uuid}}` | A client message id shared by a seed and its update |
189
+ | `{{seq}}` | The iteration number |
190
+
191
+ This is a full `message_changed` file with the filler shortened.
192
+
193
+ ```json
194
+ {
195
+ "repeat": 100,
196
+ "rate_per_second": 10,
197
+ "events": [
198
+ {"type":"message","channel":"{{test_channel}}","ts":"{{seq_ts}}","client_msg_id":"{{seq_uuid}}","text":"seed {{seq}}","user":"UZRDR0000001"},
199
+ {"type":"message","subtype":"message_changed","channel":"{{test_channel}}","message":{"ts":"{{seq_ts}}","text":"edit {{seq}}","client_msg_id":"{{seq_uuid}}"}}
200
+ ]
201
+ }
202
+ ```
203
+
204
+ The device accepts only message, message_changed and message_replied frames. Every channel must use `{{test_channel}}`. Timestamp fields must use run timestamps, thread_ts must equal ts, and client_msg_id must use `{{seq_uuid}}`. File ids must be test ids. User can be any id except your signed-in user. Leave out event_ts. The device rejects real channel and timestamp values and unresolved placeholders. Caps are 10,000 frames, 1 to 1,000 frames a second (or null burst), two minutes, 64 MB total UTF-8 template text and a 256 KB request body. Lower repeat does not shrink an oversized request body.
205
+
206
+ After `run_test_case`, call `get_test_run(run_id, wait_seconds)` until `settled` is true. A terminal state alone is not settled. The device waits two quiet seconds after the later of the run's end and its last counted event, and while frames are still pending it holds the run unsettled, at most ten seconds after the end; frames still pending at the cap count as `ignored`. A settling 409's `N ms left` is the quiet time left, or the hold time left once quiet. A frame already in its handler when a flush lands (the app backgrounded) gets a flushed span, which resolves it, so it neither holds the run nor reads as `ignored`; a frame still queued at that moment gets no span, so it holds the run to the ten second cap and reads as `ignored`. A capped wait returns a note to call again. List with no run_id if a run was evicted from the last ten (eleven while one is starting) or `clear_buffers` dropped it.
207
+
208
+ Trust summary only after settle. `ok` and `failed` count handler outcomes. `by_type` has per-type sent, ok, failed, p50_ms, p90_ms, p99_ms and max_ms. Percentiles need 100 counted events per type. Max needs one. Read dotted labels with bracket keys, such as `summary.by_type["MESSAGE.MESSAGE_CHANGED"]`.
209
+
210
+ `elapsed_ms`, `achieved_rate`, `drain_ms`, `held_ms` and `late_sends` are null before terminal. Drain is the last counted event minus the last send, null without an event or for a negative gap. Achieved rate includes the test-channel clear, so it can read low on a short burst. `other_events` counts other types and run types past their cap. `other_failed` means another handler threw. `failed_label` names a failed run type, which stops sending. `flushed` counts flush spans. Stop reasons are requested, time_cap, workspace_gone, run_failed, handler_failed or null. Error can be the cause's class name if its message is null. Sweep rates 10, 50, 100 and 1000 with repeat 100 to compare settled summaries.
211
+
212
+ A 400 names the refused frame with frame_index and template_index (0-based) and seq (1-based). A 409 active names active_run_id to wait for or stop. A 409 settling names milliseconds left to wait before retrying. Stop returns 202 while stopping, 200 once terminal, 404 unknown, or 409 while starting. When the start reply is lost (a resend's own listed-id 409, or a start that was sent and got no answer), the tool reads the run back and returns a listed run; a `starting` one carries a note that its frames are still being checked. A 404 on that read means the device holds no retained run: the frame check refused it, the request never arrived, or a run that did start settled and was then evicted or cleared, so the error says to call `run_test_case` again. A failed read-back says the run may have started: read it with `get_test_run` before starting another, and a 404 there most likely means it never started, so call `run_test_case` again. Builds declaring sources without test_runs are gated. Older builds without sources return the device's route error.
213
+
172
214
  ## Architecture
173
215
 
174
216
  ```
@@ -218,6 +260,7 @@ What gets captured depends on the in-app server implementation. The MCP server i
218
260
  * **RTM events**: WebSocket listener. Ring buffer: 2000 events.
219
261
  * **Clogs**: Analytics interceptor. Ring buffer: 1000 events. Persists across radar activation cycles.
220
262
  * **Traces**: Performance span observer. Ring buffer: 2000 spans. Persists across radar activation cycles.
263
+ * **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.
221
264
  * **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.
222
265
  * **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.
223
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.
package/dist/mcp/index.js CHANGED
@@ -12,20 +12,20 @@ import { AndroidTransport } from "../shared/android.js";
12
12
  import { IosSimulatorTransport } from "../shared/ios.js";
13
13
  import { WebappTransport } from "../shared/webapp.js";
14
14
  import { webChildEnv } from "./web-child-env.js";
15
- import { RADAR_HOST, RADAR_PORT, RADAR_VERSION, WEB_PORT_DEFAULT, WEBAPP_DEFAULT_PORT, MAX_RADAR_RESPONSE_BYTES, setRadarPort, } from "../shared/constants.js";
15
+ import { RADAR_HOST, RADAR_PORT, RADAR_VERSION, WEB_PORT_DEFAULT, WEBAPP_DEFAULT_PORT, setRadarPort, } from "../shared/constants.js";
16
16
  import { dashboardPlatformError, decidePlatform, pingLooksLikeWebappRadar, quickAndroidDeviceState, unsupportedCapabilityError, } from "./platform-detect.js";
17
17
  import { stopCapture } from "../shared/logcat-capture.js";
18
18
  import { getSpoolFilePath, epochFromSpoolPath, initializeSpoolDir, readSpool, startSpool, stopSpool, writeFrame, registerCleanup as registerSpoolCleanup, } from "../shared/event-spool.js";
19
19
  import { connectStream, destroyStream, waitForEvents, clearLocalBuffers, isStreamConnected, wasStreamRejected, clearStreamRejected, localNetworkBuffer, localRtmBuffer, setTransport, setOnReconnect, } from "../shared/stream.js";
20
20
  import { makeCallRadarForExport } from "./radar-export-get.js";
21
21
  import { radarRequestRaw } from "../shared/radar-request-raw.js";
22
- import { TokenFileError, clearRadarTokenCache, openModeWarning, radarTokenHeaderFor, tokenFileMessage, unauthorizedMessageFor } from "../shared/radar-token.js";
22
+ import { TokenFileError, clearRadarTokenCache, openModeWarning, tokenFileMessage, unauthorizedMessageFor } from "../shared/radar-token.js";
23
23
  import { buildBufferPath, createSnapshot } from "./snapshot.js";
24
24
  import { clampLogLimit, shapeLogsResult } from "./logs-result.js";
25
25
  import { querySession, clampByteCap, toNum } from "./session-query.js";
26
26
  import { resolveDetailById } from "./session-detail.js";
27
27
  import { decorateToolResult } from "./network-detail.js";
28
- import { runSessionEnable } from "./session-enable.js";
28
+ import { createEnabler } from "./session-enable.js";
29
29
  import { applyEnableOutcome, clearSources, sourceGate } from "./sources-gate.js";
30
30
  import { computeDispatch } from "./dispatch.js";
31
31
  import { backfillSpool, BACKFILL_SOURCES, makeSerializedRunner, } from "./session-backfill.js";
@@ -39,7 +39,9 @@ import { buildApiPath } from "./api-paths.js";
39
39
  import { dispatchExportSwitchboardSession, handleGetSwitchboardSession, handleGetSwitchboardSessions, shouldExportSwitchboardOffline, } from "./switchboard-tools.js";
40
40
  import { getSpoolSwitchboardRecords, markSwitchboardSpoolCleared, newestSpoolSwitchboardSessionId } from "./switchboard-spool.js";
41
41
  import { nonNegativeIntArg, SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES, SWITCHBOARD_EXPORT_IDLE_MS, SWITCHBOARD_EXPORT_OVERALL_MS } from "../shared/switchboard.js";
42
- import { interpretRadarResponse, responseBudgetError, unauthorizedResponse } from "./radar-response.js";
42
+ import { unauthorizedResponse } from "./radar-response.js";
43
+ import { DEFAULT_TIMEOUT_MS, radarHttpRequest, REQUEST_LOST_PREFIX, REQUEST_TIMED_OUT } from "./radar-http.js";
44
+ import { handleRunTestCase, handleGetTestRun, handleStopTestRun } from "./test-runs-tools.js";
43
45
  import { buildOpenDashboardResult, readDashboardFingerprint } from "./stale-dashboard.js";
44
46
  // --- Subcommand + bin-name dispatch ---
45
47
  // See computeDispatch's own comment (dispatch.ts) for the full front-door table and rationale;
@@ -54,6 +56,10 @@ const wantsSelfHealCheck = wantsInstallApp && process.argv.includes("--self-heal
54
56
  // registry-version precheck that only falls through to --self-heal-check once a real upgrade is
55
57
  // confirmed. Checked before wantsSelfHealCheck below so the two flags stay mutually exclusive.
56
58
  const wantsSelfHealPrecheck = wantsInstallApp && process.argv.includes("--self-heal-precheck");
59
+ // The two interactive halves of the app's Check for Updates... item: ask whether a newer build is
60
+ // published, then install it. Each prints a single JSON line for the app to read.
61
+ const wantsCheckUpdate = wantsInstallApp && process.argv.includes("--check-update");
62
+ const wantsUpdateNow = wantsInstallApp && process.argv.includes("--update-now");
57
63
  // --- Web dashboard bridge (open_radar_dashboard) ---
58
64
  //
59
65
  // The MCP server and the web dashboard are separate processes. open_radar_dashboard
@@ -204,7 +210,15 @@ async function openDashboardSpec(device, spec) {
204
210
  return { ...r.json, fingerprint };
205
211
  }
206
212
  if (wantsInstallApp) {
207
- if (wantsSelfHealPrecheck) {
213
+ if (wantsCheckUpdate) {
214
+ const { checkForUpdate } = await import("../web/install-app.js");
215
+ console.log(JSON.stringify(await checkForUpdate(process.env.RADAR_APP_VERSION)));
216
+ }
217
+ else if (wantsUpdateNow) {
218
+ const { runUpdateNow } = await import("../web/install-app.js");
219
+ await runUpdateNow();
220
+ }
221
+ else if (wantsSelfHealPrecheck) {
208
222
  const { runSelfHealPrecheck } = await import("../web/install-app.js");
209
223
  runSelfHealPrecheck();
210
224
  }
@@ -310,6 +324,14 @@ async function runMcpServer() {
310
324
  // just-ended session stays readable.
311
325
  registerSpoolCleanup();
312
326
  let sessionEnabled = false;
327
+ const enabler = createEnabler({
328
+ isEnabled: () => sessionEnabled,
329
+ setEnabled: (on) => { sessionEnabled = on; },
330
+ applyEnableOutcome,
331
+ clearSources,
332
+ clearStreamRejected,
333
+ log: (line) => console.error(line),
334
+ });
313
335
  // The envelope key each device list route wraps its rows in: /api/network -> {calls}, /api/rtm ->
314
336
  // {events}, /api/clogs -> {clogs}, /api/traces -> {traces}. Read once against the same list routes
315
337
  // buildApiPath pins. Defined here (the impure layer) since it is the device-response shape, not
@@ -380,56 +402,11 @@ async function runMcpServer() {
380
402
  // a truncation marker rather than a partial JSON blob the parser would choke on. Bulk exports go
381
403
  // through capture_snapshot, not this path. The ceiling now lives in constants so the device path
382
404
  // and the session-query byte cap share one value.
383
- function radarRequest(requestPath, timeoutMs = 10000) {
384
- return new Promise((resolve, reject) => {
385
- // settled-guard: req.destroy() on the cap path fires "error" (ECONNRESET) AFTER we have
386
- // already resolved the truncation, so every settle goes through these wrappers and the
387
- // second one is a no-op. Without this the abort would reject an already-resolved promise.
388
- let settled = false;
389
- const done = (r) => {
390
- if (settled)
391
- return;
392
- settled = true;
393
- resolve(r);
394
- };
395
- const fail = (e) => {
396
- if (settled)
397
- return;
398
- settled = true;
399
- reject(e);
400
- };
401
- const req = http.get({
402
- host: RADAR_HOST,
403
- port: RADAR_PORT,
404
- headers: radarTokenHeaderFor(device),
405
- path: requestPath,
406
- timeout: timeoutMs,
407
- }, (res) => {
408
- let data = "";
409
- let bytes = 0;
410
- res.on("data", (chunk) => {
411
- if (settled)
412
- return;
413
- bytes += chunk.length; // byte length, not String.length (UTF-8 over the wire)
414
- if (bytes > MAX_RADAR_RESPONSE_BYTES) {
415
- // Resolve the truncation NOW (not on "end" — req.destroy() aborts the response so
416
- // "end" never fires; it surfaces as an "error" the settled-guard then swallows).
417
- done(responseBudgetError());
418
- req.destroy();
419
- return;
420
- }
421
- data += chunk;
422
- });
423
- res.on("end", () => {
424
- done(interpretRadarResponse(res.statusCode ?? 0, data));
425
- });
426
- });
427
- req.on("error", fail);
428
- req.on("timeout", () => {
429
- req.destroy();
430
- fail(new Error("Request timed out"));
431
- });
432
- });
405
+ function radarRequest(requestPath, init = {}) {
406
+ return radarHttpRequest({ ...init, host: RADAR_HOST, port: RADAR_PORT, path: requestPath, transport: device });
407
+ }
408
+ function peerPing(deadlineMs) {
409
+ return radarRequest("/api/ping", { timeoutMs: 2000, deadlineMs: deadlineMs ?? Date.now() + 2000 });
433
410
  }
434
411
  // Reassert the shared adb forward before every HTTP-based device read. Prefer
435
412
  // reassertForward() (repoints the shared port at OUR pinned device even if a separate
@@ -439,7 +416,8 @@ async function runMcpServer() {
439
416
  function forwardForRead() {
440
417
  return device.reassertForward?.() ?? device.ensureForward();
441
418
  }
442
- async function callRadar(requestPath) {
419
+ const REARM_BUDGET_MS = 30_000;
420
+ async function callRadar(requestPath, init = {}) {
443
421
  if (!device.supportsRadarHttpTools) {
444
422
  return {
445
423
  error: unsupportedCapabilityError(device.platform, "Radar HTTP tools"),
@@ -451,8 +429,11 @@ async function runMcpServer() {
451
429
  };
452
430
  }
453
431
  const requestFromVerifiedPeer = async () => {
432
+ if (init.deadlineMs !== undefined && init.deadlineMs - Date.now() <= 0) {
433
+ return { error: "Radar did not answer in time. Call again." };
434
+ }
454
435
  if (device.acceptsRadarPeer) {
455
- const peer = await radarRequest("/api/ping", 2000);
436
+ const peer = await peerPing(init.deadlineMs);
456
437
  if (!device.acceptsRadarPeer(peer)) {
457
438
  return {
458
439
  error: `The Radar listener on the shared host port does not belong to the selected ${device.platform} app.`,
@@ -463,14 +444,21 @@ async function runMcpServer() {
463
444
  }
464
445
  if (!wasStreamRejected())
465
446
  connectStream();
466
- return radarRequest(requestPath);
447
+ return radarRequest(requestPath, init);
467
448
  };
468
449
  const mismatch = (response) => unauthorizedResponse(response, device);
469
450
  device.activate(device.getTimeoutMinutes());
470
451
  try {
471
452
  return mismatch(await requestFromVerifiedPeer());
472
453
  }
473
- catch {
454
+ catch (error) {
455
+ const timedOut = error.message === REQUEST_TIMED_OUT;
456
+ if (init.reportLost && init.deadlineMs !== undefined && init.deadlineMs - Date.now() < (init.timeoutMs ?? DEFAULT_TIMEOUT_MS) + REARM_BUDGET_MS) {
457
+ // the stream's own loop reconnects it. A teardown here leaves no timer, so capture stays off until the next device call
458
+ if (!timedOut)
459
+ device.resetState();
460
+ return { error: `${REQUEST_LOST_PREFIX}${error.message}. Call again.`, request_lost: true };
461
+ }
474
462
  device.resetState();
475
463
  destroyStream();
476
464
  if (!device.ensureForward()) {
@@ -486,6 +474,9 @@ async function runMcpServer() {
486
474
  return mismatch(await requestFromVerifiedPeer());
487
475
  }
488
476
  catch (e2) {
477
+ // a retry that times out may have reached the handler, so the read-back decides; any other retry error means the device is gone right after a re-broadcast
478
+ if (init.reportLost && e2.message === REQUEST_TIMED_OUT)
479
+ return { error: `${REQUEST_LOST_PREFIX}${e2.message}. Call again.`, request_lost: true };
489
480
  sessionEnabled = false;
490
481
  return {
491
482
  error: `Radar not responding: ${e2.message}. Session disabled. Use /radar-enable to reconnect.`,
@@ -540,65 +531,42 @@ async function runMcpServer() {
540
531
  }
541
532
  // --- Tool handlers ---
542
533
  async function handleSessionEnable(args) {
543
- const timeout = args?.timeout_minutes || 5;
544
- const deviceSerial = args?.device_serial ?? null;
545
- // The orchestration lives in session-enable.ts (testable without the stdio
546
- // server this module starts at load); this handler wires the real effects
547
- // and owns the session flag. sessionEnabled goes true up front so the
548
- // backfill's device pulls pass the session gate, then follows the outcome.
549
- // The catch covers a future refactor introducing a rejecting await: without
550
- // it the gate would stay open (sessionEnabled true) on a half-torn session
551
- // while the SDK reports an opaque error.
552
- try {
553
- sessionEnabled = true;
554
- clearStreamRejected();
555
- // Off (not stale) during the enable: the previous session's list may not describe this
556
- // build (same device, upgraded app). Repopulated from the outcome below.
557
- clearSources();
558
- const outcome = await runSessionEnable(timeout, deviceSerial, {
559
- device,
560
- destroyStream,
561
- connectStream,
562
- isStreamConnected,
563
- wasStreamRejected,
564
- resetDbState,
565
- startSpool,
566
- runBackfill: runBackfillSerialized,
567
- // A health ping does not need the default 10s: a half-alive server
568
- // (accepts TCP, never answers) would otherwise stretch the verify loop
569
- // past the MCP client's 60s tool-call timeout, and the crafted error
570
- // would never reach the user. 2s keeps worst-case enable wall time far
571
- // under that ceiling.
572
- ping: () => radarRequest("/api/ping", 2000),
573
- sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
574
- // Only fires on a switch to a different device: the prior device's buffers,
575
- // spool, capture, and pulled DBs are stale for the new hardware.
576
- onDeviceSwitch: () => {
577
- clearLocalBuffers();
578
- // Closing the spool is also what keeps the old device's switchboard records out of
579
- // export_switchboard_session's device-free fallback.
580
- stopSpool();
581
- stopCapture();
582
- cleanupPulledDatabases();
583
- // The old device's declared sources and cached flags do not describe the new one.
584
- clearSources();
585
- featureFlagsCache.clear();
586
- },
587
- });
588
- sessionEnabled = outcome.enabled;
589
- applyEnableOutcome(outcome);
590
- return textResult(outcome.body, !outcome.enabled);
591
- }
592
- catch (e) {
593
- sessionEnabled = false;
594
- clearSources();
595
- destroyStream();
596
- return textResult({
597
- error: `Enable failed unexpectedly: ${e.message}`,
598
- enabled: false,
599
- platform: device.platform,
600
- }, true);
601
- }
534
+ const deviceSerial = args?.device_serial || null;
535
+ // The enabler owns the choice, counters and flag updates without starting stdio.
536
+ // This handler lends it the session flag and wires the real effects.
537
+ const deps = {
538
+ device,
539
+ forwardForRead,
540
+ destroyStream,
541
+ connectStream,
542
+ isStreamConnected,
543
+ wasStreamRejected,
544
+ resetDbState,
545
+ startSpool,
546
+ runBackfill: runBackfillSerialized,
547
+ // A health ping does not need the default 10s: a half-alive server
548
+ // (accepts TCP, never answers) would otherwise stretch the verify loop
549
+ // past the MCP client's 60s tool-call timeout, and the crafted error
550
+ // would never reach the user. 2s keeps worst-case enable wall time far
551
+ // under that ceiling.
552
+ ping: () => peerPing(),
553
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
554
+ // Only fires on a switch to a different device: the prior device's buffers,
555
+ // spool, capture, and pulled DBs are stale for the new hardware.
556
+ onDeviceSwitch: () => {
557
+ clearLocalBuffers();
558
+ // Closing the spool is also what keeps the old device's switchboard records out of
559
+ // export_switchboard_session's device-free fallback.
560
+ stopSpool();
561
+ stopCapture();
562
+ cleanupPulledDatabases();
563
+ // The old device's declared sources and cached flags do not describe the new one.
564
+ clearSources();
565
+ featureFlagsCache.clear();
566
+ },
567
+ };
568
+ const outcome = await enabler.enable(args?.timeout_minutes, deviceSerial, deps);
569
+ return textResult(outcome.body, !outcome.enabled);
602
570
  }
603
571
  function handleSessionDisable() {
604
572
  device.stopLogCapture?.();
@@ -637,7 +605,7 @@ async function runMcpServer() {
637
605
  if (device.acceptsRadarPeer) {
638
606
  // connectStream() checks the peer too, but only by declining to connect; without this
639
607
  // the tool would wait out its timeout and report "no events" from a foreign listener.
640
- const peer = await radarRequest("/api/ping", 2000).catch(() => null);
608
+ const peer = await peerPing().catch(() => null);
641
609
  if (peer && !device.acceptsRadarPeer(peer)) {
642
610
  return textResult({
643
611
  error: `The Radar listener on the shared host port does not belong to the selected ${device.platform} app.`,
@@ -695,14 +663,14 @@ async function runMcpServer() {
695
663
  }
696
664
  }
697
665
  async function handleActivateForUser(args) {
698
- const maybe = device;
699
- if (typeof maybe.activateForUser !== "function") {
666
+ const { activateForUser } = device;
667
+ if (typeof activateForUser !== "function") {
700
668
  return textResult({ error: `Profile switching not supported on platform ${device.platform}` }, true);
701
669
  }
702
670
  try {
703
671
  const timeout = args?.timeout_minutes || device.getTimeoutMinutes() || 5;
704
672
  clearRadarTokenCache();
705
- maybe.activateForUser(args.user_id, timeout);
673
+ enabler.switchProfile(() => activateForUser.call(device, args.user_id, timeout));
706
674
  // Restart the SSE stream so network/RTM/clog events from the newly
707
675
  // activated profile start flowing again.
708
676
  destroyStream();
@@ -893,7 +861,7 @@ async function runMcpServer() {
893
861
  }
894
862
  }
895
863
  // --- MCP Server ---
896
- const server = new Server({ name: "slack-radar", version: "1.22.0" }, { capabilities: { tools: {} }, instructions: serverInstructions(device.platform) });
864
+ const server = new Server({ name: "slack-radar", version: "1.23.0" }, { capabilities: { tools: {} }, instructions: serverInstructions(device.platform) });
897
865
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
898
866
  tools: TOOL_DEFINITIONS,
899
867
  }));
@@ -1017,6 +985,18 @@ async function runMcpServer() {
1017
985
  }
1018
986
  // The switchboard tools validate host-side and answer a bad id with a reason, where the generic
1019
987
  // buildApiPath fallthrough below would only say "unknown tool" for a null path.
988
+ if (name === "run_test_case") {
989
+ const { data, isError } = await handleRunTestCase(toolArgs, callRadar);
990
+ return textResult(data, isError);
991
+ }
992
+ if (name === "get_test_run") {
993
+ const { data, isError } = await handleGetTestRun(toolArgs, callRadar);
994
+ return textResult(data, isError);
995
+ }
996
+ if (name === "stop_test_run") {
997
+ const { data, isError } = await handleStopTestRun(toolArgs, callRadar);
998
+ return textResult(data, isError);
999
+ }
1020
1000
  if (name === "get_switchboard_sessions") {
1021
1001
  const { data, isError } = await handleGetSwitchboardSessions(callRadar);
1022
1002
  return textResult(data, isError);
@@ -0,0 +1,22 @@
1
+ import { type RadarTokenSender } from "../shared/radar-token.js";
2
+ import { type RadarResponse } from "./radar-response.js";
3
+ export declare const REQUEST_LOST_PREFIX = "Radar did not answer in time: ";
4
+ export declare const REQUEST_TIMED_OUT = "Request timed out";
5
+ export declare const DEFAULT_TIMEOUT_MS = 10000;
6
+ export interface RadarRequestInit {
7
+ method?: "POST" | "DELETE";
8
+ body?: string;
9
+ timeoutMs?: number;
10
+ deadlineMs?: number;
11
+ reportLost?: boolean;
12
+ }
13
+ export declare function radarHttpRequest({ host, port, path, method, body, timeoutMs, deadlineMs, transport }: {
14
+ host: string;
15
+ port: number;
16
+ path: string;
17
+ method?: string;
18
+ body?: string;
19
+ timeoutMs?: number;
20
+ deadlineMs?: number;
21
+ transport: RadarTokenSender;
22
+ }): Promise<RadarResponse>;
@@ -0,0 +1,61 @@
1
+ import http from "http";
2
+ import { MAX_RADAR_RESPONSE_BYTES } from "../shared/constants.js";
3
+ import { radarTokenHeaderFor } from "../shared/radar-token.js";
4
+ import { interpretRadarResponse, responseBudgetError } from "./radar-response.js";
5
+ export const REQUEST_LOST_PREFIX = "Radar did not answer in time: ";
6
+ export const REQUEST_TIMED_OUT = "Request timed out";
7
+ export const DEFAULT_TIMEOUT_MS = 10_000;
8
+ export function radarHttpRequest({ host, port, path, method = "GET", body, timeoutMs = DEFAULT_TIMEOUT_MS, deadlineMs, transport }) {
9
+ return new Promise((resolve, reject) => {
10
+ let settled = false;
11
+ let overallTimer;
12
+ const done = (response) => {
13
+ if (settled)
14
+ return;
15
+ settled = true;
16
+ clearTimeout(overallTimer);
17
+ resolve(response);
18
+ };
19
+ const fail = (error) => {
20
+ if (settled)
21
+ return;
22
+ settled = true;
23
+ clearTimeout(overallTimer);
24
+ reject(error);
25
+ };
26
+ const req = http.request({
27
+ host, port, path, method, timeout: timeoutMs,
28
+ headers: {
29
+ ...radarTokenHeaderFor(transport),
30
+ ...(body === undefined ? {} : {
31
+ "Content-Type": "application/json",
32
+ "Content-Length": Buffer.byteLength(body),
33
+ }),
34
+ },
35
+ }, (res) => {
36
+ let data = "";
37
+ let bytes = 0;
38
+ res.on("data", (chunk) => {
39
+ if (settled)
40
+ return;
41
+ bytes += chunk.length;
42
+ if (bytes > MAX_RADAR_RESPONSE_BYTES) {
43
+ done(responseBudgetError());
44
+ req.destroy();
45
+ return;
46
+ }
47
+ data += chunk;
48
+ });
49
+ res.on("end", () => done(interpretRadarResponse(res.statusCode ?? 0, data)));
50
+ });
51
+ req.on("error", fail);
52
+ const timedOut = () => {
53
+ req.destroy();
54
+ fail(new Error(REQUEST_TIMED_OUT));
55
+ };
56
+ req.on("timeout", timedOut);
57
+ if (deadlineMs !== undefined)
58
+ overallTimer = setTimeout(timedOut, Math.max(0, Math.min(timeoutMs, deadlineMs - Date.now())));
59
+ req.end(body);
60
+ });
61
+ }
@@ -3,6 +3,7 @@ export interface RadarResponse {
3
3
  error?: string;
4
4
  status?: unknown;
5
5
  http_status?: number;
6
+ request_lost?: true;
6
7
  stream_connected?: boolean;
7
8
  local_network_buffer?: number;
8
9
  local_rtm_buffer?: number;
@@ -1,6 +1,7 @@
1
1
  import type { DeviceTransport } from "../shared/transport.js";
2
2
  export interface EnableDeps {
3
3
  device: DeviceTransport;
4
+ forwardForRead?: () => boolean;
4
5
  destroyStream: () => void;
5
6
  connectStream: () => void;
6
7
  isStreamConnected: () => boolean;
@@ -16,4 +17,17 @@ export interface EnableOutcome {
16
17
  body: Record<string, unknown>;
17
18
  enabled: boolean;
18
19
  }
20
+ export interface EnablerHooks {
21
+ isEnabled: () => boolean;
22
+ setEnabled: (enabled: boolean) => void;
23
+ applyEnableOutcome: (outcome: EnableOutcome) => void;
24
+ clearSources: () => void;
25
+ clearStreamRejected: () => void;
26
+ log: (line: string) => void;
27
+ }
28
+ export declare function createEnabler(hooks: EnablerHooks): {
29
+ switchProfile(broadcast: () => void): void;
30
+ enable(timeoutMinutes: number | null | undefined, deviceSerial: string | null, deps: EnableDeps): Promise<EnableOutcome>;
31
+ };
32
+ export declare function refreshEnabledSession(timeoutMinutes: number | null, deviceSerial: string | null, deps: EnableDeps): Promise<EnableOutcome | null>;
19
33
  export declare function runSessionEnable(timeoutMinutes: number, deviceSerial: string | null, deps: EnableDeps): Promise<EnableOutcome>;