@slack/radar-mcp 1.21.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.
Files changed (87) hide show
  1. package/README.md +114 -18
  2. package/dist/mcp/api-paths.d.ts +2 -2
  3. package/dist/mcp/api-paths.js +4 -19
  4. package/dist/mcp/dashboard-identity.d.ts +6 -0
  5. package/dist/mcp/dashboard-identity.js +11 -0
  6. package/dist/mcp/index.js +210 -145
  7. package/dist/mcp/logs-result.d.ts +1 -0
  8. package/dist/mcp/logs-result.js +1 -0
  9. package/dist/mcp/radar-export-get.d.ts +30 -0
  10. package/dist/mcp/radar-export-get.js +49 -0
  11. package/dist/mcp/radar-http.d.ts +22 -0
  12. package/dist/mcp/radar-http.js +61 -0
  13. package/dist/mcp/radar-response.d.ts +5 -1
  14. package/dist/mcp/radar-response.js +8 -3
  15. package/dist/mcp/session-backfill.js +3 -4
  16. package/dist/mcp/session-enable.d.ts +15 -0
  17. package/dist/mcp/session-enable.js +268 -19
  18. package/dist/mcp/snapshot.js +42 -26
  19. package/dist/mcp/sources-gate.js +6 -0
  20. package/dist/mcp/stale-dashboard.d.ts +23 -0
  21. package/dist/mcp/stale-dashboard.js +122 -0
  22. package/dist/mcp/switchboard-spool.d.ts +12 -0
  23. package/dist/mcp/switchboard-spool.js +107 -0
  24. package/dist/mcp/switchboard-tools.d.ts +9 -0
  25. package/dist/mcp/switchboard-tools.js +144 -6
  26. package/dist/mcp/test-cases.d.ts +14 -0
  27. package/dist/mcp/test-cases.js +77 -0
  28. package/dist/mcp/test-runs-tools.d.ts +8 -0
  29. package/dist/mcp/test-runs-tools.js +95 -0
  30. package/dist/mcp/tools.d.ts +4 -1
  31. package/dist/mcp/tools.js +101 -21
  32. package/dist/mcp/web-child-env.d.ts +4 -1
  33. package/dist/mcp/web-child-env.js +4 -1
  34. package/dist/shared/android.d.ts +44 -0
  35. package/dist/shared/android.js +234 -24
  36. package/dist/shared/constants.d.ts +9 -4
  37. package/dist/shared/constants.js +9 -4
  38. package/dist/shared/feature-flags.d.ts +1 -0
  39. package/dist/shared/feature-flags.js +1 -0
  40. package/dist/shared/ios-logs.d.ts +10 -0
  41. package/dist/shared/ios-logs.js +91 -0
  42. package/dist/shared/ios.d.ts +25 -2
  43. package/dist/shared/ios.js +157 -3
  44. package/dist/{web → shared}/log-session.d.ts +45 -31
  45. package/dist/shared/log-session.js +300 -0
  46. package/dist/shared/logcat-capture.js +17 -1
  47. package/dist/shared/radar-request-raw.d.ts +7 -0
  48. package/dist/shared/radar-request-raw.js +89 -0
  49. package/dist/shared/radar-token.d.ts +25 -0
  50. package/dist/shared/radar-token.js +164 -0
  51. package/dist/shared/stream.d.ts +3 -0
  52. package/dist/shared/stream.js +107 -15
  53. package/dist/shared/switchboard-host-store.d.ts +21 -0
  54. package/dist/shared/switchboard-host-store.js +166 -0
  55. package/dist/shared/switchboard-note.d.ts +15 -0
  56. package/dist/shared/switchboard-note.js +92 -0
  57. package/dist/shared/switchboard-report-file.d.ts +5 -0
  58. package/dist/shared/switchboard-report-file.js +26 -0
  59. package/dist/shared/switchboard-report.d.ts +20 -0
  60. package/dist/shared/switchboard-report.js +406 -0
  61. package/dist/shared/switchboard.d.ts +111 -2
  62. package/dist/shared/switchboard.js +436 -3
  63. package/dist/shared/transport.d.ts +49 -3
  64. package/dist/shared/version.d.ts +2 -0
  65. package/dist/shared/version.js +18 -0
  66. package/dist/shared/wire.d.ts +14 -1
  67. package/dist/web/install-app.d.ts +75 -8
  68. package/dist/web/install-app.js +330 -67
  69. package/dist/web/macapp/RadarApp.swift +487 -23
  70. package/dist/web/public/index.html +51 -9
  71. package/dist/web/public/next/app.js +33 -18
  72. package/dist/web/public/next/feed.js +102 -15
  73. package/dist/web/public/next/flags.js +3 -0
  74. package/dist/web/public/next/inspector.js +69 -3
  75. package/dist/web/public/next/prefs.js +5 -2
  76. package/dist/web/public/next/registry.js +18 -5
  77. package/dist/web/public/next/store.js +455 -29
  78. package/dist/web/public/next/switchboard-note.js +93 -0
  79. package/dist/web/public/next/toast.js +9 -5
  80. package/dist/web/public/next/voice-model.js +215 -35
  81. package/dist/web/public/next/voice.js +173 -18
  82. package/dist/web/server.d.ts +15 -11
  83. package/dist/web/server.js +690 -168
  84. package/dist/web/spec.d.ts +2 -1
  85. package/dist/web/spec.js +2 -1
  86. package/package.json +2 -2
  87. package/dist/web/log-session.js +0 -166
package/dist/mcp/index.js CHANGED
@@ -12,17 +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
- import { connectStream, destroyStream, waitForEvents, clearLocalBuffers, isStreamConnected, localNetworkBuffer, localRtmBuffer, setTransport, setOnReconnect, } from "../shared/stream.js";
19
+ import { connectStream, destroyStream, waitForEvents, clearLocalBuffers, isStreamConnected, wasStreamRejected, clearStreamRejected, localNetworkBuffer, localRtmBuffer, setTransport, setOnReconnect, } from "../shared/stream.js";
20
+ import { makeCallRadarForExport } from "./radar-export-get.js";
21
+ import { radarRequestRaw } from "../shared/radar-request-raw.js";
22
+ import { TokenFileError, clearRadarTokenCache, openModeWarning, tokenFileMessage, unauthorizedMessageFor } from "../shared/radar-token.js";
20
23
  import { buildBufferPath, createSnapshot } from "./snapshot.js";
21
24
  import { clampLogLimit, shapeLogsResult } from "./logs-result.js";
22
25
  import { querySession, clampByteCap, toNum } from "./session-query.js";
23
26
  import { resolveDetailById } from "./session-detail.js";
24
27
  import { decorateToolResult } from "./network-detail.js";
25
- import { runSessionEnable } from "./session-enable.js";
28
+ import { createEnabler } from "./session-enable.js";
26
29
  import { applyEnableOutcome, clearSources, sourceGate } from "./sources-gate.js";
27
30
  import { computeDispatch } from "./dispatch.js";
28
31
  import { backfillSpool, BACKFILL_SOURCES, makeSerializedRunner, } from "./session-backfill.js";
@@ -31,9 +34,15 @@ import { handleListPrefs, handleGetPrefs, handleSearchPrefs, } from "./prefs-too
31
34
  import { listFeatureFlags, searchFeatureFlags, getFeatureFlag, normalizeOverriddenArg, createFeatureFlagsCache, } from "./flags-tools.js";
32
35
  import { cleanupPulledDatabases, initializeDatabasePath, resetDbState, } from "../shared/db.js";
33
36
  import { TOOL_DEFINITIONS, serverInstructions, sessionGate } from "./tools.js";
37
+ import { dashboardMatchesDevice } from "./dashboard-identity.js";
34
38
  import { buildApiPath } from "./api-paths.js";
35
- import { handleGetSwitchboardSession, handleGetSwitchboardSessions } from "./switchboard-tools.js";
36
- import { interpretRadarResponse, responseBudgetError } from "./radar-response.js";
39
+ import { dispatchExportSwitchboardSession, handleGetSwitchboardSession, handleGetSwitchboardSessions, shouldExportSwitchboardOffline, } from "./switchboard-tools.js";
40
+ import { getSpoolSwitchboardRecords, markSwitchboardSpoolCleared, newestSpoolSwitchboardSessionId } from "./switchboard-spool.js";
41
+ import { nonNegativeIntArg, SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES, SWITCHBOARD_EXPORT_IDLE_MS, SWITCHBOARD_EXPORT_OVERALL_MS } from "../shared/switchboard.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";
45
+ import { buildOpenDashboardResult, readDashboardFingerprint } from "./stale-dashboard.js";
37
46
  // --- Subcommand + bin-name dispatch ---
38
47
  // See computeDispatch's own comment (dispatch.ts) for the full front-door table and rationale;
39
48
  // pulled out to a pure function so the bin-name/subcommand rules are unit-testable.
@@ -47,6 +56,10 @@ const wantsSelfHealCheck = wantsInstallApp && process.argv.includes("--self-heal
47
56
  // registry-version precheck that only falls through to --self-heal-check once a real upgrade is
48
57
  // confirmed. Checked before wantsSelfHealCheck below so the two flags stay mutually exclusive.
49
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");
50
63
  // --- Web dashboard bridge (open_radar_dashboard) ---
51
64
  //
52
65
  // The MCP server and the web dashboard are separate processes. open_radar_dashboard
@@ -71,7 +84,7 @@ function webAlive() {
71
84
  req.end();
72
85
  });
73
86
  }
74
- function startWeb(initialSpec) {
87
+ function startWeb(device, initialSpec) {
75
88
  // Detached + unref so the dashboard outlives this MCP process; inherit env so the
76
89
  // child honors the same SLACK_RADAR_WEB_PORT. Reuse the current node binary rather
77
90
  // than assuming `node` is on PATH (MCP hosts often launch with a bare PATH).
@@ -91,7 +104,7 @@ function startWeb(initialSpec) {
91
104
  const child = spawn(process.execPath, [WEB_BIN], {
92
105
  detached: true,
93
106
  stdio: "ignore",
94
- env: webChildEnv(initialSpec),
107
+ env: webChildEnv(initialSpec, { platform: device.platform, serial: device.getSelectedDevice?.()?.serial }),
95
108
  });
96
109
  child.unref();
97
110
  }
@@ -156,12 +169,12 @@ function getSpecTitle() {
156
169
  req.end();
157
170
  });
158
171
  }
159
- async function openDashboardSpec(spec) {
172
+ async function openDashboardSpec(device, spec) {
160
173
  const cold = !(await webAlive());
161
174
  if (cold) {
162
175
  // Seed the spec into the spawned server so it is the startup writer and the browser's
163
176
  // bootDefault() never overwrites it with the Live preset (see startWeb / server.ts).
164
- startWeb(spec);
177
+ startWeb(device, spec);
165
178
  // Poll for the freshly-spawned server to start listening (~5s budget).
166
179
  for (let i = 0; i < 20; i++) {
167
180
  await new Promise((r) => setTimeout(r, 250));
@@ -169,6 +182,16 @@ async function openDashboardSpec(spec) {
169
182
  break;
170
183
  }
171
184
  }
185
+ const health = await (await fetch(`${WEB_BASE}/health`, {
186
+ // /health waits up to the device ping ceiling.
187
+ signal: AbortSignal.timeout(6000),
188
+ })).json();
189
+ const selected = device.getSelectedDevice?.()?.serial;
190
+ if (!dashboardMatchesDevice(device.platform, selected, health)) {
191
+ throw new Error("The dashboard port belongs to a different platform or device. Use a separate SLACK_RADAR_WEB_PORT.");
192
+ }
193
+ // A dashboard keeps the version it started with, so read its version on both the cold and warm paths.
194
+ const fingerprint = await readDashboardFingerprint(WEB_BASE);
172
195
  const r = await postSpec(spec);
173
196
  if (r.status !== 200) {
174
197
  throw new Error(r.json.error ?? `dashboard rejected the spec (HTTP ${r.status})`);
@@ -184,10 +207,18 @@ async function openDashboardSpec(spec) {
184
207
  break;
185
208
  await postSpec(spec);
186
209
  }
187
- return r.json;
210
+ return { ...r.json, fingerprint };
188
211
  }
189
212
  if (wantsInstallApp) {
190
- 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) {
191
222
  const { runSelfHealPrecheck } = await import("../web/install-app.js");
192
223
  runSelfHealPrecheck();
193
224
  }
@@ -293,6 +324,14 @@ async function runMcpServer() {
293
324
  // just-ended session stays readable.
294
325
  registerSpoolCleanup();
295
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
+ });
296
335
  // The envelope key each device list route wraps its rows in: /api/network -> {calls}, /api/rtm ->
297
336
  // {events}, /api/clogs -> {clogs}, /api/traces -> {traces}. Read once against the same list routes
298
337
  // buildApiPath pins. Defined here (the impure layer) since it is the device-response shape, not
@@ -363,55 +402,11 @@ async function runMcpServer() {
363
402
  // a truncation marker rather than a partial JSON blob the parser would choke on. Bulk exports go
364
403
  // through capture_snapshot, not this path. The ceiling now lives in constants so the device path
365
404
  // and the session-query byte cap share one value.
366
- function radarRequest(requestPath, timeoutMs = 10000) {
367
- return new Promise((resolve, reject) => {
368
- // settled-guard: req.destroy() on the cap path fires "error" (ECONNRESET) AFTER we have
369
- // already resolved the truncation, so every settle goes through these wrappers and the
370
- // second one is a no-op. Without this the abort would reject an already-resolved promise.
371
- let settled = false;
372
- const done = (r) => {
373
- if (settled)
374
- return;
375
- settled = true;
376
- resolve(r);
377
- };
378
- const fail = (e) => {
379
- if (settled)
380
- return;
381
- settled = true;
382
- reject(e);
383
- };
384
- const req = http.get({
385
- host: RADAR_HOST,
386
- port: RADAR_PORT,
387
- path: requestPath,
388
- timeout: timeoutMs,
389
- }, (res) => {
390
- let data = "";
391
- let bytes = 0;
392
- res.on("data", (chunk) => {
393
- if (settled)
394
- return;
395
- bytes += chunk.length; // byte length, not String.length (UTF-8 over the wire)
396
- if (bytes > MAX_RADAR_RESPONSE_BYTES) {
397
- // Resolve the truncation NOW (not on "end" — req.destroy() aborts the response so
398
- // "end" never fires; it surfaces as an "error" the settled-guard then swallows).
399
- done(responseBudgetError());
400
- req.destroy();
401
- return;
402
- }
403
- data += chunk;
404
- });
405
- res.on("end", () => {
406
- done(interpretRadarResponse(res.statusCode ?? 0, data));
407
- });
408
- });
409
- req.on("error", fail);
410
- req.on("timeout", () => {
411
- req.destroy();
412
- fail(new Error("Request timed out"));
413
- });
414
- });
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 });
415
410
  }
416
411
  // Reassert the shared adb forward before every HTTP-based device read. Prefer
417
412
  // reassertForward() (repoints the shared port at OUR pinned device even if a separate
@@ -421,10 +416,8 @@ async function runMcpServer() {
421
416
  function forwardForRead() {
422
417
  return device.reassertForward?.() ?? device.ensureForward();
423
418
  }
424
- async function callRadar(requestPath) {
425
- // The host port is global and may currently be occupied by an Android adb forward. A transport
426
- // that has no Radar HTTP server (currently iOS Simulator) must stop before reassertForward():
427
- // its simulator-presence check cannot prove that the listener belongs to the selected platform.
419
+ const REARM_BUDGET_MS = 30_000;
420
+ async function callRadar(requestPath, init = {}) {
428
421
  if (!device.supportsRadarHttpTools) {
429
422
  return {
430
423
  error: unsupportedCapabilityError(device.platform, "Radar HTTP tools"),
@@ -435,12 +428,37 @@ async function runMcpServer() {
435
428
  error: "Port forwarding failed. Ensure a device is connected and the debug build is running.",
436
429
  };
437
430
  }
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
+ }
435
+ if (device.acceptsRadarPeer) {
436
+ const peer = await peerPing(init.deadlineMs);
437
+ if (!device.acceptsRadarPeer(peer)) {
438
+ return {
439
+ error: `The Radar listener on the shared host port does not belong to the selected ${device.platform} app.`,
440
+ };
441
+ }
442
+ if (requestPath === "/api/ping")
443
+ return peer;
444
+ }
445
+ if (!wasStreamRejected())
446
+ connectStream();
447
+ return radarRequest(requestPath, init);
448
+ };
449
+ const mismatch = (response) => unauthorizedResponse(response, device);
438
450
  device.activate(device.getTimeoutMinutes());
439
- connectStream();
440
451
  try {
441
- return await radarRequest(requestPath);
442
- }
443
- catch {
452
+ return mismatch(await requestFromVerifiedPeer());
453
+ }
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
+ }
444
462
  device.resetState();
445
463
  destroyStream();
446
464
  if (!device.ensureForward()) {
@@ -450,11 +468,15 @@ async function runMcpServer() {
450
468
  };
451
469
  }
452
470
  device.activate(device.getTimeoutMinutes());
453
- connectStream();
471
+ // The re-arm is a fresh claim on the device, so a refusal from before it is stale.
472
+ clearStreamRejected();
454
473
  try {
455
- return await radarRequest(requestPath);
474
+ return mismatch(await requestFromVerifiedPeer());
456
475
  }
457
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 };
458
480
  sessionEnabled = false;
459
481
  return {
460
482
  error: `Radar not responding: ${e2.message}. Session disabled. Use /radar-enable to reconnect.`,
@@ -462,6 +484,23 @@ async function runMcpServer() {
462
484
  }
463
485
  }
464
486
  }
487
+ const callRadarForExport = makeCallRadarForExport({
488
+ request: (requestPath, idleMs, overallMs, capBytes, deadline) => radarRequestRaw(RADAR_HOST, RADAR_PORT, requestPath, idleMs, overallMs, capBytes, deadline, device),
489
+ // supportsRadarHttpTools is optional on DeviceTransport; absent reads as unsupported.
490
+ supportsRadarHttpTools: () => device.supportsRadarHttpTools === true,
491
+ forwardForRead,
492
+ ensureForward: () => device.ensureForward(),
493
+ resetState: () => device.resetState(),
494
+ activate: (m) => device.activate(m),
495
+ getTimeoutMinutes: () => device.getTimeoutMinutes(),
496
+ connectStream,
497
+ wasStreamRejected,
498
+ clearStreamRejected,
499
+ destroyStream,
500
+ onSessionDisabled: () => {
501
+ sessionEnabled = false;
502
+ },
503
+ }, SWITCHBOARD_EXPORT_IDLE_MS, SWITCHBOARD_EXPORT_OVERALL_MS, SWITCHBOARD_EXPORT_SAFETY_CAP_BYTES);
465
504
  // A model exploring feature flags in one turn tends to call list, then search, then get in
466
505
  // quick succession -- each would otherwise pay its own full device round-trip for the exact
467
506
  // same ~500-flag x 2-scope payload. A short in-process cache collapses that burst into one
@@ -492,66 +531,51 @@ async function runMcpServer() {
492
531
  }
493
532
  // --- Tool handlers ---
494
533
  async function handleSessionEnable(args) {
495
- const timeout = args?.timeout_minutes || 5;
496
- const deviceSerial = args?.device_serial ?? null;
497
- // The orchestration lives in session-enable.ts (testable without the stdio
498
- // server this module starts at load); this handler wires the real effects
499
- // and owns the session flag. sessionEnabled goes true up front so the
500
- // backfill's device pulls pass the session gate, then follows the outcome.
501
- // The catch covers a future refactor introducing a rejecting await: without
502
- // it the gate would stay open (sessionEnabled true) on a half-torn session
503
- // while the SDK reports an opaque error.
504
- try {
505
- sessionEnabled = true;
506
- // Off (not stale) during the enable: the previous session's list may not describe this
507
- // build (same device, upgraded app). Repopulated from the outcome below.
508
- clearSources();
509
- const outcome = await runSessionEnable(timeout, deviceSerial, {
510
- device,
511
- destroyStream,
512
- connectStream,
513
- isStreamConnected,
514
- resetDbState,
515
- startSpool,
516
- runBackfill: runBackfillSerialized,
517
- // A health ping does not need the default 10s: a half-alive server
518
- // (accepts TCP, never answers) would otherwise stretch the verify loop
519
- // past the MCP client's 60s tool-call timeout, and the crafted error
520
- // would never reach the user. 2s keeps worst-case enable wall time far
521
- // under that ceiling.
522
- ping: () => radarRequest("/api/ping", 2000),
523
- sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
524
- // Only fires on a switch to a different device: the prior device's buffers,
525
- // spool, capture, and pulled DBs are stale for the new hardware.
526
- onDeviceSwitch: () => {
527
- clearLocalBuffers();
528
- stopSpool();
529
- stopCapture();
530
- cleanupPulledDatabases();
531
- // The old device's declared sources and cached flags do not describe the new one.
532
- clearSources();
533
- featureFlagsCache.clear();
534
- },
535
- });
536
- sessionEnabled = outcome.enabled;
537
- applyEnableOutcome(outcome);
538
- return textResult(outcome.body, !outcome.enabled);
539
- }
540
- catch (e) {
541
- sessionEnabled = false;
542
- clearSources();
543
- destroyStream();
544
- return textResult({
545
- error: `Enable failed unexpectedly: ${e.message}`,
546
- enabled: false,
547
- platform: device.platform,
548
- }, true);
549
- }
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);
550
570
  }
551
571
  function handleSessionDisable() {
572
+ device.stopLogCapture?.();
552
573
  sessionEnabled = false;
553
574
  clearSources();
554
575
  destroyStream();
576
+ clearStreamRejected();
577
+ // A transient device error must not clear this, but an explicit disable, a device switch, and
578
+ // process exit all do.
555
579
  clearLocalBuffers();
556
580
  featureFlagsCache.clear();
557
581
  // Explicit disable stops the logcat capture immediately. Without this, the
@@ -570,10 +594,24 @@ async function runMcpServer() {
570
594
  });
571
595
  }
572
596
  async function handleWaitForEvents(args) {
597
+ const refused = () => textResult({ error: unauthorizedMessageFor(device) }, true);
598
+ // A refused stream stays final until an enable or a re-arm; retrying here would re-broadcast the token.
599
+ if (wasStreamRejected())
600
+ return refused();
573
601
  if (!isStreamConnected()) {
574
602
  if (!forwardForRead()) {
575
603
  return textResult({ error: "Not connected. Ensure device is connected and radar is enabled." }, true);
576
604
  }
605
+ if (device.acceptsRadarPeer) {
606
+ // connectStream() checks the peer too, but only by declining to connect; without this
607
+ // the tool would wait out its timeout and report "no events" from a foreign listener.
608
+ const peer = await peerPing().catch(() => null);
609
+ if (peer && !device.acceptsRadarPeer(peer)) {
610
+ return textResult({
611
+ error: `The Radar listener on the shared host port does not belong to the selected ${device.platform} app.`,
612
+ }, true);
613
+ }
614
+ }
577
615
  device.activate(device.getTimeoutMinutes());
578
616
  connectStream();
579
617
  await new Promise((r) => setTimeout(r, 1000));
@@ -585,6 +623,9 @@ async function runMcpServer() {
585
623
  timeout_ms: args?.timeout_ms,
586
624
  idle_timeout_ms: args?.idle_timeout_ms,
587
625
  });
626
+ // A 401 during the settle or the wait hands back an empty list at once.
627
+ if (events.length === 0 && wasStreamRejected())
628
+ return refused();
588
629
  return textResult({
589
630
  event_count: events.length,
590
631
  events,
@@ -622,16 +663,18 @@ async function runMcpServer() {
622
663
  }
623
664
  }
624
665
  async function handleActivateForUser(args) {
625
- const maybe = device;
626
- if (typeof maybe.activateForUser !== "function") {
666
+ const { activateForUser } = device;
667
+ if (typeof activateForUser !== "function") {
627
668
  return textResult({ error: `Profile switching not supported on platform ${device.platform}` }, true);
628
669
  }
629
670
  try {
630
671
  const timeout = args?.timeout_minutes || device.getTimeoutMinutes() || 5;
631
- maybe.activateForUser(args.user_id, timeout);
672
+ clearRadarTokenCache();
673
+ enabler.switchProfile(() => activateForUser.call(device, args.user_id, timeout));
632
674
  // Restart the SSE stream so network/RTM/clog events from the newly
633
675
  // activated profile start flowing again.
634
676
  destroyStream();
677
+ clearStreamRejected();
635
678
  connectStream();
636
679
  // Give the newly spawned adb logcat child a moment to emit its first
637
680
  // lines to the capture file. Matches the warmup delay used by
@@ -646,7 +689,7 @@ async function runMcpServer() {
646
689
  });
647
690
  }
648
691
  catch (e) {
649
- return textResult({ error: `Profile activation failed: ${e.message}` }, true);
692
+ return textResult({ error: e instanceof TokenFileError ? tokenFileMessage(e, "profile") : `Profile activation failed: ${e.message}. Is the device connected? Check adb devices.` }, true);
650
693
  }
651
694
  }
652
695
  async function handleCaptureSnapshot(args) {
@@ -762,13 +805,19 @@ async function runMcpServer() {
762
805
  }
763
806
  }
764
807
  async function handleClearBuffers() {
808
+ // The spool stays open for query_session, so the switchboard copy is cut by a mark instead:
809
+ // without it, an export after the device ring is emptied would fall back to the pre-clear call.
765
810
  clearLocalBuffers();
811
+ markSwitchboardSpoolCleared();
766
812
  const result = await callRadar("/api/clear");
767
813
  return textResult(result, !!result.error);
768
814
  }
769
815
  async function handlePing(args) {
770
816
  if (args?.timeout_minutes) {
771
817
  device.activate(args.timeout_minutes);
818
+ const tokenFileError = device.getLastActivateTokenFileError?.();
819
+ if (tokenFileError)
820
+ return textResult({ error: tokenFileError.message, mcp_version: RADAR_VERSION }, true);
772
821
  }
773
822
  const result = await callRadar("/api/ping");
774
823
  // Version is a property of this process, not the device, so it is reported
@@ -781,6 +830,9 @@ async function runMcpServer() {
781
830
  result.local_rtm_buffer = localRtmBuffer.length;
782
831
  result.timeout_minutes = device.getTimeoutMinutes();
783
832
  result.platform = device.platform;
833
+ const warning = openModeWarning(result.token_required);
834
+ if (warning)
835
+ result.warning = warning;
784
836
  }
785
837
  return textResult(result, !!result.error);
786
838
  }
@@ -798,16 +850,8 @@ async function runMcpServer() {
798
850
  // The web server runs its own coerce+validate on /setspec, so a thin pass of
799
851
  // the authored args is enough; a bad spec comes back as an HTTP 400 with its
800
852
  // reason, which we surface verbatim rather than rendering silent zeros.
801
- const out = await openDashboardSpec(args);
802
- const url = out.url ?? WEB_BASE;
803
- return textResult({
804
- ok: true,
805
- url,
806
- title: out.title ?? args.title ?? "",
807
- note: `Custom dashboard "${out.title ?? args.title ?? ""}" is live at ${url} (the 'Custom' tab). ` +
808
- "It reads the connected device, so Slack Radar must be enabled on it — the dashboard has " +
809
- "its own Reconnect button if the device is not yet armed. Call open_radar_dashboard again to refine it.",
810
- });
853
+ const out = await openDashboardSpec(device, args);
854
+ return textResult(buildOpenDashboardResult({ ...out, title: out.title ?? args.title }, out.fingerprint, RADAR_VERSION, WEB_BASE));
811
855
  }
812
856
  catch (e) {
813
857
  return textResult({
@@ -817,7 +861,7 @@ async function runMcpServer() {
817
861
  }
818
862
  }
819
863
  // --- MCP Server ---
820
- const server = new Server({ name: "slack-radar", version: "1.21.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) });
821
865
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
822
866
  tools: TOOL_DEFINITIONS,
823
867
  }));
@@ -830,12 +874,15 @@ async function runMcpServer() {
830
874
  if (name === "_radar_session_disable") {
831
875
  return handleSessionDisable();
832
876
  }
877
+ // A host-only switchboard report needs no device call, so it may run while disabled when this
878
+ // process already spooled the records.
879
+ const allowSwitchboardExportOffline = name === "export_switchboard_session" &&
880
+ !sessionEnabled &&
881
+ shouldExportSwitchboardOffline(nonNegativeIntArg(toolArgs.id), getSpoolSwitchboardRecords, newestSpoolSwitchboardSessionId);
833
882
  // Single source of truth for the session gate (also unit-tested in tools.test.mjs).
834
- // Returns an error result when a tool requires an enabled session and there is none;
835
- // null when the tool is allowed (ping, the session enable/disable verbs, and
836
- // open_radar_dashboard — the dashboard is an independent local process with its own
837
- // device-enable Reconnect button, so opening it does not need an enabled MCP session).
838
- const gate = sessionGate(name, sessionEnabled);
883
+ // open_radar_dashboard passes while disabled because the dashboard is an independent local
884
+ // process with its own device-enable Reconnect button.
885
+ const gate = sessionGate(name, sessionEnabled, allowSwitchboardExportOffline);
839
886
  if (gate) {
840
887
  return textResult(JSON.parse(gate.content[0].text), gate.isError);
841
888
  }
@@ -938,6 +985,18 @@ async function runMcpServer() {
938
985
  }
939
986
  // The switchboard tools validate host-side and answer a bad id with a reason, where the generic
940
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
+ }
941
1000
  if (name === "get_switchboard_sessions") {
942
1001
  const { data, isError } = await handleGetSwitchboardSessions(callRadar);
943
1002
  return textResult(data, isError);
@@ -946,6 +1005,12 @@ async function runMcpServer() {
946
1005
  const { data, isError } = await handleGetSwitchboardSession(toolArgs, callRadar);
947
1006
  return textResult(data, isError);
948
1007
  }
1008
+ if (name === "export_switchboard_session") {
1009
+ // A disabled session only reaches here via allowSwitchboardExportOffline, and then the
1010
+ // dispatch takes the offline path, which makes no device calls.
1011
+ const { data, isError } = await dispatchExportSwitchboardSession(toolArgs, () => sessionEnabled, callRadarForExport, device);
1012
+ return textResult(data, isError);
1013
+ }
949
1014
  const apiPath = buildApiPath(name, toolArgs);
950
1015
  if (apiPath === null) {
951
1016
  return textResult(`Unknown tool: ${name}`, true);
@@ -4,6 +4,7 @@ export interface LogsToolResult {
4
4
  lines: string[];
5
5
  count: number;
6
6
  source?: string;
7
+ capture_error?: string;
7
8
  }
8
9
  export declare function clampLogLimit(limit: number | undefined): number;
9
10
  export declare function shapeLogsResult(tag: string, result: LogResult): LogsToolResult;
@@ -11,5 +11,6 @@ export function shapeLogsResult(tag, result) {
11
11
  lines: result.lines,
12
12
  count: result.lines.length,
13
13
  source: result.source,
14
+ ...(result.capture_error ? { capture_error: result.capture_error } : {}),
14
15
  };
15
16
  }
@@ -0,0 +1,30 @@
1
+ import type { SwitchboardExportGet } from "../shared/switchboard.js";
2
+ export type RadarRequestRaw = (requestPath: string, idleMs: number, overallMs: number, capBytes: number, deadline?: number) => Promise<{
3
+ status: number;
4
+ body: Record<string, unknown> | null;
5
+ bytes?: number;
6
+ capped?: boolean;
7
+ }>;
8
+ export interface CallRadarForExportDeps {
9
+ request: RadarRequestRaw;
10
+ supportsRadarHttpTools: () => boolean;
11
+ forwardForRead: () => boolean;
12
+ ensureForward: () => boolean;
13
+ resetState: () => void;
14
+ activate: (timeoutMinutes: number) => void;
15
+ getTimeoutMinutes: () => number;
16
+ connectStream: () => void;
17
+ wasStreamRejected: () => boolean;
18
+ clearStreamRejected: () => void;
19
+ destroyStream: () => void;
20
+ onSessionDisabled: () => void;
21
+ }
22
+ /**
23
+ * Build the export path's raw device GET, retrying once after a forward rebuild like callRadar,
24
+ * but without radarRequest's model-context byte budget.
25
+ *
26
+ * A capped result is returned without retrying: the same cap would trip again, and the device
27
+ * did nothing wrong, so none of the reset/reconnect/disable side effects apply. Past the
28
+ * deadline, no further attempt is made.
29
+ */
30
+ export declare function makeCallRadarForExport(deps: CallRadarForExportDeps, idleMs: number, overallMs: number, defaultCapBytes: number): SwitchboardExportGet;