@slack/radar-mcp 1.22.0 → 1.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +62 -12
- package/dist/mcp/dashboard-identity.d.ts +10 -0
- package/dist/mcp/dashboard-identity.js +20 -0
- package/dist/mcp/debug-package-reset.d.ts +5 -0
- package/dist/mcp/debug-package-reset.js +28 -0
- package/dist/mcp/flags-tools.d.ts +2 -0
- package/dist/mcp/flags-tools.js +15 -1
- package/dist/mcp/index.js +172 -142
- package/dist/mcp/radar-http.d.ts +22 -0
- package/dist/mcp/radar-http.js +63 -0
- package/dist/mcp/radar-response.d.ts +1 -0
- package/dist/mcp/session-enable.d.ts +15 -0
- package/dist/mcp/session-enable.js +195 -33
- package/dist/mcp/sources-gate.js +5 -0
- package/dist/mcp/switchboard-tools.d.ts +5 -2
- package/dist/mcp/switchboard-tools.js +18 -12
- package/dist/mcp/test-cases.d.ts +14 -0
- package/dist/mcp/test-cases.js +77 -0
- package/dist/mcp/test-runs-tools.d.ts +8 -0
- package/dist/mcp/test-runs-tools.js +95 -0
- package/dist/mcp/tools.js +106 -171
- package/dist/mcp/web-child-env.js +2 -1
- package/dist/shared/android.d.ts +75 -10
- package/dist/shared/android.js +352 -109
- package/dist/shared/constants.d.ts +17 -5
- package/dist/shared/constants.js +59 -5
- package/dist/shared/db.d.ts +1 -1
- package/dist/shared/db.js +21 -14
- package/dist/shared/debug-log.js +2 -4
- package/dist/shared/enable-diagnosis.d.ts +27 -1
- package/dist/shared/enable-diagnosis.js +73 -0
- package/dist/shared/log-session.d.ts +2 -1
- package/dist/shared/logcat-capture.js +17 -1
- package/dist/shared/prefs.js +4 -5
- package/dist/shared/radar-request-raw.js +3 -1
- package/dist/shared/switchboard.d.ts +1 -0
- package/dist/shared/switchboard.js +3 -1
- package/dist/shared/transport.d.ts +30 -0
- package/dist/web/install-app.d.ts +18 -0
- package/dist/web/install-app.js +60 -7
- package/dist/web/macapp/RadarApp.swift +147 -1
- package/dist/web/server.d.ts +17 -0
- package/dist/web/server.js +180 -35
- package/package.json +1 -1
|
@@ -8,12 +8,165 @@
|
|
|
8
8
|
// an adb-level broadcast failure (previously swallowed entirely), and a broadcast
|
|
9
9
|
// that exits 0 with no receiver (radar modules missing, wrong profile), which the
|
|
10
10
|
// old code reported as enabled:true with a failing ping.
|
|
11
|
-
import { deviceServerSilentError, readProcessState, } from "../shared/enable-diagnosis.js";
|
|
11
|
+
import { deviceServerSilentError, foreignRadarOwnerMessage, readProcessState, tokenViaArgvField, } from "../shared/enable-diagnosis.js";
|
|
12
12
|
import { ENABLE_PING_WAITS_MS } from "../shared/constants.js";
|
|
13
13
|
import { clearRadarTokenCache, openModeWarningAfterEnable, tokenFileMessage, unauthorizedMessageFor, } from "../shared/radar-token.js";
|
|
14
14
|
// The device answered the ping with HTTP 401: the token is refused, the app is not down.
|
|
15
15
|
class PingRefused extends Error {
|
|
16
16
|
}
|
|
17
|
+
async function identifiedPing(device, ping) {
|
|
18
|
+
const status = await ping();
|
|
19
|
+
if (device.acceptsRadarPeer && !device.acceptsRadarPeer(status)) {
|
|
20
|
+
throw new Error(`The Radar listener on the shared host port does not belong to the selected ${device.platform} app.`);
|
|
21
|
+
}
|
|
22
|
+
return status;
|
|
23
|
+
}
|
|
24
|
+
async function verifiedPing(device, ping) {
|
|
25
|
+
const status = await identifiedPing(device, ping);
|
|
26
|
+
if (status.http_status === 401)
|
|
27
|
+
throw new PingRefused("the device refused the ping");
|
|
28
|
+
if (device.acceptsRadarPeer && status.status !== "ok") {
|
|
29
|
+
throw new Error(typeof status.error === "string" ? status.error : "Radar is not armed");
|
|
30
|
+
}
|
|
31
|
+
return status;
|
|
32
|
+
}
|
|
33
|
+
function foreignOwnerOutcome(device, owner) {
|
|
34
|
+
return {
|
|
35
|
+
enabled: false,
|
|
36
|
+
body: {
|
|
37
|
+
error: foreignRadarOwnerMessage(device.logPackage ?? "the armed build", owner),
|
|
38
|
+
enabled: false,
|
|
39
|
+
platform: device.platform,
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
function isArmed(status) {
|
|
44
|
+
return status.http_status === undefined && (status.status === "ok" || status.ok === true);
|
|
45
|
+
}
|
|
46
|
+
function selectedDeviceFields(device) {
|
|
47
|
+
const selected = device.getSelectedDevice?.();
|
|
48
|
+
return selected ? { device_serial: selected.serial, device_label: selected.label } : {};
|
|
49
|
+
}
|
|
50
|
+
export function createEnabler(hooks) {
|
|
51
|
+
let inFlight = 0;
|
|
52
|
+
let generation = 0;
|
|
53
|
+
return {
|
|
54
|
+
// A profile switch makes an in-flight repeat ping stale. Bump first so a broadcast that throws still counts.
|
|
55
|
+
switchProfile(broadcast) {
|
|
56
|
+
generation++;
|
|
57
|
+
broadcast();
|
|
58
|
+
},
|
|
59
|
+
async enable(timeoutMinutes, deviceSerial, deps) {
|
|
60
|
+
// An absent or zero timeout keeps the current window.
|
|
61
|
+
const requestedTimeout = timeoutMinutes || null;
|
|
62
|
+
const { device, connectStream, isStreamConnected, destroyStream } = deps;
|
|
63
|
+
try {
|
|
64
|
+
if (hooks.isEnabled() && inFlight === 0) {
|
|
65
|
+
const started = generation;
|
|
66
|
+
const refreshed = await refreshEnabledSession(requestedTimeout, deviceSerial, deps);
|
|
67
|
+
if (refreshed && hooks.isEnabled() && generation === started) {
|
|
68
|
+
if (!isStreamConnected())
|
|
69
|
+
connectStream();
|
|
70
|
+
hooks.applyEnableOutcome(refreshed);
|
|
71
|
+
device.ensureLogCapture?.();
|
|
72
|
+
hooks.log("[radar] _radar_session_enable path=fast");
|
|
73
|
+
return refreshed;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
// A fallback keeps the session window while a disabled session starts at five minutes.
|
|
77
|
+
// Read after the ping so a disable logs the fresh setup it runs.
|
|
78
|
+
const wasEnabled = hooks.isEnabled();
|
|
79
|
+
const timeout = requestedTimeout ?? (wasEnabled ? device.getTimeoutMinutes() : 5);
|
|
80
|
+
hooks.log(`[radar] _radar_session_enable path=${wasEnabled ? "fallback" : "full"}`);
|
|
81
|
+
generation++;
|
|
82
|
+
inFlight++;
|
|
83
|
+
try {
|
|
84
|
+
// The flag goes true up front so the backfill's pulls pass the session gate.
|
|
85
|
+
hooks.setEnabled(true);
|
|
86
|
+
hooks.clearStreamRejected();
|
|
87
|
+
// Full setup clears sources, while a repeat refreshes them from the ping body.
|
|
88
|
+
hooks.clearSources();
|
|
89
|
+
const outcome = await runSessionEnable(timeout, deviceSerial, deps);
|
|
90
|
+
hooks.setEnabled(outcome.enabled);
|
|
91
|
+
hooks.applyEnableOutcome(outcome);
|
|
92
|
+
return outcome;
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
inFlight--;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
// A rejecting await must not leave the gate open on a half-torn session.
|
|
100
|
+
hooks.setEnabled(false);
|
|
101
|
+
hooks.clearSources();
|
|
102
|
+
destroyStream();
|
|
103
|
+
return {
|
|
104
|
+
enabled: false,
|
|
105
|
+
body: {
|
|
106
|
+
error: `Enable failed unexpectedly: ${error.message}`,
|
|
107
|
+
enabled: false,
|
|
108
|
+
platform: device.platform,
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
export async function refreshEnabledSession(timeoutMinutes, deviceSerial, deps) {
|
|
116
|
+
const { device } = deps;
|
|
117
|
+
if (!device.supportsRadarHttpTools && device.supportsHostLogs)
|
|
118
|
+
return null;
|
|
119
|
+
if (device.sendsRadarToken && device.getActiveUserId?.() == null)
|
|
120
|
+
return null;
|
|
121
|
+
// A healthy ping does not prove the last broadcast landed; the full flow re-sends it.
|
|
122
|
+
if (device.getLastActivateError?.())
|
|
123
|
+
return null;
|
|
124
|
+
if (timeoutMinutes !== null && timeoutMinutes !== device.getTimeoutMinutes())
|
|
125
|
+
return null;
|
|
126
|
+
if (deviceSerial !== null && device.getSelectedDevice?.()?.serial !== deviceSerial)
|
|
127
|
+
return null;
|
|
128
|
+
const selection = device.resolveDevice?.(deviceSerial);
|
|
129
|
+
if (selection && (!selection.ok || selection.switched))
|
|
130
|
+
return null;
|
|
131
|
+
if (deps.wasStreamRejected())
|
|
132
|
+
return null;
|
|
133
|
+
clearRadarTokenCache();
|
|
134
|
+
const before = device.getSelectedDevice?.()?.serial;
|
|
135
|
+
if (deps.forwardForRead?.() === false)
|
|
136
|
+
return null;
|
|
137
|
+
if (device.getSelectedDevice?.()?.serial !== before)
|
|
138
|
+
return null;
|
|
139
|
+
let status;
|
|
140
|
+
try {
|
|
141
|
+
status = await identifiedPing(device, deps.ping);
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
if (!isArmed(status))
|
|
147
|
+
return null;
|
|
148
|
+
if (status.token_required === false && device.sendsRadarToken)
|
|
149
|
+
return null;
|
|
150
|
+
const activeUserId = device.getActiveUserId?.();
|
|
151
|
+
if (status.android_user_id != null && activeUserId != null && String(status.android_user_id) !== String(activeUserId))
|
|
152
|
+
return null;
|
|
153
|
+
// Another build holding the socket answers healthy, so only the full flow can refuse it.
|
|
154
|
+
if (device.foreignRadarOwner?.(status) != null)
|
|
155
|
+
return null;
|
|
156
|
+
// The caller starts the capture after confirming the session is still current.
|
|
157
|
+
return {
|
|
158
|
+
enabled: true,
|
|
159
|
+
body: {
|
|
160
|
+
enabled: true,
|
|
161
|
+
already_enabled: true,
|
|
162
|
+
platform: device.platform,
|
|
163
|
+
stream_connected: deps.isStreamConnected(),
|
|
164
|
+
...selectedDeviceFields(device),
|
|
165
|
+
timeout_minutes: device.getTimeoutMinutes(),
|
|
166
|
+
...status,
|
|
167
|
+
},
|
|
168
|
+
};
|
|
169
|
+
}
|
|
17
170
|
export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
|
|
18
171
|
const outcome = await enableSession(timeoutMinutes, deviceSerial, deps);
|
|
19
172
|
// activate() starts a transport-owned log capture before the app is verified. An enable that
|
|
@@ -32,6 +185,8 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
|
|
|
32
185
|
// always reset for the same reason; the MCP path was missing it.
|
|
33
186
|
destroyStream();
|
|
34
187
|
device.resetState();
|
|
188
|
+
// A fresh enable decides the build again, so drop the one a past arm held.
|
|
189
|
+
device.releaseDebugBuild?.();
|
|
35
190
|
// A re-enable may be a different device or a re-armed profile, so drop the cached DB
|
|
36
191
|
// user set + sqlite path; the next DB tool call re-detects the profiles fresh.
|
|
37
192
|
resetDbState();
|
|
@@ -70,22 +225,6 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
|
|
|
70
225
|
},
|
|
71
226
|
};
|
|
72
227
|
}
|
|
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
228
|
// Simulator Radar is already reachable on the Mac's loopback; verify its identity before
|
|
90
229
|
// starting backfill or SSE so an Android adb forward occupying the same port is never consumed.
|
|
91
230
|
if (device.acceptsRadarPeer) {
|
|
@@ -149,7 +288,6 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
|
|
|
149
288
|
},
|
|
150
289
|
};
|
|
151
290
|
}
|
|
152
|
-
const selected = device.getSelectedDevice?.() ?? null;
|
|
153
291
|
return {
|
|
154
292
|
enabled: true,
|
|
155
293
|
body: {
|
|
@@ -157,26 +295,20 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
|
|
|
157
295
|
platform: device.platform,
|
|
158
296
|
stream_connected: false,
|
|
159
297
|
log_capture: "host",
|
|
160
|
-
...(
|
|
161
|
-
? { device_serial: selected.serial, device_label: selected.label }
|
|
162
|
-
: {}),
|
|
298
|
+
...selectedDeviceFields(device),
|
|
163
299
|
},
|
|
164
300
|
};
|
|
165
301
|
}
|
|
166
302
|
if (activateError) {
|
|
167
|
-
//
|
|
168
|
-
// (armed by a prior session, or the broadcast timed out on a loaded device
|
|
169
|
-
// after landing), so probe before failing: a working server beats a pedantic
|
|
170
|
-
// error, and a dead one gets a real error instead of the old silent
|
|
171
|
-
// enabled:true + failing tools.
|
|
303
|
+
// A prior server may still answer despite the failed enable.
|
|
172
304
|
try {
|
|
173
|
-
await verifiedPing();
|
|
305
|
+
await verifiedPing(device, ping);
|
|
174
306
|
}
|
|
175
307
|
catch (error) {
|
|
176
308
|
return {
|
|
177
309
|
enabled: false,
|
|
178
310
|
body: {
|
|
179
|
-
error: error instanceof PingRefused
|
|
311
|
+
error: device.getLastActivateBareError?.() ? activateError : error instanceof PingRefused
|
|
180
312
|
? `Radar activation broadcast failed: ${activateError}. ${unauthorizedMessageFor(device)}`
|
|
181
313
|
: device.radarListenerHint
|
|
182
314
|
? `Radar activation failed: ${activateError}. ${device.radarListenerHint}`
|
|
@@ -187,6 +319,23 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
|
|
|
187
319
|
};
|
|
188
320
|
}
|
|
189
321
|
}
|
|
322
|
+
// The broadcast cannot move a socket another build already holds. Ask before any spool or
|
|
323
|
+
// stream work so nothing is written under the wrong build. No answer yet is fine, the verify
|
|
324
|
+
// loop below asks again.
|
|
325
|
+
if (device.foreignRadarOwner) {
|
|
326
|
+
let early = null;
|
|
327
|
+
try {
|
|
328
|
+
early = await ping();
|
|
329
|
+
}
|
|
330
|
+
catch {
|
|
331
|
+
// Nothing bound yet.
|
|
332
|
+
}
|
|
333
|
+
const owner = early ? device.foreignRadarOwner(early) : null;
|
|
334
|
+
if (owner !== null) {
|
|
335
|
+
destroyStream();
|
|
336
|
+
return foreignOwnerOutcome(device, owner);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
190
339
|
// Open the session event spool, then backfill the device rings into it. The live
|
|
191
340
|
// SSE push can start DURING the backfill (the backfill pulls via the injected
|
|
192
341
|
// fetch, which opens the stream on its first call), so the trailing
|
|
@@ -204,10 +353,18 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
|
|
|
204
353
|
// declaring it dead.
|
|
205
354
|
let status = null;
|
|
206
355
|
let saw401 = false;
|
|
356
|
+
let foreignOwner = null;
|
|
207
357
|
for (const waitMs of ENABLE_PING_WAITS_MS) {
|
|
208
358
|
await sleep(waitMs);
|
|
209
359
|
try {
|
|
210
|
-
|
|
360
|
+
const answer = await verifiedPing(device, ping);
|
|
361
|
+
// A foreign owner does not go away by waiting, so stop at once.
|
|
362
|
+
foreignOwner = device.foreignRadarOwner?.(answer) ?? null;
|
|
363
|
+
if (foreignOwner === null) {
|
|
364
|
+
status = answer;
|
|
365
|
+
// Holds the build that answered even when this enable's own broadcast failed.
|
|
366
|
+
device.adoptRadarOwner?.(answer);
|
|
367
|
+
}
|
|
211
368
|
break;
|
|
212
369
|
}
|
|
213
370
|
catch (error) {
|
|
@@ -215,6 +372,11 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
|
|
|
215
372
|
saw401 = true;
|
|
216
373
|
}
|
|
217
374
|
}
|
|
375
|
+
if (foreignOwner !== null) {
|
|
376
|
+
destroyStream();
|
|
377
|
+
deps.onForeignOwnerAfterBackfill?.();
|
|
378
|
+
return foreignOwnerOutcome(device, foreignOwner);
|
|
379
|
+
}
|
|
218
380
|
if (status === null) {
|
|
219
381
|
destroyStream();
|
|
220
382
|
if (saw401) {
|
|
@@ -224,6 +386,7 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
|
|
|
224
386
|
error: unauthorizedMessageFor(device),
|
|
225
387
|
enabled: false,
|
|
226
388
|
platform: device.platform,
|
|
389
|
+
...tokenViaArgvField(device),
|
|
227
390
|
},
|
|
228
391
|
};
|
|
229
392
|
}
|
|
@@ -240,6 +403,7 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
|
|
|
240
403
|
error,
|
|
241
404
|
enabled: false,
|
|
242
405
|
platform: device.platform,
|
|
406
|
+
...tokenViaArgvField(device),
|
|
243
407
|
},
|
|
244
408
|
};
|
|
245
409
|
}
|
|
@@ -252,7 +416,6 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
|
|
|
252
416
|
}
|
|
253
417
|
else if (!isStreamConnected())
|
|
254
418
|
connectStream();
|
|
255
|
-
const selected = device.getSelectedDevice?.() ?? null;
|
|
256
419
|
// A tokened enable that stays open did not take, so name its broadcast failure.
|
|
257
420
|
const openModeWarning = openModeWarningAfterEnable(status.token_required, activateError);
|
|
258
421
|
return {
|
|
@@ -261,9 +424,7 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
|
|
|
261
424
|
enabled: true,
|
|
262
425
|
platform: device.platform,
|
|
263
426
|
stream_connected: isStreamConnected(),
|
|
264
|
-
...(
|
|
265
|
-
? { device_serial: selected.serial, device_label: selected.label }
|
|
266
|
-
: {}),
|
|
427
|
+
...selectedDeviceFields(device),
|
|
267
428
|
// The broadcast failed but the server answered (armed by a prior session).
|
|
268
429
|
// activate()'s success branch never ran, so the logcat capture is not
|
|
269
430
|
// armed: get_recent_logs degrades to the device ring for this session.
|
|
@@ -274,6 +435,7 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
|
|
|
274
435
|
}
|
|
275
436
|
: {}),
|
|
276
437
|
...status,
|
|
438
|
+
...tokenViaArgvField(device),
|
|
277
439
|
...(openModeWarning ? { warning: openModeWarning } : {}),
|
|
278
440
|
},
|
|
279
441
|
};
|
package/dist/mcp/sources-gate.js
CHANGED
|
@@ -23,6 +23,11 @@ export const TOOL_SOURCE = {
|
|
|
23
23
|
get_switchboard_sessions: "switchboard",
|
|
24
24
|
get_switchboard_session: "switchboard",
|
|
25
25
|
export_switchboard_session: "switchboard",
|
|
26
|
+
// Replay needs a build that declares the test_runs source.
|
|
27
|
+
// Reads and writes share the same capability check.
|
|
28
|
+
run_test_case: "test_runs",
|
|
29
|
+
get_test_run: "test_runs",
|
|
30
|
+
stop_test_run: "test_runs",
|
|
26
31
|
};
|
|
27
32
|
// null = no discovery info (old build or no session); gating is off.
|
|
28
33
|
let sessionSources = null;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { RadarTokenSender } from "../shared/radar-token.js";
|
|
2
|
+
import type { DeviceTransport } from "../shared/transport.js";
|
|
2
3
|
import { type SwitchboardExportGet } from "../shared/switchboard.js";
|
|
3
4
|
import { type RadarResponse } from "./radar-response.js";
|
|
4
5
|
export interface HandlerResult {
|
|
@@ -10,9 +11,11 @@ export declare const SWITCHBOARD_BUDGET_HINT = "Pass kind or lower limit; for th
|
|
|
10
11
|
export declare function handleGetSwitchboardSessions(fetch: RadarFetch): Promise<HandlerResult>;
|
|
11
12
|
export declare function handleGetSwitchboardSession(args: Record<string, unknown>, fetch: RadarFetch): Promise<HandlerResult>;
|
|
12
13
|
export declare const SESSION_DISABLED_SUFFIX_LINE = "Session disabled. Use /radar-enable to reconnect.";
|
|
14
|
+
type EnableErrorSource = Partial<Pick<DeviceTransport, "getLastActivateBareError">>;
|
|
15
|
+
export declare function sessionDisabledLine(transport?: EnableErrorSource, fallback?: string): string;
|
|
13
16
|
export declare const RECONNECT_ONLY_SUFFIX_LINE = "Use /radar-enable to reconnect.";
|
|
14
|
-
export declare function appendSessionDisabledSuffix(message: string, sessionJustDisabled: boolean): string;
|
|
15
17
|
export declare function handleExportSwitchboardSession(args: Record<string, unknown>, get: SwitchboardExportGet, sender: RadarTokenSender, now?: number, exportRoot?: string): Promise<HandlerResult>;
|
|
16
18
|
export declare function shouldExportSwitchboardOffline(requestedId: number | null, getHostRecords: (sessionId: number) => Record<string, unknown>[], getNewestHostSessionId: () => number | null): boolean;
|
|
17
19
|
export declare function handleExportSwitchboardSessionOffline(args: Record<string, unknown>, now?: number, exportRoot?: string): HandlerResult;
|
|
18
|
-
export declare function dispatchExportSwitchboardSession(args: Record<string, unknown>, isSessionEnabled: () => boolean, get: SwitchboardExportGet, sender: RadarTokenSender, now?: number, exportRoot?: string): Promise<HandlerResult>;
|
|
20
|
+
export declare function dispatchExportSwitchboardSession(args: Record<string, unknown>, isSessionEnabled: () => boolean, get: SwitchboardExportGet, sender: (RadarTokenSender & EnableErrorSource) | undefined, now?: number, exportRoot?: string): Promise<HandlerResult>;
|
|
21
|
+
export {};
|
|
@@ -8,7 +8,7 @@ import { MAX_RADAR_RESPONSE_BYTES } from "../shared/constants.js";
|
|
|
8
8
|
import { buildSwitchboardReport, capitalizeSwitchboardNote, stripSwitchboardControlChars, switchboardReportNotes } from "../shared/switchboard-report.js";
|
|
9
9
|
import { writeSwitchboardReportFile } from "../shared/switchboard-report-file.js";
|
|
10
10
|
import { getSpoolSwitchboardRecords, newestSpoolSwitchboardSessionId } from "./switchboard-spool.js";
|
|
11
|
-
import { assembleSwitchboardExport, hostOnlyGapCount, hostOnlySwitchboardDetail, nonNegativeIntArg, } from "../shared/switchboard.js";
|
|
11
|
+
import { assembleSwitchboardExport, hostOnlyGapCount, hostOnlySwitchboardDetail, nonNegativeIntArg, SWITCHBOARD_DEVICE_UNREACHABLE_ERROR, } from "../shared/switchboard.js";
|
|
12
12
|
import { buildApiPath, switchboardSessionQuery } from "./api-paths.js";
|
|
13
13
|
import { responseBudgetError } from "./radar-response.js";
|
|
14
14
|
export const SWITCHBOARD_BUDGET_HINT = "Pass kind or lower limit; for the whole session use query_session with source switchboard, which pages with a cursor.";
|
|
@@ -53,13 +53,14 @@ function parseSwitchboardExportId(args) {
|
|
|
53
53
|
return { ok: true, id: parsed };
|
|
54
54
|
}
|
|
55
55
|
export const SESSION_DISABLED_SUFFIX_LINE = "Session disabled. Use /radar-enable to reconnect.";
|
|
56
|
+
// An enable error that already names its fix wins over the fallback, same rule as session-enable.
|
|
57
|
+
export function sessionDisabledLine(transport, fallback) {
|
|
58
|
+
const bare = transport?.getLastActivateBareError?.()?.message.replace(/\.+$/, "");
|
|
59
|
+
const sentence = bare === undefined ? fallback : `${bare}.`;
|
|
60
|
+
return sentence === undefined ? SESSION_DISABLED_SUFFIX_LINE : `${sentence} ${SESSION_DISABLED_SUFFIX_LINE}`;
|
|
61
|
+
}
|
|
56
62
|
// For a session already off before the call: the report notes already say the session is off.
|
|
57
63
|
export const RECONNECT_ONLY_SUFFIX_LINE = "Use /radar-enable to reconnect.";
|
|
58
|
-
// switchboard.ts's messages are shared with the web export route, which has no session concept,
|
|
59
|
-
// so the MCP appends this itself when the export call is what disabled the session.
|
|
60
|
-
export function appendSessionDisabledSuffix(message, sessionJustDisabled) {
|
|
61
|
-
return sessionJustDisabled ? `${message} ${SESSION_DISABLED_SUFFIX_LINE}` : message;
|
|
62
|
-
}
|
|
63
64
|
export async function handleExportSwitchboardSession(args, get, sender, now = Date.now(), exportRoot = SWITCHBOARD_EXPORT_DIR) {
|
|
64
65
|
const parsedId = parseSwitchboardExportId(args);
|
|
65
66
|
if (!parsedId.ok)
|
|
@@ -112,22 +113,27 @@ export async function dispatchExportSwitchboardSession(args, isSessionEnabled, g
|
|
|
112
113
|
return handleExportSwitchboardSessionOffline(args, now, exportRoot);
|
|
113
114
|
}
|
|
114
115
|
const result = await handleExportSwitchboardSession(args, get, sender, now, exportRoot);
|
|
115
|
-
|
|
116
|
+
if (isSessionEnabled())
|
|
117
|
+
return result;
|
|
118
|
+
// The retry resets state before its re-arm, so only the re-arm's own enable can leave a bare error here.
|
|
119
|
+
return withSessionDisabledSuffix(result, sender);
|
|
116
120
|
}
|
|
117
|
-
//
|
|
118
|
-
|
|
121
|
+
// switchboard.ts's messages are shared with the web export route, which has no session concept,
|
|
122
|
+
// so the MCP adds this line itself. Touches only the returned data, never the file already on disk.
|
|
123
|
+
function withSessionDisabledSuffix(result, sender) {
|
|
119
124
|
const data = result.data;
|
|
120
125
|
if (data === null || typeof data !== "object" || Array.isArray(data))
|
|
121
126
|
return result;
|
|
122
127
|
const d = { ...data };
|
|
123
128
|
if (typeof d.error === "string") {
|
|
124
|
-
|
|
129
|
+
// Only the unreachable text gives way to the enable error; a build or write failure keeps its own message.
|
|
130
|
+
d.error = d.error === SWITCHBOARD_DEVICE_UNREACHABLE_ERROR ? sessionDisabledLine(sender, d.error) : `${d.error} ${sessionDisabledLine(sender)}`;
|
|
125
131
|
}
|
|
126
132
|
else {
|
|
127
133
|
if (Array.isArray(d.notes))
|
|
128
|
-
d.notes = [...d.notes,
|
|
134
|
+
d.notes = [...d.notes, sessionDisabledLine(sender)];
|
|
129
135
|
if (typeof d.summary === "string")
|
|
130
|
-
d.summary =
|
|
136
|
+
d.summary = `${d.summary} ${sessionDisabledLine(sender)}`;
|
|
131
137
|
}
|
|
132
138
|
return { data: d, isError: result.isError };
|
|
133
139
|
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare const CASE_NAME: RegExp;
|
|
2
|
+
export declare const MAX_CASE_FILE_BYTES: number;
|
|
3
|
+
export declare const testCaseDir: () => string;
|
|
4
|
+
export interface TestCase {
|
|
5
|
+
repeat?: number;
|
|
6
|
+
rate_per_second: number | null;
|
|
7
|
+
events: Record<string, unknown>[];
|
|
8
|
+
}
|
|
9
|
+
export declare const BUILTIN_CASES: Map<string, TestCase>;
|
|
10
|
+
export declare function caseStem(name: string): string;
|
|
11
|
+
export declare function loadCase(name: string, dir?: string): TestCase | {
|
|
12
|
+
error: string;
|
|
13
|
+
};
|
|
14
|
+
export declare function buildRunBody(caseDef: TestCase, overrides: Partial<Pick<TestCase, "repeat" | "rate_per_second">>, runId: string): string;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import fs from "fs";
|
|
2
|
+
import os from "os";
|
|
3
|
+
import path from "path";
|
|
4
|
+
export const CASE_NAME = /^[A-Za-z0-9_-]{1,64}$/;
|
|
5
|
+
export const MAX_CASE_FILE_BYTES = 256 * 1024;
|
|
6
|
+
export const testCaseDir = () => path.join(os.homedir(), ".slack-radar", "test-cases");
|
|
7
|
+
function filler(label) {
|
|
8
|
+
return `${label} {{seq}} ${"made up replay text ".repeat(205)}`;
|
|
9
|
+
}
|
|
10
|
+
const seed = { type: "message", channel: "{{test_channel}}", ts: "{{seq_ts}}", client_msg_id: "{{seq_uuid}}", text: filler("seed"), user: "UZRDR0000001" };
|
|
11
|
+
export const BUILTIN_CASES = new Map([
|
|
12
|
+
["message_changed", { repeat: 100, rate_per_second: 10, events: [seed, {
|
|
13
|
+
type: "message", subtype: "message_changed", channel: "{{test_channel}}",
|
|
14
|
+
message: { ts: "{{seq_ts}}", text: filler("edit"), client_msg_id: "{{seq_uuid}}" },
|
|
15
|
+
}] }],
|
|
16
|
+
["message_replied", { repeat: 100, rate_per_second: 10, events: [seed, {
|
|
17
|
+
type: "message", subtype: "message_replied", channel: "{{test_channel}}",
|
|
18
|
+
message: { ts: "{{seq_ts}}", thread_ts: "{{seq_ts}}", text: filler("reply"), client_msg_id: "{{seq_uuid}}", reply_count: 1, replies: [{ user: "UZRDR0000001", ts: "{{frame_ts}}" }] },
|
|
19
|
+
}] }],
|
|
20
|
+
]);
|
|
21
|
+
export function caseStem(name) {
|
|
22
|
+
return name.replace(/\.json$/, "");
|
|
23
|
+
}
|
|
24
|
+
export function loadCase(name, dir = testCaseDir()) {
|
|
25
|
+
const stem = caseStem(name);
|
|
26
|
+
if (!CASE_NAME.test(stem))
|
|
27
|
+
return { error: "case must match [A-Za-z0-9_-]{1,64}, optionally followed by .json" };
|
|
28
|
+
const filename = path.join(dir, `${stem}.json`);
|
|
29
|
+
let fd;
|
|
30
|
+
try {
|
|
31
|
+
fd = fs.openSync(filename, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK);
|
|
32
|
+
const stat = fs.fstatSync(fd);
|
|
33
|
+
if (!stat.isFile())
|
|
34
|
+
return { error: `${filename} must be a regular file` };
|
|
35
|
+
if (stat.size > MAX_CASE_FILE_BYTES)
|
|
36
|
+
return { error: `${filename} exceeds 256 KB` };
|
|
37
|
+
const text = fs.readFileSync(fd, "utf8");
|
|
38
|
+
let obj;
|
|
39
|
+
try {
|
|
40
|
+
obj = JSON.parse(text.replace(/^\uFEFF/, ""));
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
const message = error.message;
|
|
44
|
+
const line = message.match(/line (\d+) column (\d+)/);
|
|
45
|
+
const position = message.match(/position (\d+)/);
|
|
46
|
+
const location = line ? ` at line ${line[1]} column ${line[2]}` : position ? ` at position ${position[1]}` : "";
|
|
47
|
+
return { error: `${filename} is not valid JSON${location}` };
|
|
48
|
+
}
|
|
49
|
+
if (typeof obj !== "object" || obj === null || Array.isArray(obj) || !Array.isArray(obj.events)) {
|
|
50
|
+
return { error: `${filename} needs an events array in an object` };
|
|
51
|
+
}
|
|
52
|
+
if (!("rate_per_second" in obj))
|
|
53
|
+
return { error: `${filename} needs a rate_per_second key (a number, or null for a burst)` };
|
|
54
|
+
return obj;
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
if (!["ENOENT", "ENOTDIR"].includes(error.code ?? ""))
|
|
58
|
+
return { error: `${filename}: ${error.message}` };
|
|
59
|
+
const builtin = BUILTIN_CASES.get(stem);
|
|
60
|
+
if (builtin)
|
|
61
|
+
return builtin;
|
|
62
|
+
let stems = [];
|
|
63
|
+
try {
|
|
64
|
+
stems = fs.readdirSync(dir).filter((entry) => entry.endsWith(".json")).map(caseStem).sort();
|
|
65
|
+
}
|
|
66
|
+
catch { }
|
|
67
|
+
return { error: `no case named ${stem}. Built in: ${[...BUILTIN_CASES.keys()].join(", ")}. In ${dir}: ${stems.join(", ") || "none"}` };
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
if (fd !== undefined)
|
|
71
|
+
fs.closeSync(fd);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
export function buildRunBody(caseDef, overrides, runId) {
|
|
75
|
+
return JSON.stringify({ run_id: runId, repeat: overrides.repeat ?? caseDef.repeat ?? 1,
|
|
76
|
+
rate_per_second: "rate_per_second" in overrides ? overrides.rate_per_second : caseDef.rate_per_second, events: caseDef.events });
|
|
77
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { RadarResponse } from "./radar-response.js";
|
|
2
|
+
import type { RadarRequestInit } from "./radar-http.js";
|
|
3
|
+
import type { HandlerResult } from "./switchboard-tools.js";
|
|
4
|
+
type RadarCall = (path: string, init?: RadarRequestInit) => Promise<RadarResponse>;
|
|
5
|
+
export declare function handleRunTestCase(args: Record<string, unknown>, call: RadarCall, dir?: string, newRunId?: () => string, now?: () => number): Promise<HandlerResult>;
|
|
6
|
+
export declare function handleGetTestRun(args: Record<string, unknown>, call: RadarCall, sleep?: (ms: number) => Promise<void>, now?: () => number): Promise<HandlerResult>;
|
|
7
|
+
export declare function handleStopTestRun(args: Record<string, unknown>, call: RadarCall): Promise<HandlerResult>;
|
|
8
|
+
export {};
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { randomUUID } from "crypto";
|
|
2
|
+
import { buildRunBody, CASE_NAME, loadCase, testCaseDir } from "./test-cases.js";
|
|
3
|
+
const TEST_RUNS_PATH = "/api/test_runs";
|
|
4
|
+
const POST_TIMEOUT_MS = 15_000;
|
|
5
|
+
const POST_DEADLINE_MS = 50_000;
|
|
6
|
+
const POLL_TIMEOUT_MS = 3_000;
|
|
7
|
+
const POLL_GAP_MS = 1_000;
|
|
8
|
+
const WAIT_CAP_S = 45;
|
|
9
|
+
const MAX_BODY_BYTES = 256 * 1024;
|
|
10
|
+
const runPath = (id) => `${TEST_RUNS_PATH}/${id}`;
|
|
11
|
+
const isRequestFailure = (data) => (data.http_status ?? 0) >= 400 || Boolean(data.error) && !("state" in data);
|
|
12
|
+
// the flag steers the read-back only; the model never sees it
|
|
13
|
+
const result = ({ request_lost, ...data }) => ({ data, isError: isRequestFailure(data) });
|
|
14
|
+
const trimTail = (message) => message.replace(/\. Call again\.$/, "").replace(/\.$/, "");
|
|
15
|
+
const FRAME_CHECK_ERROR = "the device refused the run while checking its frames. Call run_test_case again to see the reason";
|
|
16
|
+
const RUN_ID_ERROR = "run_id must match [A-Za-z0-9_-]{1,64}";
|
|
17
|
+
const isRunId = (id) => typeof id === "string" && CASE_NAME.test(id);
|
|
18
|
+
const notFound = (data, id) => data.http_status === 404
|
|
19
|
+
? { ...data, error: `run ${id} not found. The device keeps the last ten runs, or clear_buffers dropped it; call get_test_run with no run_id to list them` } : data;
|
|
20
|
+
async function readBack(runId, post, call, now) {
|
|
21
|
+
const found = await call(runPath(runId), { timeoutMs: POLL_TIMEOUT_MS, deadlineMs: now() + POLL_TIMEOUT_MS, reportLost: true });
|
|
22
|
+
if ("state" in found)
|
|
23
|
+
return found.state === "starting" ? { ...found, note: "the device is still checking the frames; if a later read answers 404 they were refused, call run_test_case again to see the reason" } : found;
|
|
24
|
+
if (found.http_status === 404)
|
|
25
|
+
return post.http_status === 409
|
|
26
|
+
? { error: FRAME_CHECK_ERROR, http_status: 404 }
|
|
27
|
+
: { error: `the device holds no run ${runId}: ${trimTail(String(post.error))}. Call run_test_case again`, run_id: runId };
|
|
28
|
+
return { error: `run ${runId} may have started: the device did not answer the start or the read-back (${trimTail(String(found.error))}). Call get_test_run(run_id) before starting another run; a 404 there most likely means it never started, so call run_test_case again`, run_id: runId };
|
|
29
|
+
}
|
|
30
|
+
export async function handleRunTestCase(args, call, dir = testCaseDir(), newRunId = randomUUID, now = Date.now) {
|
|
31
|
+
if (typeof args.case !== "string" || !args.case)
|
|
32
|
+
return result({ error: "case is required: a built-in name (message_changed, message_replied) or a file stem under ~/.slack-radar/test-cases" });
|
|
33
|
+
const deadline = now() + POST_DEADLINE_MS;
|
|
34
|
+
const caseDef = loadCase(args.case, dir);
|
|
35
|
+
if ("error" in caseDef)
|
|
36
|
+
return result(caseDef);
|
|
37
|
+
const runId = newRunId();
|
|
38
|
+
if (!isRunId(runId))
|
|
39
|
+
return result({ error: RUN_ID_ERROR });
|
|
40
|
+
const overrides = {
|
|
41
|
+
...(typeof args.repeat === "number" ? { repeat: args.repeat } : {}),
|
|
42
|
+
...("rate_per_second" in args ? { rate_per_second: args.rate_per_second } : {}),
|
|
43
|
+
};
|
|
44
|
+
const body = buildRunBody(caseDef, overrides, runId);
|
|
45
|
+
if (Buffer.byteLength(body) > MAX_BODY_BYTES)
|
|
46
|
+
return result({ error: `the request body is ${Math.ceil(Buffer.byteLength(body) / 1024)} KB, the device takes at most 256 KB. Lower repeat does not help, shrink or split the events` });
|
|
47
|
+
let data = await call(TEST_RUNS_PATH, { method: "POST", body, timeoutMs: POST_TIMEOUT_MS, deadlineMs: deadline, reportLost: true });
|
|
48
|
+
const lost = data.request_lost === true;
|
|
49
|
+
// builds without listed_run_id still answer with the text alone
|
|
50
|
+
const listed = data.http_status === 409 && (data.listed_run_id !== undefined ? data.listed_run_id === runId : data.error === `run_id ${runId} is already listed`);
|
|
51
|
+
if (lost || listed)
|
|
52
|
+
data = await readBack(runId, data, call, now);
|
|
53
|
+
return result(isRequestFailure(data) ? { ...data, run_id: runId } : data);
|
|
54
|
+
}
|
|
55
|
+
export async function handleGetTestRun(args, call, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), now = Date.now) {
|
|
56
|
+
const wait = Math.min(WAIT_CAP_S, Math.max(0, typeof args.wait_seconds === "number" ? args.wait_seconds : 0));
|
|
57
|
+
if (args.run_id === undefined) {
|
|
58
|
+
if (wait > 0)
|
|
59
|
+
return result({ error: "wait_seconds needs run_id" });
|
|
60
|
+
return result(await call(TEST_RUNS_PATH));
|
|
61
|
+
}
|
|
62
|
+
if (!isRunId(args.run_id))
|
|
63
|
+
return result({ error: RUN_ID_ERROR });
|
|
64
|
+
const id = args.run_id;
|
|
65
|
+
if (!wait)
|
|
66
|
+
return result(notFound(await call(runPath(id)), id));
|
|
67
|
+
const start = now();
|
|
68
|
+
const deadline = start + wait * 1000;
|
|
69
|
+
let data;
|
|
70
|
+
let lastState;
|
|
71
|
+
for (;;) {
|
|
72
|
+
data = notFound(await call(runPath(id), { timeoutMs: POLL_TIMEOUT_MS, deadlineMs: now() + POLL_TIMEOUT_MS, reportLost: true }), id);
|
|
73
|
+
if (isRequestFailure(data)) {
|
|
74
|
+
return result(data.http_status === 404 && lastState === "starting" ? { ...data, error: FRAME_CHECK_ERROR } : data);
|
|
75
|
+
}
|
|
76
|
+
lastState = data.state;
|
|
77
|
+
if (data.settled === true)
|
|
78
|
+
break;
|
|
79
|
+
if (now() + POLL_GAP_MS >= deadline)
|
|
80
|
+
break;
|
|
81
|
+
await sleep(POLL_GAP_MS);
|
|
82
|
+
if (now() >= deadline)
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
const waited_ms = now() - start;
|
|
86
|
+
return result({ ...data, waited_ms, ...(data.settled === true ? {} : {
|
|
87
|
+
note: `not settled after ${waited_ms / 1000} s (state ${data.state}). Call get_test_run again${args.wait_seconds !== wait ? ". wait_seconds capped at 45 s" : ""}`,
|
|
88
|
+
}) });
|
|
89
|
+
}
|
|
90
|
+
export async function handleStopTestRun(args, call) {
|
|
91
|
+
if (!isRunId(args.run_id))
|
|
92
|
+
return result({ error: RUN_ID_ERROR });
|
|
93
|
+
const id = args.run_id;
|
|
94
|
+
return result(notFound(await call(runPath(id), { method: "DELETE" }), id));
|
|
95
|
+
}
|