@slack/radar-mcp 1.22.0 → 1.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,6 +14,146 @@ import { clearRadarTokenCache, openModeWarningAfterEnable, tokenFileMessage, una
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 isArmed(status) {
34
+ return status.http_status === undefined && (status.status === "ok" || status.ok === true);
35
+ }
36
+ function selectedDeviceFields(device) {
37
+ const selected = device.getSelectedDevice?.();
38
+ return selected ? { device_serial: selected.serial, device_label: selected.label } : {};
39
+ }
40
+ export function createEnabler(hooks) {
41
+ let inFlight = 0;
42
+ let generation = 0;
43
+ return {
44
+ // A profile switch makes an in-flight repeat ping stale. Bump first so a broadcast that throws still counts.
45
+ switchProfile(broadcast) {
46
+ generation++;
47
+ broadcast();
48
+ },
49
+ async enable(timeoutMinutes, deviceSerial, deps) {
50
+ // An absent or zero timeout keeps the current window.
51
+ const requestedTimeout = timeoutMinutes || null;
52
+ const { device, connectStream, isStreamConnected, destroyStream } = deps;
53
+ try {
54
+ if (hooks.isEnabled() && inFlight === 0) {
55
+ const started = generation;
56
+ const refreshed = await refreshEnabledSession(requestedTimeout, deviceSerial, deps);
57
+ if (refreshed && hooks.isEnabled() && generation === started) {
58
+ if (!isStreamConnected())
59
+ connectStream();
60
+ hooks.applyEnableOutcome(refreshed);
61
+ device.ensureLogCapture?.();
62
+ hooks.log("[radar] _radar_session_enable path=fast");
63
+ return refreshed;
64
+ }
65
+ }
66
+ // A fallback keeps the session window while a disabled session starts at five minutes.
67
+ // Read after the ping so a disable logs the fresh setup it runs.
68
+ const wasEnabled = hooks.isEnabled();
69
+ const timeout = requestedTimeout ?? (wasEnabled ? device.getTimeoutMinutes() : 5);
70
+ hooks.log(`[radar] _radar_session_enable path=${wasEnabled ? "fallback" : "full"}`);
71
+ generation++;
72
+ inFlight++;
73
+ try {
74
+ // The flag goes true up front so the backfill's pulls pass the session gate.
75
+ hooks.setEnabled(true);
76
+ hooks.clearStreamRejected();
77
+ // Full setup clears sources, while a repeat refreshes them from the ping body.
78
+ hooks.clearSources();
79
+ const outcome = await runSessionEnable(timeout, deviceSerial, deps);
80
+ hooks.setEnabled(outcome.enabled);
81
+ hooks.applyEnableOutcome(outcome);
82
+ return outcome;
83
+ }
84
+ finally {
85
+ inFlight--;
86
+ }
87
+ }
88
+ catch (error) {
89
+ // A rejecting await must not leave the gate open on a half-torn session.
90
+ hooks.setEnabled(false);
91
+ hooks.clearSources();
92
+ destroyStream();
93
+ return {
94
+ enabled: false,
95
+ body: {
96
+ error: `Enable failed unexpectedly: ${error.message}`,
97
+ enabled: false,
98
+ platform: device.platform,
99
+ },
100
+ };
101
+ }
102
+ },
103
+ };
104
+ }
105
+ export async function refreshEnabledSession(timeoutMinutes, deviceSerial, deps) {
106
+ const { device } = deps;
107
+ if (!device.supportsRadarHttpTools && device.supportsHostLogs)
108
+ return null;
109
+ if (device.sendsRadarToken && device.getActiveUserId?.() == null)
110
+ return null;
111
+ // A healthy ping does not prove the last broadcast landed; the full flow re-sends it.
112
+ if (device.getLastActivateError?.())
113
+ return null;
114
+ if (timeoutMinutes !== null && timeoutMinutes !== device.getTimeoutMinutes())
115
+ return null;
116
+ if (deviceSerial !== null && device.getSelectedDevice?.()?.serial !== deviceSerial)
117
+ return null;
118
+ const selection = device.resolveDevice?.(deviceSerial);
119
+ if (selection && (!selection.ok || selection.switched))
120
+ return null;
121
+ if (deps.wasStreamRejected())
122
+ return null;
123
+ clearRadarTokenCache();
124
+ const before = device.getSelectedDevice?.()?.serial;
125
+ if (deps.forwardForRead?.() === false)
126
+ return null;
127
+ if (device.getSelectedDevice?.()?.serial !== before)
128
+ return null;
129
+ let status;
130
+ try {
131
+ status = await identifiedPing(device, deps.ping);
132
+ }
133
+ catch {
134
+ return null;
135
+ }
136
+ if (!isArmed(status))
137
+ return null;
138
+ if (status.token_required === false && device.sendsRadarToken)
139
+ return null;
140
+ const activeUserId = device.getActiveUserId?.();
141
+ if (status.android_user_id != null && activeUserId != null && String(status.android_user_id) !== String(activeUserId))
142
+ return null;
143
+ // The caller starts the capture after confirming the session is still current.
144
+ return {
145
+ enabled: true,
146
+ body: {
147
+ enabled: true,
148
+ already_enabled: true,
149
+ platform: device.platform,
150
+ stream_connected: deps.isStreamConnected(),
151
+ ...selectedDeviceFields(device),
152
+ timeout_minutes: device.getTimeoutMinutes(),
153
+ ...status,
154
+ },
155
+ };
156
+ }
17
157
  export async function runSessionEnable(timeoutMinutes, deviceSerial, deps) {
18
158
  const outcome = await enableSession(timeoutMinutes, deviceSerial, deps);
19
159
  // activate() starts a transport-owned log capture before the app is verified. An enable that
@@ -70,22 +210,6 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
70
210
  },
71
211
  };
72
212
  }
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
213
  // Simulator Radar is already reachable on the Mac's loopback; verify its identity before
90
214
  // starting backfill or SSE so an Android adb forward occupying the same port is never consumed.
91
215
  if (device.acceptsRadarPeer) {
@@ -149,7 +273,6 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
149
273
  },
150
274
  };
151
275
  }
152
- const selected = device.getSelectedDevice?.() ?? null;
153
276
  return {
154
277
  enabled: true,
155
278
  body: {
@@ -157,9 +280,7 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
157
280
  platform: device.platform,
158
281
  stream_connected: false,
159
282
  log_capture: "host",
160
- ...(selected
161
- ? { device_serial: selected.serial, device_label: selected.label }
162
- : {}),
283
+ ...selectedDeviceFields(device),
163
284
  },
164
285
  };
165
286
  }
@@ -170,7 +291,7 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
170
291
  // error, and a dead one gets a real error instead of the old silent
171
292
  // enabled:true + failing tools.
172
293
  try {
173
- await verifiedPing();
294
+ await verifiedPing(device, ping);
174
295
  }
175
296
  catch (error) {
176
297
  return {
@@ -207,7 +328,7 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
207
328
  for (const waitMs of ENABLE_PING_WAITS_MS) {
208
329
  await sleep(waitMs);
209
330
  try {
210
- status = await verifiedPing();
331
+ status = await verifiedPing(device, ping);
211
332
  break;
212
333
  }
213
334
  catch (error) {
@@ -252,7 +373,6 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
252
373
  }
253
374
  else if (!isStreamConnected())
254
375
  connectStream();
255
- const selected = device.getSelectedDevice?.() ?? null;
256
376
  // A tokened enable that stays open did not take, so name its broadcast failure.
257
377
  const openModeWarning = openModeWarningAfterEnable(status.token_required, activateError);
258
378
  return {
@@ -261,9 +381,7 @@ async function enableSession(timeoutMinutes, deviceSerial, deps) {
261
381
  enabled: true,
262
382
  platform: device.platform,
263
383
  stream_connected: isStreamConnected(),
264
- ...(selected
265
- ? { device_serial: selected.serial, device_label: selected.label }
266
- : {}),
384
+ ...selectedDeviceFields(device),
267
385
  // The broadcast failed but the server answered (armed by a prior session).
268
386
  // activate()'s success branch never ran, so the logcat capture is not
269
387
  // armed: get_recent_logs degrades to the device ring for this session.
@@ -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;
@@ -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
+ }
package/dist/mcp/tools.js CHANGED
@@ -9,13 +9,15 @@ export const SERVER_INSTRUCTIONS = [
9
9
  "live. It builds the report from the live stream copy, no device call needed.",
10
10
  "Use /radar-enable to activate, /radar-disable to deactivate.",
11
11
  "",
12
- "AUTO-ENABLE: When the user asks an obvious device question, invoke the Skill tool with",
13
- 'skill="radar-enable" FIRST, then proceed with the radar tool call. No need to ask.',
12
+ "AUTO-ENABLE: When the user asks an obvious device question, call the radar tool straight away.",
13
+ 'Invoke the Skill tool with skill="radar-enable" only when a tool says Radar is not active or',
14
+ "Session disabled, or when the user asks to connect.",
14
15
  "Obvious device questions include: clogs, network calls, RTM events, screenshots,",
15
16
  "app state, device logs, Slackbot voice sessions, or any reference to what is happening on the connected device.",
17
+ "Enable once without asking, then retry the tool. If the enable or the retry fails, tell the user and stop.",
16
18
  "",
17
19
  "TIMEOUT: The device-side radar auto-shuts down after idle. On tool call failure,",
18
- "the session flips to disabled. Tell the user and offer to re-enable.",
20
+ "the session flips to disabled and the tool says Radar is not active or Session disabled. The AUTO-ENABLE rule applies.",
19
21
  "",
20
22
  "When to use:",
21
23
  '- "what am I looking at" / "what screen is this" -> screenshot',
@@ -35,6 +37,7 @@ export const SERVER_INSTRUCTIONS = [
35
37
  '- "what feature-flag overrides are set?" / "check debug_features" -> search_prefs(query="X") or get_prefs(file="debug_features_...xml"). This shows MANUAL OVERRIDES only, not effective flag state: debug_features_*.xml holds only flags the debug menu overrode, and an override is deleted once it matches the server value. A flag missing from this file can still be ON server-side -- absence means "no override," never "disabled." Prefer get_feature_flag/list_feature_flags/search_feature_flags for the actual live value; use this route only when the manual-override history itself is what is being asked about.',
36
38
  '- "what did the app remember" / "what is cached in prefs" / "what team_prefs are set" -> list_prefs then get_prefs',
37
39
  '- "save this" / "file this as a bug" / "share this" / "bundle this" / "attach to ticket" / "give me a repro" / "snapshot this" / "preserve this" / "hold this state" / "save what you just saw" -> capture_snapshot',
40
+ '- "how does the app handle N events a second" / "replay RTM" / "stress the message handler" -> run_test_case(case, repeat, rate_per_second) then get_test_run(run_id, wait_seconds) until settled. A 409 with "ms left" means wait that long and retry, a 409 "active" names the run to wait for or stop',
38
41
  "",
39
42
  "Key behaviors:",
40
43
  "- Network/RTM buffers clear on shutdown. Clogs persist from app start.",
@@ -473,17 +476,17 @@ export const TOOL_DEFINITIONS = [
473
476
  },
474
477
  {
475
478
  name: "clear_buffers",
476
- description: "Clear all captured network calls and RTM events from both device and local buffers.",
479
+ description: "Clear all captured network calls, RTM events and settled test runs from both device and local buffers.",
477
480
  inputSchema: { type: "object", properties: {} },
478
481
  annotations: { destructiveHint: true },
479
482
  },
480
483
  {
481
484
  name: "_radar_session_enable",
482
- description: "Enable Slack Radar for this session. Sets up ADB forwarding, activates the device-side server, and connects the SSE stream. Called by /radar-enable skill. If the result has a warning field, show it to the user verbatim.",
485
+ description: "Enable Slack Radar for this session. Sets up ADB forwarding, activates the device-side server, and connects the SSE stream. Called by /radar-enable skill. Safe to repeat: on an already enabled session it checks the device first and returns the current status with already_enabled: true. It runs the full setup again when that check fails or the last activation did not land, the device, token or profile changed, the timeout changes, or Radar is in open mode. For a clean reset run /radar-disable, then /radar-enable. If the result has a warning field, show it to the user verbatim.",
483
486
  inputSchema: {
484
487
  type: "object",
485
488
  properties: {
486
- timeout_minutes: { type: "number", description: "Device-side auto-shutdown timeout in minutes (default: 5)" },
489
+ timeout_minutes: { type: "number", description: "Device-side auto-shutdown timeout in minutes (default 5 on first enable, a repeat keeps the current window)" },
487
490
  device_serial: {
488
491
  type: "string",
489
492
  description: "Target device serial from adb devices. Optional; auto-selected when exactly one device is attached. When multiple devices are attached the enable fails with the list; retry with one of the listed serials.",
@@ -729,6 +732,38 @@ export const TOOL_DEFINITIONS = [
729
732
  },
730
733
  annotations: { readOnlyHint: true },
731
734
  },
735
+ {
736
+ name: "run_test_case",
737
+ description: "Replay a case of made-up RTM frames into the app's own message handler on the device. case is a built-in name (message_changed, message_replied: a seed message then its update, 100 pairs at 10 frames a second) or the stem of ~/.slack-radar/test-cases/<name>.json, which replaces a built-in of the same name. Frames per run = repeat × events, and the rate counts every frame. Then call get_test_run(run_id, wait_seconds) until settled. A 409 active names active_run_id: get_test_run or stop_test_run it. A 409 settling, N ms left: wait that long and retry. A 400 names the refused frame. Debug builds that serve test_runs only.",
738
+ inputSchema: {
739
+ type: "object",
740
+ properties: {
741
+ case: { type: "string", description: "Built-in name or case file stem." },
742
+ repeat: { type: "integer", minimum: 1, description: "Times the case's events are sent. Default from the case." },
743
+ rate_per_second: { type: ["number", "null"], minimum: 1, maximum: 1000, description: "Frames a second, 1 to 1000, or null for a burst. Default from the case." },
744
+ },
745
+ required: ["case"],
746
+ },
747
+ annotations: { readOnlyHint: false },
748
+ },
749
+ {
750
+ name: "get_test_run",
751
+ description: "Read one replay run, or the last ten with active_run_id when run_id is omitted. wait_seconds (max 45) polls until settled; it bounds when the last read starts and each read gets 3 s; an unsettled answer carries a note, call again. settled turns true 2 quiet s after the later of the run's end and its last counted event; frames still pending hold it up to 10 s after the end, then count as ignored. Trust summary only once settled: ok and failed count handler outcomes. by_type keys can be dotted, read summary.by_type[\"MESSAGE.MESSAGE_CHANGED\"] for sent, ok, failed, max_ms and p50_ms/p90_ms/p99_ms (null under 100 counted events of that type). stop_reason and summary.failed_label say why a run ended early. elapsed_ms, achieved_rate, drain_ms, held_ms and late_sends are null until the run ends. An unknown run_id is a 404. clear_buffers drops settled runs, read them first.",
752
+ inputSchema: {
753
+ type: "object",
754
+ properties: {
755
+ run_id: { type: "string" },
756
+ wait_seconds: { type: "integer", minimum: 0, maximum: 45 },
757
+ },
758
+ },
759
+ annotations: { readOnlyHint: true },
760
+ },
761
+ {
762
+ name: "stop_test_run",
763
+ description: "Stop a replay run. 202 with the run while it stops, 200 once it has already ended, 404 unknown, 409 while still starting (retry in a moment). Its counts stay readable with get_test_run.",
764
+ inputSchema: { type: "object", properties: { run_id: { type: "string" } }, required: ["run_id"] },
765
+ annotations: { readOnlyHint: false, idempotentHint: true },
766
+ },
732
767
  ];
733
768
  /**
734
769
  * Check whether a tool call should be blocked by the session gate.
@@ -764,7 +799,7 @@ export function sessionGate(toolName, sessionEnabled, allowSwitchboardExportOffl
764
799
  {
765
800
  type: "text",
766
801
  text: JSON.stringify({
767
- error: "Radar is not active. Use /radar-enable to connect, or ask about the device to auto-enable.",
802
+ error: "Radar is not active. Run /radar-enable, then retry this call.",
768
803
  }),
769
804
  },
770
805
  ],
@@ -117,6 +117,7 @@ export declare class AndroidTransport implements DeviceTransport {
117
117
  private recordActivateFailure;
118
118
  private readArmToken;
119
119
  getLastActivateError(): string | null;
120
+ ensureLogCapture(): void;
120
121
  getLastActivateTokenFileError(): TokenFileError | null;
121
122
  resetState(): void;
122
123
  dropForward(): void;
@@ -564,9 +564,7 @@ export class AndroidTransport {
564
564
  this.radarEnabled = true;
565
565
  this.lastActivateError = null;
566
566
  this.lastActivateTokenFileError = null;
567
- registerCleanup();
568
- if (ADB)
569
- startCapture(ADB);
567
+ this.ensureLogCapture();
570
568
  }
571
569
  // Broadcast failed, device may not be connected. Recorded so the enable path can report
572
570
  // it instead of claiming success with a failing ping. radarEnabled drops too: a prior
@@ -591,6 +589,9 @@ export class AndroidTransport {
591
589
  getLastActivateError() {
592
590
  return this.lastActivateError;
593
591
  }
592
+ // One capture start for activate, a profile switch and a repeat enable; startCapture skips a live child.
593
+ ensureLogCapture() { registerCleanup(); if (ADB)
594
+ startCapture(ADB); }
594
595
  getLastActivateTokenFileError() {
595
596
  return this.lastActivateTokenFileError;
596
597
  }
@@ -761,13 +762,14 @@ export class AndroidTransport {
761
762
  this.detectedUserId = userId;
762
763
  this.currentTimeoutMinutes = timeout;
763
764
  this.radarEnabled = true;
765
+ // This broadcast landed, so the enable error it replaces is stale.
766
+ this.lastActivateError = null;
764
767
  // Profile switch means the interesting scope changed; drop the old
765
768
  // capture so the new session starts from a fresh file scoped to this
766
769
  // profile's debug run.
767
770
  if (profileChanged)
768
771
  stopCapture();
769
- registerCleanup();
770
- startCapture(ADB);
772
+ this.ensureLogCapture();
771
773
  }
772
774
  // Every listing is also the cheapest place to notice a pinned device disconnecting
773
775
  // WITHOUT an explicit re-enable (PR #94 review, stse): selectedDevice previously only
@@ -11,7 +11,23 @@ import path from "path";
11
11
  * later. Capturing to a local file from session-enable onward preserves
12
12
  * everything from the enable moment forward.
13
13
  *
14
- * Lifecycle: startCapture on activate, stopCapture on resetState/disable.
14
+ * Starts through ensureLogCapture, a no-op while a child is live:
15
+ * - A landed activate (recordActivateSuccess).
16
+ * - A landed activate_for_user, same profile or not (activateForUser).
17
+ * - An accepted repeat enable (createEnabler).
18
+ * Restarts on a fresh file:
19
+ * - A different or unknown prior profile (activateForUser).
20
+ * - Size rotation (rotateCaptureIfNeeded below).
21
+ * Stops:
22
+ * - Disable (handleSessionDisable) or device switch (onDeviceSwitch).
23
+ * - A full enable that ends disabled (runSessionEnable).
24
+ * - Its idle timer (rescheduleIdleTimer).
25
+ * - The child's own exit (startCapture).
26
+ * - MCP exit (registerCleanup).
27
+ * Survives resetState, the device-side idle timeout, a failed broadcast,
28
+ * any same-device enable that ends enabled, a thrown enable (the catch in
29
+ * createEnabler) and the self-heal auto-disables, which flip
30
+ * sessionEnabled false without stopping the capture.
15
31
  */
16
32
  const LOG_DIR = path.join(os.homedir(), ".slack-radar", "logs");
17
33
  const ROTATION_BYTES = 100 * 1024 * 1024;
@@ -248,6 +248,12 @@ export interface DeviceTransport {
248
248
  * implementations may omit it.
249
249
  */
250
250
  getLastActivateError?(): string | null;
251
+ /**
252
+ * Starts the transport's own log capture when none is live. Called after an
253
+ * activate or profile broadcast lands, and by a repeat enable the fast path
254
+ * accepts, since that path skips activate.
255
+ */
256
+ ensureLogCapture?(): void;
251
257
  /** No broadcast went out, so callers report the file problem without probing the device. */
252
258
  getLastActivateTokenFileError?(): TokenFileError | null;
253
259
  /**
@@ -197,3 +197,21 @@ export declare function runSelfHealPrecheck(): void;
197
197
  /** The awaitable core of runSelfHealPrecheck(), exported so a test can await its outcome
198
198
  * directly instead of polling for the fire-and-forget wrapper to finish. */
199
199
  export declare function runSelfHealPrecheckAsync(): Promise<void>;
200
+ export interface UpdateCheckResult {
201
+ installed: string | null;
202
+ latest: string | null;
203
+ updateAvailable: boolean;
204
+ /** The installed bundle is already newer than the app asking, so a restart (no install) picks it up. */
205
+ restartAvailable?: boolean;
206
+ error?: string;
207
+ }
208
+ /** Whether the registry has a newer Radar than the installed app, or the installed app is already
209
+ * ahead of `runningVersion` and just needs a restart. Never throws; failures land in `error`. */
210
+ export declare function checkForUpdate(runningVersion?: string): Promise<UpdateCheckResult>;
211
+ export interface UpdateNowResult {
212
+ updated: boolean;
213
+ error?: string;
214
+ }
215
+ /** Entry point for `install-app --update-now`. Reuses the self-heal rebuild, so an explicit update
216
+ * stays subject to the same npm config as the background one. */
217
+ export declare function runUpdateNow(): Promise<void>;