@slack/radar-mcp 1.21.0 → 1.22.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 (80) hide show
  1. package/README.md +68 -15
  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 +117 -32
  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-response.d.ts +4 -1
  12. package/dist/mcp/radar-response.js +8 -3
  13. package/dist/mcp/session-backfill.js +3 -4
  14. package/dist/mcp/session-enable.d.ts +1 -0
  15. package/dist/mcp/session-enable.js +146 -15
  16. package/dist/mcp/snapshot.js +42 -26
  17. package/dist/mcp/sources-gate.js +1 -0
  18. package/dist/mcp/stale-dashboard.d.ts +23 -0
  19. package/dist/mcp/stale-dashboard.js +122 -0
  20. package/dist/mcp/switchboard-spool.d.ts +12 -0
  21. package/dist/mcp/switchboard-spool.js +107 -0
  22. package/dist/mcp/switchboard-tools.d.ts +9 -0
  23. package/dist/mcp/switchboard-tools.js +144 -6
  24. package/dist/mcp/tools.d.ts +4 -1
  25. package/dist/mcp/tools.js +60 -15
  26. package/dist/mcp/web-child-env.d.ts +4 -1
  27. package/dist/mcp/web-child-env.js +4 -1
  28. package/dist/shared/android.d.ts +43 -0
  29. package/dist/shared/android.js +227 -19
  30. package/dist/shared/constants.d.ts +9 -4
  31. package/dist/shared/constants.js +9 -4
  32. package/dist/shared/feature-flags.d.ts +1 -0
  33. package/dist/shared/feature-flags.js +1 -0
  34. package/dist/shared/ios-logs.d.ts +10 -0
  35. package/dist/shared/ios-logs.js +91 -0
  36. package/dist/shared/ios.d.ts +25 -2
  37. package/dist/shared/ios.js +157 -3
  38. package/dist/{web → shared}/log-session.d.ts +45 -31
  39. package/dist/shared/log-session.js +300 -0
  40. package/dist/shared/radar-request-raw.d.ts +7 -0
  41. package/dist/shared/radar-request-raw.js +89 -0
  42. package/dist/shared/radar-token.d.ts +25 -0
  43. package/dist/shared/radar-token.js +164 -0
  44. package/dist/shared/stream.d.ts +3 -0
  45. package/dist/shared/stream.js +107 -15
  46. package/dist/shared/switchboard-host-store.d.ts +21 -0
  47. package/dist/shared/switchboard-host-store.js +166 -0
  48. package/dist/shared/switchboard-note.d.ts +15 -0
  49. package/dist/shared/switchboard-note.js +92 -0
  50. package/dist/shared/switchboard-report-file.d.ts +5 -0
  51. package/dist/shared/switchboard-report-file.js +26 -0
  52. package/dist/shared/switchboard-report.d.ts +20 -0
  53. package/dist/shared/switchboard-report.js +406 -0
  54. package/dist/shared/switchboard.d.ts +111 -2
  55. package/dist/shared/switchboard.js +436 -3
  56. package/dist/shared/transport.d.ts +43 -3
  57. package/dist/shared/version.d.ts +2 -0
  58. package/dist/shared/version.js +18 -0
  59. package/dist/shared/wire.d.ts +14 -1
  60. package/dist/web/install-app.d.ts +57 -8
  61. package/dist/web/install-app.js +270 -60
  62. package/dist/web/macapp/RadarApp.swift +340 -22
  63. package/dist/web/public/index.html +51 -9
  64. package/dist/web/public/next/app.js +33 -18
  65. package/dist/web/public/next/feed.js +102 -15
  66. package/dist/web/public/next/flags.js +3 -0
  67. package/dist/web/public/next/inspector.js +69 -3
  68. package/dist/web/public/next/prefs.js +5 -2
  69. package/dist/web/public/next/registry.js +18 -5
  70. package/dist/web/public/next/store.js +455 -29
  71. package/dist/web/public/next/switchboard-note.js +93 -0
  72. package/dist/web/public/next/toast.js +9 -5
  73. package/dist/web/public/next/voice-model.js +215 -35
  74. package/dist/web/public/next/voice.js +173 -18
  75. package/dist/web/server.d.ts +15 -11
  76. package/dist/web/server.js +690 -168
  77. package/dist/web/spec.d.ts +2 -1
  78. package/dist/web/spec.js +2 -1
  79. package/package.json +2 -2
  80. package/dist/web/log-session.js +0 -166
@@ -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;
@@ -0,0 +1,49 @@
1
+ // callRadarForExport's forward-then-retry-once logic as an injectable factory, so a test can
2
+ // drive it with fakes (index.ts connects stdio at module load and cannot be imported).
3
+ /**
4
+ * Build the export path's raw device GET, retrying once after a forward rebuild like callRadar,
5
+ * but without radarRequest's model-context byte budget.
6
+ *
7
+ * A capped result is returned without retrying: the same cap would trip again, and the device
8
+ * did nothing wrong, so none of the reset/reconnect/disable side effects apply. Past the
9
+ * deadline, no further attempt is made.
10
+ */
11
+ export function makeCallRadarForExport(deps, idleMs, overallMs, defaultCapBytes) {
12
+ const msLeft = (deadline) => (deadline === undefined ? undefined : deadline - Date.now());
13
+ return async function callRadarForExport(requestPath, capBytes = defaultCapBytes, deadline) {
14
+ if (!deps.supportsRadarHttpTools())
15
+ return { status: 0, body: null };
16
+ if (!deps.forwardForRead())
17
+ return { status: 0, body: null };
18
+ const firstLeft = msLeft(deadline);
19
+ if (firstLeft !== undefined && firstLeft <= 0)
20
+ return { status: 0, body: null };
21
+ deps.activate(deps.getTimeoutMinutes());
22
+ if (!deps.wasStreamRejected())
23
+ deps.connectStream();
24
+ const first = await deps.request(requestPath, idleMs, overallMs, capBytes, deadline);
25
+ if (first.status !== 0 || first.capped)
26
+ return first;
27
+ // Out of time is not the device's fault, so skip the retry without its disable side effects.
28
+ const retryLeft = msLeft(deadline);
29
+ if (retryLeft !== undefined && retryLeft <= 0)
30
+ return first;
31
+ deps.resetState();
32
+ deps.destroyStream();
33
+ if (!deps.ensureForward()) {
34
+ deps.onSessionDisabled();
35
+ return { status: 0, body: null };
36
+ }
37
+ const secondLeft = msLeft(deadline);
38
+ if (secondLeft !== undefined && secondLeft <= 0)
39
+ return first;
40
+ deps.activate(deps.getTimeoutMinutes());
41
+ // The re-arm is a fresh claim on the device, so a refusal from before it is stale.
42
+ deps.clearStreamRejected();
43
+ deps.connectStream();
44
+ const second = await deps.request(requestPath, idleMs, overallMs, capBytes, deadline);
45
+ if (second.status === 0 && !second.capped)
46
+ deps.onSessionDisabled();
47
+ return second;
48
+ };
49
+ }
@@ -1,6 +1,8 @@
1
+ import { type RadarTokenSender } from "../shared/radar-token.js";
1
2
  export interface RadarResponse {
2
3
  error?: string;
3
- status?: number;
4
+ status?: unknown;
5
+ http_status?: number;
4
6
  stream_connected?: boolean;
5
7
  local_network_buffer?: number;
6
8
  local_rtm_buffer?: number;
@@ -19,6 +21,7 @@ export interface RadarResponse {
19
21
  * body keeps the existing {raw} behavior, a real if unusual success payload.
20
22
  */
21
23
  export declare function interpretRadarResponse(status: number, body: string): RadarResponse;
24
+ export declare function unauthorizedResponse(response: RadarResponse, sender: RadarTokenSender): RadarResponse;
22
25
  /**
23
26
  * The error a proxied answer gets when it would not fit the response budget. radarRequest trips it
24
27
  * on the wire as the bytes arrive; a handler that receives a parsed answer through an injected
@@ -2,6 +2,7 @@
2
2
  // out of index.ts so it is unit-testable: index.ts connects stdio at module load, so importing it
3
3
  // from a test would hang.
4
4
  import { MAX_RADAR_RESPONSE_BYTES } from "../shared/constants.js";
5
+ import { unauthorizedMessageFor } from "../shared/radar-token.js";
5
6
  /**
6
7
  * Turn a device HTTP (status, body) into the RadarResponse the tool layer returns. Parse JSON
7
8
  * when the body is JSON: this preserves the device's own error bodies (e.g. an in-app 404 sends
@@ -24,6 +25,7 @@ export function interpretRadarResponse(status, body) {
24
25
  return {
25
26
  error: `Device returned HTTP ${status} with a non-JSON body. The route may not exist on this build (an older debug build can predate a newer tool), or an upstream error occurred.${bodyDetail}`,
26
27
  status,
28
+ http_status: status,
27
29
  };
28
30
  }
29
31
  return { raw: body };
@@ -32,10 +34,13 @@ export function interpretRadarResponse(status, body) {
32
34
  // RadarResponse, and a downstream `result.error` read on a non-object (esp. null) would throw.
33
35
  // Keep it as a raw payload instead of casting a lie. (The old code cast straight to
34
36
  // RadarResponse and carried this hole; guarding here closes it.)
35
- if (typeof parsed !== "object" || parsed === null) {
36
- return { raw: body };
37
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
38
+ return status >= 400 ? { raw: body, http_status: status } : { raw: body };
37
39
  }
38
- return parsed;
40
+ return status >= 400 ? { ...parsed, http_status: status } : parsed;
41
+ }
42
+ export function unauthorizedResponse(response, sender) {
43
+ return response.http_status === 401 ? { error: unauthorizedMessageFor(sender), http_status: 401 } : response;
39
44
  }
40
45
  /**
41
46
  * The error a proxied answer gets when it would not fit the response budget. radarRequest trips it
@@ -12,10 +12,9 @@ export const BACKFILL_SOURCES = new Map([
12
12
  ["trace", "get_recent_traces"],
13
13
  ]);
14
14
  // Switchboard has no flat ring list: the device keeps it per session, two routes deep, so it is
15
- // its own leg below rather than a BACKFILL_SOURCES row. Records per session asked for: the device
16
- // holds 2000 per session (SwitchboardRadarPlugin eventCapacity), so this asks for the whole ring;
17
- // without it the device pages at 50, a few seconds of a live voice session. A full page of 2000
18
- // records at about 250 bytes each stays under the device's 1 MB response cap.
15
+ // its own leg below rather than a BACKFILL_SOURCES row. Backfill asks for one page of the
16
+ // device's max, 2000 (the default 50 is a few seconds of a live voice session); at about 250
17
+ // bytes a record that stays under the device's 1 MB response cap.
19
18
  export const SWITCHBOARD_BACKFILL_LIMIT = 2000;
20
19
  // A read frame's numeric id, or undefined when it carries none. Only rows with a numeric id can be
21
20
  // deduped; a row with no id is written every round (it cannot be matched against the spool).
@@ -4,6 +4,7 @@ export interface EnableDeps {
4
4
  destroyStream: () => void;
5
5
  connectStream: () => void;
6
6
  isStreamConnected: () => boolean;
7
+ wasStreamRejected: () => boolean;
7
8
  resetDbState: () => void;
8
9
  startSpool: () => void;
9
10
  runBackfill: () => Promise<unknown>;
@@ -9,12 +9,21 @@
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
11
  import { deviceServerSilentError, readProcessState, } from "../shared/enable-diagnosis.js";
12
- // Ping-verify cadence: first probe fast (a healthy server answers immediately;
13
- // this is the whole latency of a normal enable), then two patient retries to
14
- // absorb real server startup.
15
- const PING_WAITS_MS = [500, 1000, 1000];
12
+ import { ENABLE_PING_WAITS_MS } from "../shared/constants.js";
13
+ import { clearRadarTokenCache, openModeWarningAfterEnable, tokenFileMessage, unauthorizedMessageFor, } from "../shared/radar-token.js";
14
+ // The device answered the ping with HTTP 401: the token is refused, the app is not down.
15
+ class PingRefused extends Error {
16
+ }
16
17
  export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
17
- const { device, destroyStream, connectStream, isStreamConnected, resetDbState, startSpool, runBackfill, ping, sleep, onDeviceSwitch, } = deps;
18
+ const outcome = await enableSession(timeoutMinutes, deviceSerial, deps);
19
+ // activate() starts a transport-owned log capture before the app is verified. An enable that
20
+ // ends disabled must not leave that child running, or leave its lines for the next enable.
21
+ if (!outcome.enabled)
22
+ deps.device.stopLogCapture?.();
23
+ return outcome;
24
+ }
25
+ async function enableSession(timeoutMinutes, deviceSerial, deps) {
26
+ const { device, destroyStream, connectStream, isStreamConnected, wasStreamRejected, resetDbState, startSpool, runBackfill, ping, sleep, onDeviceSwitch, } = deps;
18
27
  // Tear down the old stream (and its reconnect loop) FIRST, then drop all cached
19
28
  // transport state so this enable starts clean. Without the reset, a stale adb
20
29
  // forward (device end dead after an idle timeout or a replug) makes ensureForward()
@@ -49,6 +58,7 @@ export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
49
58
  if (selection && selection.ok && selection.switched) {
50
59
  onDeviceSwitch();
51
60
  }
61
+ clearRadarTokenCache();
52
62
  if (!device.ensureForward()) {
53
63
  const reason = device.getLastForwardError?.() ?? null;
54
64
  return {
@@ -60,8 +70,99 @@ export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
60
70
  },
61
71
  };
62
72
  }
63
- device.activate(timeoutMinutes);
73
+ const identifiedPing = async () => {
74
+ const status = await ping();
75
+ if (device.acceptsRadarPeer && !device.acceptsRadarPeer(status)) {
76
+ throw new Error(`The Radar listener on the shared host port does not belong to the selected ${device.platform} app.`);
77
+ }
78
+ return status;
79
+ };
80
+ const verifiedPing = async () => {
81
+ const status = await identifiedPing();
82
+ if (status.http_status === 401)
83
+ throw new PingRefused("the device refused the ping");
84
+ if (device.acceptsRadarPeer && status.status !== "ok") {
85
+ throw new Error(typeof status.error === "string" ? status.error : "Radar is not armed");
86
+ }
87
+ return status;
88
+ };
89
+ // Simulator Radar is already reachable on the Mac's loopback; verify its identity before
90
+ // starting backfill or SSE so an Android adb forward occupying the same port is never consumed.
91
+ if (device.acceptsRadarPeer) {
92
+ let status = null;
93
+ try {
94
+ status = await ping();
95
+ }
96
+ catch (error) {
97
+ // Nothing answered (ECONNREFUSED, a timeout). Say so in the platform's terms instead of
98
+ // handing back the raw socket error.
99
+ const reason = error instanceof Error ? error.message : String(error);
100
+ return {
101
+ enabled: false,
102
+ body: {
103
+ error: `No Radar listener answered for the ${device.platform} app (${reason}).` +
104
+ (device.radarListenerHint ? ` ${device.radarListenerHint}` : ""),
105
+ enabled: false,
106
+ platform: device.platform,
107
+ },
108
+ };
109
+ }
110
+ if (!device.acceptsRadarPeer(status)) {
111
+ return {
112
+ enabled: false,
113
+ body: {
114
+ error: `The Radar listener on the shared host port does not belong to the selected ${device.platform} app.`,
115
+ enabled: false,
116
+ platform: device.platform,
117
+ },
118
+ };
119
+ }
120
+ }
121
+ if (device.activateAsync) {
122
+ await device.activateAsync(timeoutMinutes);
123
+ }
124
+ else {
125
+ device.activate(timeoutMinutes);
126
+ }
127
+ const tokenFileError = device.getLastActivateTokenFileError?.() ?? null;
128
+ if (tokenFileError) {
129
+ return {
130
+ enabled: false,
131
+ body: { error: tokenFileMessage(tokenFileError, "mcp"), enabled: false, platform: device.platform },
132
+ };
133
+ }
64
134
  const activateError = device.getLastActivateError?.() ?? null;
135
+ // A host-log-only transport has a real session boundary without an app-side Radar HTTP
136
+ // listener. Selecting the device and starting its capture are sufficient; probing the
137
+ // host-global Radar port here would either reject a healthy session or, worse, accept an
138
+ // unrelated listener. Keep the HTTP/spool/backfill path below exclusive to transports that
139
+ // explicitly advertise it. No shipped transport takes this branch today (Android and the iOS
140
+ // Simulator both serve Radar HTTP); it is the contract for one that only has host logs.
141
+ if (!device.supportsRadarHttpTools && device.supportsHostLogs) {
142
+ if (activateError) {
143
+ return {
144
+ enabled: false,
145
+ body: {
146
+ error: `Log capture activation failed: ${activateError}`,
147
+ enabled: false,
148
+ platform: device.platform,
149
+ },
150
+ };
151
+ }
152
+ const selected = device.getSelectedDevice?.() ?? null;
153
+ return {
154
+ enabled: true,
155
+ body: {
156
+ enabled: true,
157
+ platform: device.platform,
158
+ stream_connected: false,
159
+ log_capture: "host",
160
+ ...(selected
161
+ ? { device_serial: selected.serial, device_label: selected.label }
162
+ : {}),
163
+ },
164
+ };
165
+ }
65
166
  if (activateError) {
66
167
  // The broadcast failed at the adb level. The device server may STILL be alive
67
168
  // (armed by a prior session, or the broadcast timed out on a loaded device
@@ -69,13 +170,17 @@ export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
69
170
  // error, and a dead one gets a real error instead of the old silent
70
171
  // enabled:true + failing tools.
71
172
  try {
72
- await ping();
173
+ await verifiedPing();
73
174
  }
74
- catch {
175
+ catch (error) {
75
176
  return {
76
177
  enabled: false,
77
178
  body: {
78
- error: `Radar activation broadcast failed: ${activateError}. Is the device connected? Check adb devices.`,
179
+ error: error instanceof PingRefused
180
+ ? `Radar activation broadcast failed: ${activateError}. ${unauthorizedMessageFor(device)}`
181
+ : device.radarListenerHint
182
+ ? `Radar activation failed: ${activateError}. ${device.radarListenerHint}`
183
+ : `Radar activation broadcast failed: ${activateError}. Is the device connected? Check adb devices.`,
79
184
  enabled: false,
80
185
  platform: device.platform,
81
186
  },
@@ -87,27 +192,41 @@ export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
87
192
  // fetch, which opens the stream on its first call), so the trailing
88
193
  // connectStream() is usually a no-op. Correctness does not rely on connect
89
194
  // ordering: the (source, id) have-set and the read-time collapse fold any
90
- // frame both paths write into one.
195
+ // frame both paths write into one. Skipped while the device refused the stream:
196
+ // connecting clears that latch, and the check after the pings needs it.
91
197
  startSpool();
92
198
  await runBackfill();
93
- connectStream();
199
+ if (!wasStreamRejected())
200
+ connectStream();
94
201
  // Verify the device server actually came up. A broadcast can land nowhere and
95
202
  // still exit 0 (no receiver: radar modules missing from the build, or a
96
203
  // wrong-profile target). Retry to absorb real startup latency before
97
204
  // declaring it dead.
98
205
  let status = null;
99
- for (const waitMs of PING_WAITS_MS) {
206
+ let saw401 = false;
207
+ for (const waitMs of ENABLE_PING_WAITS_MS) {
100
208
  await sleep(waitMs);
101
209
  try {
102
- status = await ping();
210
+ status = await verifiedPing();
103
211
  break;
104
212
  }
105
- catch {
106
- // Retry until the waits are exhausted.
213
+ catch (error) {
214
+ if (error instanceof PingRefused)
215
+ saw401 = true;
107
216
  }
108
217
  }
109
218
  if (status === null) {
110
219
  destroyStream();
220
+ if (saw401) {
221
+ return {
222
+ enabled: false,
223
+ body: {
224
+ error: unauthorizedMessageFor(device),
225
+ enabled: false,
226
+ platform: device.platform,
227
+ },
228
+ };
229
+ }
111
230
  // Checked fresh, not from a cache, but only here, seconds after the broadcast: backfill,
112
231
  // stream connect, and three ping retries have already run. A confirmed "stopped" does not
113
232
  // prove the app was never launched. It is equally consistent with the app receiving the
@@ -124,7 +243,18 @@ export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
124
243
  },
125
244
  };
126
245
  }
246
+ // A late pass means the 401 tore the first stream down, or the device refused
247
+ // the backfill's stream and the connect above was skipped. Either way the rings
248
+ // hold what the spool missed.
249
+ if (saw401 || wasStreamRejected()) {
250
+ connectStream();
251
+ await runBackfill();
252
+ }
253
+ else if (!isStreamConnected())
254
+ connectStream();
127
255
  const selected = device.getSelectedDevice?.() ?? null;
256
+ // A tokened enable that stays open did not take, so name its broadcast failure.
257
+ const openModeWarning = openModeWarningAfterEnable(status.token_required, activateError);
128
258
  return {
129
259
  enabled: true,
130
260
  body: {
@@ -144,6 +274,7 @@ export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
144
274
  }
145
275
  : {}),
146
276
  ...status,
277
+ ...(openModeWarning ? { warning: openModeWarning } : {}),
147
278
  },
148
279
  };
149
280
  }
@@ -267,32 +267,9 @@ export async function createSnapshot(device, fetchBuffer, opts = {}, now = Date.
267
267
  files.unshift(bundleFile);
268
268
  // Auto-zip: collapse the 4-file directory into a single shareable
269
269
  // artifact. Users universally want to attach ONE file to Jira or drop
270
- // ONE file in Slack, not drag a directory. Best-effort: if `zip` is
271
- // missing on the user's PATH (rare — ships with macOS and most Linux
272
- // distros) we just record the failure and the user can zip manually.
273
- let zipPath = null;
274
- const zipCandidate = `${dir}.zip`;
275
- try {
276
- const zipResult = spawnSync("zip", ["-rq", zipCandidate, "."], {
277
- cwd: dir,
278
- timeout: 10000,
279
- });
280
- if (zipResult.status === 0) {
281
- try {
282
- fs.chmodSync(zipCandidate, FILE_MODE);
283
- }
284
- catch {
285
- // Leave mode as-is; already a zip copy of owner-readable files.
286
- }
287
- zipPath = zipCandidate;
288
- }
289
- else {
290
- errors.push(`zip failed with status ${zipResult.status ?? "null"}${zipResult.stderr ? ": " + zipResult.stderr.toString().trim() : ""}`);
291
- }
292
- }
293
- catch (e) {
294
- errors.push(`zip not available: ${e.message}`);
295
- }
270
+ // ONE file in Slack, not drag a directory. Best-effort: record the
271
+ // failure and the user can zip manually.
272
+ const zipPath = zipSnapshotDir(dir, errors);
296
273
  return {
297
274
  path: dir,
298
275
  files,
@@ -304,6 +281,45 @@ export async function createSnapshot(device, fetchBuffer, opts = {}, now = Date.
304
281
  privacy_notice: PRIVACY_NOTICE,
305
282
  };
306
283
  }
284
+ // `zip` ships with macOS and most Linux distros but not every image (the
285
+ // shared devspace base has none). python3 has a zipfile CLI that builds the
286
+ // same archive, so try it before giving up. Every tool that runs and fails
287
+ // is recorded, and the next one still gets a shot.
288
+ const ZIP_TOOLS = [
289
+ { cmd: "zip", args: (out) => ["-rq", out, "."] },
290
+ { cmd: "python3", args: (out) => ["-m", "zipfile", "-c", out, "."] },
291
+ ];
292
+ function zipSnapshotDir(dir, errors) {
293
+ const out = `${dir}.zip`;
294
+ const failures = [];
295
+ for (const tool of ZIP_TOOLS) {
296
+ const result = spawnSync(tool.cmd, tool.args(out), {
297
+ cwd: dir,
298
+ timeout: 10000,
299
+ });
300
+ if (result.error?.code === "ENOENT") {
301
+ continue;
302
+ }
303
+ if (result.status === 0) {
304
+ try {
305
+ fs.chmodSync(out, FILE_MODE);
306
+ }
307
+ catch {
308
+ // Leave mode as-is; already a zip copy of owner-readable files.
309
+ }
310
+ return out;
311
+ }
312
+ // A timeout or kill leaves status null, so say why instead.
313
+ const why = result.error?.message ?? result.signal ?? result.stderr?.toString().trim();
314
+ failures.push(`${tool.cmd} exited with status ${result.status ?? "null"}${why ? ": " + why : ""}`);
315
+ // A half-written archive would look like a good one to the user.
316
+ fs.rmSync(out, { force: true });
317
+ }
318
+ errors.push(failures.length > 0
319
+ ? `zip failed: ${failures.join("; ")}`
320
+ : `zip not available: no ${ZIP_TOOLS.map((t) => t.cmd).join(" or ")} on PATH`);
321
+ return null;
322
+ }
307
323
  /**
308
324
  * Count items inside a buffer response. Handles the `{ calls: [...] }`,
309
325
  * `{ events: [...] }`, `{ clogs: [...] }`, `{ traces: [...] }` shapes the
@@ -22,6 +22,7 @@ export const TOOL_SOURCE = {
22
22
  // routes, so the gate turns that into the uniform "build does not serve" error.
23
23
  get_switchboard_sessions: "switchboard",
24
24
  get_switchboard_session: "switchboard",
25
+ export_switchboard_session: "switchboard",
25
26
  };
26
27
  // null = no discovery info (old build or no session); gating is off.
27
28
  let sessionSources = null;
@@ -0,0 +1,23 @@
1
+ export interface DashboardFingerprint {
2
+ version: string | null;
3
+ inUse: "no" | "yes" | "unknown";
4
+ inUseBy: string | null;
5
+ readFailed: boolean;
6
+ }
7
+ interface DashboardReply {
8
+ url?: string;
9
+ title?: string;
10
+ }
11
+ interface OpenDashboardResult {
12
+ ok: true;
13
+ url: string;
14
+ title: string;
15
+ note: string;
16
+ stale_dashboard?: true | null;
17
+ stale_mcp?: true;
18
+ dashboard_version?: string;
19
+ mcp_version?: string;
20
+ }
21
+ export declare function readDashboardFingerprint(base: string): Promise<DashboardFingerprint>;
22
+ export declare function buildOpenDashboardResult(out: DashboardReply, fingerprint: DashboardFingerprint, currentVersion: string, trustedBase: string): OpenDashboardResult;
23
+ export {};
@@ -0,0 +1,122 @@
1
+ import { compareVersions, parseVersion } from "../shared/version.js";
2
+ const FINGERPRINT_TIMEOUT_MS = 2000;
3
+ const PORT_ADVICE = "Or set SLACK_RADAR_WEB_PORT to a free port in this MCP server's config and restart this Claude Code session.";
4
+ const STANDALONE_PORT_ADVICE = "To use a separate dashboard instead, set SLACK_RADAR_WEB_PORT to a free port in this MCP server's config and restart this Claude Code session.";
5
+ const RELAUNCHER_ADVICE = "If the older version comes back, another Radar launcher on an older version restarted it (the dock app, or another Claude Code session), so ask the user to update or quit that one.";
6
+ function dashboardInUse(claim, inUseBy) {
7
+ if (inUseBy === "mcp")
8
+ return "unknown";
9
+ if (inUseBy !== null)
10
+ return "yes";
11
+ if (claim === "1")
12
+ return "yes";
13
+ if (claim === "0")
14
+ return "no";
15
+ return "unknown";
16
+ }
17
+ export async function readDashboardFingerprint(base) {
18
+ const failed = { version: null, inUse: "unknown", inUseBy: null, readFailed: true };
19
+ try {
20
+ const response = await fetch(`${base}/spec`, {
21
+ // We only advise a stop; take would keep an unopened dashboard in use forever.
22
+ headers: { "X-Radar-In-Use-For": "stop" },
23
+ signal: AbortSignal.timeout(FINGERPRINT_TIMEOUT_MS),
24
+ redirect: "error",
25
+ });
26
+ await response.body?.cancel();
27
+ if (!response.ok)
28
+ return failed;
29
+ const inUseBy = response.headers.get("X-Radar-In-Use-By");
30
+ const claim = response.headers.get("X-Radar-In-Use");
31
+ return {
32
+ version: response.headers.get("X-Radar-Version"),
33
+ inUse: dashboardInUse(claim, inUseBy),
34
+ inUseBy,
35
+ readFailed: false,
36
+ };
37
+ }
38
+ catch {
39
+ return failed;
40
+ }
41
+ }
42
+ function stopAdvice(fingerprint, base, hasShutdown) {
43
+ const url = new URL(base);
44
+ const port = url.port || (url.protocol === "https:" ? "443" : "80");
45
+ let first;
46
+ if (fingerprint.inUse === "yes") {
47
+ const holder = fingerprint.inUseBy === "tab"
48
+ ? "Someone has this dashboard open in a window."
49
+ : "Something is using it.";
50
+ first = `${holder} Ask the user before stopping it.`;
51
+ }
52
+ else if (fingerprint.inUse === "no") {
53
+ // The five-minute mcp claim is documented in docs/wire-contract.md.
54
+ first = "The dashboard reports no open window and no Claude Code session use in the last 5 minutes. A quiet session may still rely on it, so ask the user before stopping it.";
55
+ }
56
+ else {
57
+ first = "Could not tell whether anyone else is using it, so ask the user before stopping it.";
58
+ }
59
+ const controls = hasShutdown
60
+ ? `To stop it, click ⏻ Stop dashboard in its header, then click it again to confirm, or run curl -X POST -H 'X-Radar-Dashboard: 1' ${base}/shutdown.`
61
+ : `Stop the process that holds the port. Find it with lsof -nP -iTCP:${port} -sTCP:LISTEN and confirm it is a Radar dashboard first.`;
62
+ return `${first} ${controls}`;
63
+ }
64
+ export function buildOpenDashboardResult(out, fingerprint, currentVersion,
65
+ // This MCP's own WEB_BASE; the reported URL is untrusted and must stay out of the shell hint.
66
+ trustedBase) {
67
+ const title = out.title ?? "";
68
+ const result = {
69
+ ok: true,
70
+ url: out.url ?? trustedBase,
71
+ title,
72
+ note: `Custom dashboard "${title}" is live at ${trustedBase} (the 'Custom' tab). ` +
73
+ "It reads the connected device, so Slack Radar must be enabled on it — the dashboard has " +
74
+ "its own Reconnect button if the device is not yet armed. Call open_radar_dashboard again to refine it.",
75
+ };
76
+ if (parseVersion(currentVersion) === null) {
77
+ result.stale_dashboard = null;
78
+ result.note += ` This MCP server's version (${currentVersion}) is not a plain x.y.z, so the version check was skipped.`;
79
+ return result;
80
+ }
81
+ if (fingerprint.readFailed) {
82
+ result.stale_dashboard = null;
83
+ result.note += " This MCP server could not read the dashboard server's version this time, so the version check was skipped.";
84
+ return result;
85
+ }
86
+ const version = fingerprint.version;
87
+ if (version === null) {
88
+ result.stale_dashboard = true;
89
+ result.mcp_version = currentVersion;
90
+ result.note += " The dashboard server did not report its version, so it is older than 1.6.0. " +
91
+ stopAdvice(fingerprint, trustedBase, false) +
92
+ ` Then call open_radar_dashboard again. ${RELAUNCHER_ADVICE} ${PORT_ADVICE}`;
93
+ return result;
94
+ }
95
+ if (parseVersion(version) === null) {
96
+ result.stale_dashboard = null;
97
+ // The header comes from whatever holds the port, so it never goes into text the model reads.
98
+ result.note += " The dashboard server reported a version that is not a plain x.y.z, so the version check was skipped. " +
99
+ STANDALONE_PORT_ADVICE;
100
+ return result;
101
+ }
102
+ const comparisonOrder = compareVersions(version, currentVersion);
103
+ if (comparisonOrder === 0)
104
+ return result;
105
+ result.dashboard_version = version;
106
+ result.mcp_version = currentVersion;
107
+ const comparison = `The dashboard server is running version ${version}, while this MCP server is running version ${currentVersion}.`;
108
+ if (comparisonOrder > 0) {
109
+ result.stale_mcp = true;
110
+ result.note += ` ${comparison} This MCP server is older than the dashboard. ` +
111
+ "Either a newer Radar was installed after this Claude Code session started, or this MCP server's config pins an older version. " +
112
+ "The dashboard still works. To match versions, ask the user to restart this Claude Code session or update the pinned version.";
113
+ return result;
114
+ }
115
+ result.stale_dashboard = true;
116
+ result.note += ` ${comparison} The dashboard is older than this MCP server. An install does not stop a server that is already running. ` +
117
+ stopAdvice(fingerprint, trustedBase, compareVersions(version, "1.14.0") >= 0) +
118
+ " Then call open_radar_dashboard again to relaunch on the current version. " +
119
+ RELAUNCHER_ADVICE + " " +
120
+ PORT_ADVICE;
121
+ return result;
122
+ }
@@ -0,0 +1,12 @@
1
+ /** Hide every switchboard record spooled so far from the export's host copy (clear_buffers). */
2
+ export declare function markSwitchboardSpoolCleared(): void;
3
+ /**
4
+ * The spooled records of `sessionId`'s newest call, each once, in id order. [] when the spool is
5
+ * closed (disabled) or this process never spooled the id.
6
+ *
7
+ * Walked in time order, a call starts at a session/begin, or at an id at or below one already
8
+ * seen (ids climb within a call, so this catches a restart whose begin was never spooled).
9
+ */
10
+ export declare function getSpoolSwitchboardRecords(sessionId: number): Record<string, unknown>[];
11
+ /** Ranked by timestamp, not id: ids restart with the app process, timestamps keep climbing. */
12
+ export declare function newestSpoolSwitchboardSessionId(): number | null;