@slack/radar-mcp 1.25.0 → 1.27.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 (63) hide show
  1. package/README.md +47 -3
  2. package/dist/mcp/api-paths.d.ts +25 -1
  3. package/dist/mcp/api-paths.js +85 -9
  4. package/dist/mcp/dispatch.d.ts +1 -0
  5. package/dist/mcp/dispatch.js +4 -2
  6. package/dist/mcp/flags-tools.d.ts +1 -0
  7. package/dist/mcp/flags-tools.js +1 -1
  8. package/dist/mcp/index.js +36 -11
  9. package/dist/mcp/json-rows.d.ts +6 -0
  10. package/dist/mcp/json-rows.js +10 -0
  11. package/dist/mcp/radar-response.d.ts +2 -2
  12. package/dist/mcp/radar-response.js +2 -2
  13. package/dist/mcp/redact.d.ts +14 -0
  14. package/dist/mcp/redact.js +71 -0
  15. package/dist/mcp/session-enable.d.ts +1 -0
  16. package/dist/mcp/session-enable.js +8 -6
  17. package/dist/mcp/snapshot-cli.d.ts +52 -0
  18. package/dist/mcp/snapshot-cli.js +331 -0
  19. package/dist/mcp/snapshot-summary.d.ts +1 -0
  20. package/dist/mcp/snapshot-summary.js +254 -0
  21. package/dist/mcp/snapshot.d.ts +32 -3
  22. package/dist/mcp/snapshot.js +392 -125
  23. package/dist/mcp/test-runs-tools.d.ts +2 -0
  24. package/dist/mcp/test-runs-tools.js +58 -5
  25. package/dist/mcp/tools.js +32 -6
  26. package/dist/shared/android.d.ts +40 -4
  27. package/dist/shared/android.js +199 -12
  28. package/dist/shared/constants.d.ts +6 -5
  29. package/dist/shared/constants.js +6 -5
  30. package/dist/shared/feature-flags.d.ts +14 -5
  31. package/dist/shared/feature-flags.js +23 -6
  32. package/dist/shared/radar-token.d.ts +5 -5
  33. package/dist/shared/radar-token.js +24 -10
  34. package/dist/shared/switchboard-note.js +2 -1
  35. package/dist/shared/switchboard-report.js +4 -1
  36. package/dist/shared/test-case-capture.d.ts +15 -0
  37. package/dist/shared/test-case-capture.js +235 -0
  38. package/dist/shared/test-case-store.d.ts +54 -0
  39. package/dist/shared/test-case-store.js +208 -0
  40. package/dist/shared/transport.d.ts +27 -1
  41. package/dist/web/install-app.js +1 -1
  42. package/dist/web/public/index.html +2 -0
  43. package/dist/web/public/next/app.js +12 -1
  44. package/dist/web/public/next/feature-flags.js +23 -6
  45. package/dist/web/public/next/feed.js +19 -4
  46. package/dist/web/public/next/filters.js +5 -5
  47. package/dist/web/public/next/flags.js +5 -3
  48. package/dist/web/public/next/registry.js +3 -2
  49. package/dist/web/public/next/save-case.js +92 -0
  50. package/dist/web/public/next/store.js +4 -2
  51. package/dist/web/public/next/switchboard-note.js +2 -1
  52. package/dist/web/public/next/test-cases.js +328 -0
  53. package/dist/web/public/next/voice-model.js +13 -1
  54. package/dist/web/public/next/voice.js +9 -4
  55. package/dist/web/server.d.ts +1 -0
  56. package/dist/web/server.js +214 -2
  57. package/dist/web/spec.d.ts +3 -2
  58. package/dist/web/spec.js +10 -9
  59. package/package.json +1 -1
  60. package/dist/mcp/test-cases.d.ts +0 -14
  61. package/dist/mcp/test-cases.js +0 -77
  62. /package/dist/web/public/icons/{radar-1024.png → icon-1024.png} +0 -0
  63. /package/dist/web/public/icons/{radar.svg → icon.svg} +0 -0
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from "crypto";
2
- import { buildRunBody, CASE_NAME, loadCase, testCaseDir } from "./test-cases.js";
2
+ import { buildRunBody, CASE_NAME, checkCaseName, listCases, loadCase, saveCase, testCaseDir } from "../shared/test-case-store.js";
3
+ import { captureCase } from "../shared/test-case-capture.js";
3
4
  const TEST_RUNS_PATH = "/api/test_runs";
4
5
  const POST_TIMEOUT_MS = 15_000;
5
6
  const POST_DEADLINE_MS = 50_000;
@@ -23,9 +24,9 @@ async function readBack(runId, post, call, now) {
23
24
  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
25
  if (found.http_status === 404)
25
26
  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 };
27
+ ? { error: FRAME_CHECK_ERROR, http_status: 404, reason: "frame_check" }
28
+ : { error: `the device holds no run ${runId}: ${trimTail(String(post.error))}. Call run_test_case again`, run_id: runId, reason: "not_listed" };
29
+ 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, reason: "may_have_started" };
29
30
  }
30
31
  export async function handleRunTestCase(args, call, dir = testCaseDir(), newRunId = randomUUID, now = Date.now) {
31
32
  if (typeof args.case !== "string" || !args.case)
@@ -71,7 +72,7 @@ export async function handleGetTestRun(args, call, sleep = (ms) => new Promise((
71
72
  for (;;) {
72
73
  data = notFound(await call(runPath(id), { timeoutMs: POLL_TIMEOUT_MS, deadlineMs: now() + POLL_TIMEOUT_MS, reportLost: true }), id);
73
74
  if (isRequestFailure(data)) {
74
- return result(data.http_status === 404 && lastState === "starting" ? { ...data, error: FRAME_CHECK_ERROR } : data);
75
+ return result(data.http_status === 404 && lastState === "starting" ? { ...data, error: FRAME_CHECK_ERROR, reason: "frame_check" } : data);
75
76
  }
76
77
  lastState = data.state;
77
78
  if (data.settled === true)
@@ -93,3 +94,55 @@ export async function handleStopTestRun(args, call) {
93
94
  const id = args.run_id;
94
95
  return result(notFound(await call(runPath(id), { method: "DELETE" }), id));
95
96
  }
97
+ const IDS_ERROR = "ids is required, 1 to 200 RTM event ids from get_recent_rtm_events";
98
+ const fail = (error, extra = {}) => ({ data: { error, ...extra }, isError: true });
99
+ export function handleListTestCases(dir = testCaseDir()) {
100
+ return { data: listCases(dir), isError: false };
101
+ }
102
+ export async function handleSaveTestCase(args, call, dir = testCaseDir()) {
103
+ const { ids } = args;
104
+ if (!Array.isArray(ids) || ids.length < 1 || ids.length > 200 || !ids.every((id) => Number.isInteger(id) && id >= 0))
105
+ return fail(IDS_ERROR, { reason: "bad_ids" });
106
+ const repeat = args.repeat ?? 1;
107
+ if (typeof repeat !== "number" || !Number.isInteger(repeat) || repeat < 1)
108
+ return fail("repeat must be a whole number, 1 or more");
109
+ const rate = "rate_per_second" in args ? args.rate_per_second : 10;
110
+ if (rate !== null && (typeof rate !== "number" || !Number.isInteger(rate) || rate < 1 || rate > 1000))
111
+ return fail("rate_per_second must be a whole number from 1 to 1000, or null for a burst");
112
+ if (typeof args.name !== "string" || !args.name)
113
+ return fail("name is required: letters, digits, _ or -, up to 64");
114
+ const problem = checkCaseName(args.name, args.overwrite === true, dir);
115
+ if (problem)
116
+ return fail(problem.error, { reason: problem.reason });
117
+ const records = [];
118
+ const missing = [];
119
+ for (const id of [...new Set(ids)]) {
120
+ const data = await call(`/api/rtm/${id}`);
121
+ if (data.http_status === 404) {
122
+ missing.push(id);
123
+ continue;
124
+ }
125
+ if (isRequestFailure(data))
126
+ return { data, isError: true };
127
+ records.push({ ...data, id });
128
+ }
129
+ const captured = captureCase(records);
130
+ if (captured.events.length === 0) {
131
+ return fail("none of these events can be replayed", { kept: captured.kept, dropped: captured.dropped, missing });
132
+ }
133
+ const caseDef = { repeat, rate_per_second: rate, events: captured.events };
134
+ const saved = saveCase(args.name, caseDef, args.overwrite === true, dir);
135
+ if ("error" in saved)
136
+ return fail(saved.error, saved.reason ? { reason: saved.reason } : {});
137
+ return {
138
+ isError: false,
139
+ data: {
140
+ saved: saved.path, events: captured.events.length, repeat, rate_per_second: rate, kept: captured.kept,
141
+ ...(Object.keys(captured.dropped).length ? { dropped: captured.dropped } : {}),
142
+ ...(Object.keys(captured.removed).length ? { removed_block_fields: captured.removed } : {}),
143
+ ...(missing.length ? { missing } : {}),
144
+ ...(captured.seeded ? { seeded: true } : {}),
145
+ ...(captured.targets > 1 ? { note: `the updates edited ${captured.targets} different messages; the case replays them all against one seeded message per iteration` } : {}),
146
+ },
147
+ };
148
+ }
package/dist/mcp/tools.js CHANGED
@@ -88,7 +88,7 @@ export function serverInstructions(platform) {
88
88
  ].join("\n");
89
89
  }
90
90
  // Shared by the three flag tools so their wording cannot drift apart.
91
- const SESSION_VALUE_NOTE = "Rows carry session_enabled (the flag's own value the app runs now: the first-read value for a flag already read this session, or the value a read returns now for one not yet read) and restart_note when it differs from `enabled`; a row where session_enabled or enabled is absent or not a boolean is not known, never a match; only when both are booleans does a missing restart_note mean they match.";
91
+ const SESSION_VALUE_NOTE = "Rows carry session_enabled (the flag's own value the app runs now: the first-read value for a flag already read this session, or the value a read returns now for one not yet read) and restart_note when it differs from `enabled`; a toggle row where session_enabled or enabled is absent or not a boolean is not known, never a match; only when both are booleans does a missing restart_note mean they match. Experiment rows carry session_group_name (the group the first read this session returned, or a read returns now for one not yet read; \"\" is no group; read-once code may still use it until restart, for a signed-in team until it signs out) and restart_note when it differs from group_name; absent or not a string means not known, and only when both are strings does a missing restart_note mean they match; code that reads every time already runs group_name.";
92
92
  export const TOOL_DEFINITIONS = [
93
93
  {
94
94
  name: "ping",
@@ -131,7 +131,7 @@ export const TOOL_DEFINITIONS = [
131
131
  },
132
132
  {
133
133
  name: "get_recent_rtm_events",
134
- description: "Get recent RTM (Real Time Messaging) event summaries. Use when the user asks 'what just happened' / 'what's going on' (with get_recent_network_calls). Event types use subtypes when there is one (message_changed, not message).",
134
+ description: "Get recent RTM (Real Time Messaging) event summaries. Use when the user asks 'what just happened' / 'what's going on' (with get_recent_network_calls). Event types use subtypes when there is one (message_changed, not message). Pass ids to save_test_case to keep them as a replay case.",
135
135
  inputSchema: {
136
136
  type: "object",
137
137
  properties: {
@@ -233,13 +233,13 @@ export const TOOL_DEFINITIONS = [
233
233
  },
234
234
  {
235
235
  name: "get_switchboard_sessions",
236
- description: "List the Slackbot voice (switchboard) sessions the device still holds, at most 8, newest first. A session is one voice conversation attempt, from the controller starting (before any socket opens) to it ending. Each entry carries session_id, team_id, began_at, ended_at (null live), total_captured, frames {incoming, outgoing}, last_state (newest connection/mic/speaking state, absent before the first state record), levels (newest level tick, or null), server_session_id (null until named), turns ({count, last_response_ms, last_clock}, null before the first timed turn) and saved_turn_counts (per outcome), all absent on an older build. last_response_ms can be a gap between reply chunks when last_clock is resumed_from_server_answer. saved_turn_counts counts each outcome, and absent on an older device build means not counted, not zero. A server resend counts again under applied or no_line, so their sum can run above the finals and is not a lost turn. session_id restarts at 1 with the app process; go by began_at. A session already running when radar was enabled lists from its first seen record, team_id null. get_switchboard_session(id) has the records.",
236
+ description: "List the Slackbot voice (switchboard) sessions the device still holds, at most 8, newest first. A session is one voice conversation attempt, from the controller starting (before any socket opens) to it ending. Each entry carries session_id, team_id, began_at, ended_at (null live), total_captured, frames {incoming, outgoing}, last_state (newest connection/mic/speaking/user_speaking state, absent before the first state record), levels (newest level tick, or null), server_session_id (null until named), turns ({count, last_response_ms, last_clock}, null before the first timed turn) and saved_turn_counts (per outcome), all absent on an older build. last_response_ms can be a gap between reply chunks when last_clock is resumed_from_server_answer. saved_turn_counts counts each outcome, and absent on an older device build means not counted, not zero. A server resend counts again under applied or no_line, so their sum can run above the finals and is not a lost turn. session_id restarts at 1 with the app process; go by began_at. A session already running when radar was enabled lists from its first seen record, team_id null. get_switchboard_session(id) has the records.",
237
237
  inputSchema: { type: "object", properties: {} },
238
238
  annotations: { readOnlyHint: true },
239
239
  },
240
240
  {
241
241
  name: "get_switchboard_session",
242
- description: "Get one voice session's summary plus the newest `limit` of its records (events), oldest first; events is only the page. Record kinds: state = connection, mic and speaking transitions (state_kind, from, to, cause) with Server:<code> causes; frame = control frames in and out (direction, frame_type, bytes), audio frames carry frame_type audio and a byte count, never the audio; player = playback events rearm, jitter_trim, hold_refuse, reply_hold, reply_unhold, read_stall, pre_ready_drop with gap_ms, bytes_queued; phase = startup phase durations (phase, duration_ms); session = begin, end, ready (server_session_id), config (mic_encoding); levels = one meter-tick batch (started_at, sample_count, offsets_ms, mic/playback rms+peak arrays, 0..1); turn = response_ms (end of speech to first reply audio) and clock (no_card, resumed_from_tap, resumed_from_server_answer); saved_turn = outcome (applied, no_line, missing_field, other_session), has_thread; reconnect_try = trigger (restart, drop, settings), try, outcome (ready, retry, refused, gave_up, where try counts tries made and 0 means the budget was already spent); a Reconnecting state's cause is its trigger; card = card_kind (tool_approval, auth_prompt), event (shown, answered, refused, declined, closed, replaced, expired, cleared, carried), by (tap, server), card_id; a card shown or carried with no later record was still up at the session's last record. Summary server_session_ids lists ready ids. For saved_turn, no_line means no subtitle line still held the item and the turn is still kept; every turn other_session with a null server_session_id usually means session.ready named no session (a ready record with a null id) or never arrived (no ready record). Pass kind to narrow (player for stutter, state for mic and connection, phase for slow start, levels for meter history); the limit applies after the kind filter; total_captured counts every kind. This is a single page, not the whole session; for that use export_switchboard_session or query_session under source switchboard.",
242
+ description: "Get one voice session's summary plus the newest `limit` of its records (events), oldest first; events is only the page. Record kinds: state = connection, mic, speaking and user_speaking transitions (state_kind, from, to, cause) with Server:<code> and SwipedAway causes; frame = control frames in and out (direction, frame_type, bytes), audio frames carry frame_type audio and a byte count, never the audio; player = playback events rearm, jitter_trim, hold_refuse, reply_hold, reply_unhold, read_stall, pre_ready_drop with gap_ms, bytes_queued, dropped_chunks; phase = startup phase durations (phase, duration_ms); session = begin, end, ready (server_session_id), config (mic_encoding); levels = one meter-tick batch (started_at, sample_count, offsets_ms, mic/playback rms+peak arrays, 0..1); turn = response_ms (end of speech to first reply audio) and clock (no_card, resumed_from_tap, resumed_from_server_answer); saved_turn = outcome (applied, no_line, missing_field, other_session), has_thread; reconnect_try = trigger (restart, drop, settings), try, outcome (ready, retry, refused, gave_up, where try counts tries made and 0 means the budget was already spent); a Reconnecting state's cause is its trigger; card = card_kind (tool_approval, auth_prompt), event (shown, answered, refused, answer_failed, declined, closed, replaced, expired, cleared, carried), by (tap, server), card_id; a card shown or carried and not taken down since was still up at the session's last record. Summary server_session_ids lists ready ids. For saved_turn, no_line means no subtitle line still held the item and the turn is still kept; every turn other_session with a null server_session_id usually means session.ready named no session (a ready record with a null id) or never arrived (no ready record). Pass kind to narrow (player for stutter, state for mic and connection, phase for slow start, levels for meter history); the limit applies after the kind filter; total_captured counts every kind. For the whole session use export_switchboard_session or query_session under source switchboard.",
243
243
  inputSchema: {
244
244
  type: "object",
245
245
  properties: {
@@ -317,7 +317,7 @@ export const TOOL_DEFINITIONS = [
317
317
  },
318
318
  {
319
319
  name: "capture_snapshot",
320
- description: "Bundle the current Radar state into a single on-disk artifact for sharing. Writes four files to ~/.slack-radar/snapshots/snapshot-<ts>/: bundle.json (network + RTM + clog + trace buffers, up to 1000 items each — a bulk export, much larger than point queries like get_network_call_detail), logcat.tail.log (last N lines of the active capture), screenshot.png (current screen), and README.txt (receiver-facing explainer). Switchboard voice sessions are not bundled; keep them with get_switchboard_session or query_session(source=switchboard). Use when the user says 'save this', 'file this as a bug', 'share this', 'bundle this up', 'attach to a ticket', 'make me a repro', or otherwise wants a shareable reproducible handoff. PRIVACY: bundle.json contains raw API request/response bodies including auth headers, RTM message content, user/team/channel IDs, clog payloads, and performance trace spans — review before sharing externally. " +
320
+ description: "Bundle the current Radar state into a single on-disk artifact for sharing. Writes to ~/.slack-radar/snapshots/snapshot-<ts>/: summary.md (read this first: failed calls, log errors, clogs, flags), bundle.json (network + RTM + clog + trace buffers, up to 1000 items each, plus feature flags, voice-session summaries, details of failed network calls, and device and app facts), logcat.tail.log (last N log lines), screenshot.png (current screen), and README.txt (receiver-facing explainer). Use when the user says 'save this', 'file this as a bug', 'share this', 'bundle this up', 'attach to a ticket', 'make me a repro', or otherwise wants a shareable reproducible handoff. PRIVACY: auth headers, cookies and token-shaped strings are blanked by pattern by default, best effort, so still review before sharing externally; redact=false keeps them raw. " +
321
321
  "When it returns, tell the user: result.zip_path (the single shareable file), else result.path; a one-line summary of the counts; \"Privacy: \" followed by result.privacy_notice word for word, verbatim and never paraphrased, even under time pressure; if result.log_lines_truncated is true, that the 1 MB read cap cut the log lines; if result.errors is non-empty, which parts failed. If they asked to file it as a bug or attach it to a ticket, offer to attach result.zip_path through the Jira or Slack MCP; do not attach without asking.",
322
322
  inputSchema: {
323
323
  type: "object",
@@ -336,6 +336,10 @@ export const TOOL_DEFINITIONS = [
336
336
  minimum: 1,
337
337
  maximum: 10000,
338
338
  },
339
+ redact: {
340
+ type: "boolean",
341
+ description: "Blank auth headers, cookies and token-shaped strings (default: true). false keeps raw headers and tokens; only for a bundle that stays on this machine.",
342
+ },
339
343
  },
340
344
  },
341
345
  annotations: { readOnlyHint: false },
@@ -394,7 +398,7 @@ export const TOOL_DEFINITIONS = [
394
398
  {
395
399
  name: "open_radar_dashboard",
396
400
  description: "Build or refine a custom live dashboard tab in the Slack Radar web UI from a spec YOU author. " +
397
- "Suggest this when the user describes a live view the pre-built tabs (Live/Network/RTM/Clogs/Traces/Logs/Switchboard, plus the Database, Preferences and Feature Flags browsers) do not cover " +
401
+ "Suggest this when the user describes a live view the pre-built tabs (Live/Network/RTM/Clogs/Traces/Logs/Switchboard, plus the Database, Preferences, Feature Flags and Test cases browsers) do not cover " +
398
402
  "(e.g. 'graph calls per second vs response time and flag slow ones', 'beep when I get a DM'); invoke it once they agree. " +
399
403
  "Translate the request into the spec fields below and call this tool; it ensures the web dashboard is " +
400
404
  "running (default http://localhost:8100, or the port set in SLACK_RADAR_WEB_PORT) and renders your spec as a 'Custom' tab, then returns the URL to share. " +
@@ -664,6 +668,28 @@ export const TOOL_DEFINITIONS = [
664
668
  inputSchema: { type: "object", properties: { run_id: { type: "string" } }, required: ["run_id"] },
665
669
  annotations: { readOnlyHint: false, idempotentHint: true },
666
670
  },
671
+ {
672
+ name: "save_test_case",
673
+ description: "Save RTM events you captured as a replay case under ~/.slack-radar/test-cases/<name>.json. ids come from get_recent_rtm_events. Only message, message_changed and message_replied frames from the server are kept. Channel, ts, user, client and file ids become test values and all text becomes filler of the same length, so the file holds no real ids or text. Every iteration replays the updates against one seeded message. Pass overwrite to replace a file or a built-in name. Then call run_test_case with the name.",
674
+ inputSchema: {
675
+ type: "object",
676
+ properties: {
677
+ name: { type: "string", description: "Case name, letters, digits, _ or -, up to 64." },
678
+ ids: { type: "array", items: { type: "integer", minimum: 0 }, minItems: 1, maxItems: 200, description: "RTM event ids from get_recent_rtm_events." },
679
+ repeat: { type: "integer", minimum: 1, description: "Times the events are sent. Default 1." },
680
+ rate_per_second: { type: ["integer", "null"], minimum: 1, maximum: 1000, description: "Frames a second, 1 to 1000, or null for a burst. Default 10." },
681
+ overwrite: { type: "boolean", description: "Replace an existing file or a built-in name. Default false." },
682
+ },
683
+ required: ["name", "ids"],
684
+ },
685
+ annotations: { readOnlyHint: false },
686
+ },
687
+ {
688
+ name: "list_test_cases",
689
+ description: "List the built-in and saved replay cases with repeat, rate, event count and counts by type. A file that cannot load shows its error.",
690
+ inputSchema: { type: "object", properties: {} },
691
+ annotations: { readOnlyHint: true },
692
+ },
667
693
  ];
668
694
  /**
669
695
  * Check whether a tool call should be blocked by the session gate.
@@ -117,7 +117,33 @@ export interface AndroidTransportDependencies {
117
117
  spawnLogcat?: () => ChildProcess;
118
118
  /** Start the `ps` listing that labels log rows with their package. */
119
119
  spawnProcessList?: SpawnAndroidProcessList;
120
+ /**
121
+ * Let adb pick a free host port (`adb forward tcp:0`) instead of the shared RADAR_PORT, so
122
+ * parallel runs on one host never meet on a port. Only the headless snapshot command opts in.
123
+ * SLACK_RADAR_DEVICE_PORT, when it gives a usable port, still wins and keeps today's behavior.
124
+ */
125
+ ownForwardPort?: boolean;
120
126
  }
127
+ /** First `versionName` / `versionCode` in a `dumpsys package` dump (one block per user repeats them). */
128
+ export declare function parsePackageVersion(dump: string): {
129
+ version_name: string | null;
130
+ version_code: string | null;
131
+ };
132
+ /**
133
+ * The foreground component from a `dumpsys activity activities` dump. Newer builds print
134
+ * `topResumedActivity`, older ones `mResumedActivity`; the new form wins when both show.
135
+ */
136
+ export declare function parseResumedActivity(dump: string): string | null;
137
+ /** `adb shell date +%s` output as epoch ms, or null when it is not whole seconds. */
138
+ export declare function parseDeviceClockMs(out: string): number | null;
139
+ /**
140
+ * Reads the device and app facts through `run`, which takes adb argv and returns stdout or
141
+ * throws. Split out so a test can feed canned output without a device.
142
+ */
143
+ export declare function readDeviceFacts(run: (args: string[]) => string, pkg: string, serial: string | null): {
144
+ device: Record<string, string | boolean | null>;
145
+ app: Record<string, string | null>;
146
+ };
121
147
  export declare class AndroidTransport implements DeviceTransport {
122
148
  readonly platform = "android";
123
149
  get logPackage(): string;
@@ -143,17 +169,22 @@ export declare class AndroidTransport implements DeviceTransport {
143
169
  private lastTokenViaArgv;
144
170
  private selectedDevice;
145
171
  private readonly dashboardPidPackages;
172
+ private readonly ownForwardPort;
173
+ private ownedPort;
146
174
  constructor(dependencies?: AndroidTransportDependencies);
147
175
  ensureForward(): boolean;
148
176
  private rebuildForward;
177
+ private forwardFreePort;
178
+ private noPinReason;
179
+ releaseForward(): void;
149
180
  reassertForward(): boolean;
150
181
  private recordForwardIfListed;
151
182
  /**
152
183
  * reassertForward, off the event loop. Same listing-first-then-rebuild logic and the same
153
- * state fields, but every adb call runs through execFileAsync so a caller that must keep
154
- * serving HTTP while adb is slow (the dashboard's boot-arm chain) is never blocked, even
155
- * inside a single call. The sync twin stays for the MCP request paths, which have nothing
156
- * else to do while adb runs.
184
+ * state fields for the shared port, but every adb call runs through execFileAsync so a
185
+ * caller that must keep serving HTTP while adb is slow (the dashboard's boot-arm chain) is
186
+ * never blocked, even inside a single call. The sync twin stays for the MCP request paths,
187
+ * which have nothing else to do while adb runs. An own-port transport takes the sync twin.
157
188
  */
158
189
  reassertForwardAsync(): Promise<boolean>;
159
190
  private rebuildForwardAsync;
@@ -202,6 +233,11 @@ export declare class AndroidTransport implements DeviceTransport {
202
233
  recordScreen(durationS: number): string;
203
234
  getAppState(): string;
204
235
  getRecentLogs(tag: string, limit: number, grep?: string): LogResult;
236
+ getDeviceFacts(): {
237
+ device: Record<string, string | boolean | null>;
238
+ app: Record<string, string | null>;
239
+ };
240
+ deviceClockMs(): number | null;
205
241
  stopLogCapture(): void;
206
242
  listProfiles(): {
207
243
  userId: string;
@@ -5,7 +5,7 @@ import path from "path";
5
5
  import { promisify } from "util";
6
6
  import { readDebugLogBuffer } from "./debug-log.js";
7
7
  import { filterLogLines, getCaptureFilePath, isCapturing, readRecentLogs, registerCleanup, rotateCaptureIfNeeded, startCapture, stopCapture, } from "./logcat-capture.js";
8
- import { RADAR_PORT, RADAR_VERSION, slackDebugPackage, debugPackageFromPsName, debugPackageOverride, debugPackageOverrideError, SHIPPED_DEBUG_PACKAGES, setSlackDebugPackage, } from "./constants.js";
8
+ import { RADAR_PORT, setRadarPort, RADAR_VERSION, slackDebugPackage, debugPackageFromPsName, debugPackageOverride, debugPackageOverrideError, SHIPPED_DEBUG_PACKAGES, setSlackDebugPackage, } from "./constants.js";
9
9
  import { getOrCreateRadarToken } from "./radar-token.js";
10
10
  import { AmbiguousDebugPackageError, AndroidUserIdError, BareEnableError, DebugPackageOverrideError, NoDebugBuildRunningError, UnknownDebugBuildError, } from "./enable-diagnosis.js";
11
11
  import { LogSession } from "./log-session.js";
@@ -450,9 +450,11 @@ export function parseAdbDevicesOutput(raw) {
450
450
  if (parts.length < 2)
451
451
  continue;
452
452
  const serial = parts[0];
453
- const state = parts[1];
453
+ // adb prints "no permissions" as two words; reading just "no" would make a bad message.
454
+ const twoWord = parts[1] === "no" && parts[2] === "permissions";
455
+ const state = twoWord ? "no permissions" : parts[1];
454
456
  let label = serial;
455
- for (const field of parts.slice(2)) {
457
+ for (const field of parts.slice(twoWord ? 3 : 2)) {
456
458
  if (field.startsWith("model:")) {
457
459
  label = field.slice("model:".length).replace(/_/g, " ");
458
460
  break;
@@ -470,6 +472,75 @@ function spawnAndroidLogcat() {
470
472
  stdio: ["ignore", "pipe", "ignore"],
471
473
  });
472
474
  }
475
+ /** First `versionName` / `versionCode` in a `dumpsys package` dump (one block per user repeats them). */
476
+ export function parsePackageVersion(dump) {
477
+ const name = /versionName=(\S+)/.exec(dump)?.[1] ?? null;
478
+ const code = /versionCode=(\d+)/.exec(dump)?.[1] ?? null;
479
+ return { version_name: name, version_code: code };
480
+ }
481
+ /**
482
+ * The foreground component from a `dumpsys activity activities` dump. Newer builds print
483
+ * `topResumedActivity`, older ones `mResumedActivity`; the new form wins when both show.
484
+ */
485
+ export function parseResumedActivity(dump) {
486
+ for (const key of ["topResumedActivity", "mResumedActivity"]) {
487
+ const line = dump.split("\n").find((l) => l.includes(key));
488
+ const m = line ? /([A-Za-z0-9_.$]+\/[A-Za-z0-9_.$]+)/.exec(line) : null;
489
+ if (m)
490
+ return m[1];
491
+ }
492
+ return null;
493
+ }
494
+ /** `adb shell date +%s` output as epoch ms, or null when it is not whole seconds. */
495
+ export function parseDeviceClockMs(out) {
496
+ const t = out.trim();
497
+ return /^\d{1,12}$/.test(t) ? Number(t) * 1000 : null;
498
+ }
499
+ /**
500
+ * Reads the device and app facts through `run`, which takes adb argv and returns stdout or
501
+ * throws. Split out so a test can feed canned output without a device.
502
+ */
503
+ export function readDeviceFacts(run, pkg, serial) {
504
+ const attempt = (fn) => {
505
+ try {
506
+ return fn();
507
+ }
508
+ catch {
509
+ return null;
510
+ }
511
+ };
512
+ // One shell round trip for the six props; getprop prints an empty line for an unset one, so
513
+ // the lines stay in step with the names.
514
+ const propNames = ["ro.product.model", "ro.product.manufacturer", "ro.build.version.release", "ro.build.version.sdk", "ro.kernel.qemu", "ro.boot.qemu"];
515
+ const propOut = attempt(() => run(["shell", `for p in ${propNames.join(" ")}; do getprop $p; done`]));
516
+ const props = propOut === null ? [] : propOut.split("\n");
517
+ const prop = (name) => props[propNames.indexOf(name)]?.trim() || null;
518
+ // Older images set ro.kernel.qemu, newer ones only ro.boot.qemu.
519
+ const isEmulator = propOut === null ? null : prop("ro.kernel.qemu") === "1" || prop("ro.boot.qemu") === "1";
520
+ // `adb shell` re-parses its args on the device, so a package name with shell characters
521
+ // is never sent; it only ever comes from config, and a dot-separated name is all it needs.
522
+ // Both dumps are large, so grep keeps only the lines the parsers read on the device side.
523
+ const pkgDump = /^[A-Za-z0-9_.]+$/.test(pkg)
524
+ ? attempt(() => run(["shell", `dumpsys package ${pkg} | grep -E 'versionName|versionCode'`]))
525
+ : null;
526
+ const actDump = attempt(() => run(["shell", "dumpsys activity activities | grep -E 'topResumedActivity|mResumedActivity'"]));
527
+ const version = pkgDump ? parsePackageVersion(pkgDump) : { version_name: null, version_code: null };
528
+ return {
529
+ device: {
530
+ model: prop("ro.product.model"),
531
+ manufacturer: prop("ro.product.manufacturer"),
532
+ android_release: prop("ro.build.version.release"),
533
+ sdk: prop("ro.build.version.sdk"),
534
+ emulator: isEmulator,
535
+ serial,
536
+ },
537
+ app: {
538
+ package: pkg,
539
+ ...version,
540
+ resumed_activity: actDump ? parseResumedActivity(actDump) : null,
541
+ },
542
+ };
543
+ }
473
544
  export class AndroidTransport {
474
545
  platform = "android";
475
546
  get logPackage() { return slackDebugPackage(); }
@@ -531,7 +602,12 @@ export class AndroidTransport {
531
602
  // body and web /health. Not cleared by resetState: the env pin is sticky by design.
532
603
  selectedDevice = null;
533
604
  dashboardPidPackages;
605
+ ownForwardPort;
606
+ // The port adb gave this process; null until the first own-port forward lands.
607
+ ownedPort = null;
534
608
  constructor(dependencies = {}) {
609
+ this.ownForwardPort =
610
+ dependencies.ownForwardPort === true && !(Number(process.env.SLACK_RADAR_DEVICE_PORT) || 0);
535
611
  this.dashboardPidPackages = new AndroidPidPackageMap(dependencies.spawnProcessList);
536
612
  const spawnLogcat = dependencies.spawnLogcat ?? spawnAndroidLogcat;
537
613
  this.logSession = new LogSession(() => {
@@ -554,6 +630,8 @@ export class AndroidTransport {
554
630
  this.lastForwardError = adbNotFoundError();
555
631
  return false;
556
632
  }
633
+ if (this.ownForwardPort)
634
+ return this.forwardFreePort();
557
635
  // Drop any existing mapping first. Re-issuing `adb forward` over a stale mapping
558
636
  // (one whose device end died, e.g. after a device disconnect, OR one a separate
559
637
  // process on this host repointed to a different device) has been observed to leave
@@ -583,6 +661,77 @@ export class AndroidTransport {
583
661
  return false;
584
662
  }
585
663
  }
664
+ // Own-port mode: ask adb for a free port. Never removes anything on a rebuild, because an
665
+ // old port we no longer see in the listing may be gone or now someone else's.
666
+ forwardFreePort() {
667
+ // Without a pin the listing check is skipped, so every read would take a new port.
668
+ if (!process.env.ANDROID_SERIAL) {
669
+ this.lastForwardError = this.noPinReason();
670
+ return false;
671
+ }
672
+ try {
673
+ const out = execSync(`${ADB} forward tcp:0 localabstract:${SOCKET_NAME}`, {
674
+ timeout: 5000,
675
+ encoding: "utf-8",
676
+ stdio: ["ignore", "pipe", "pipe"],
677
+ }).trim();
678
+ const port = /^\d+$/.test(out) ? Number(out) : 0;
679
+ if (port < 1 || port > 65535) {
680
+ this.lastForwardError = "adb did not report the forwarded port";
681
+ return false;
682
+ }
683
+ setRadarPort(port);
684
+ this.ownedPort = port;
685
+ this.portForwarded = true;
686
+ this.lastForwardError = null;
687
+ return true;
688
+ }
689
+ catch (e) {
690
+ this.lastForwardError = e.message;
691
+ return false;
692
+ }
693
+ }
694
+ // Selecting a device leaves the pin empty when nothing is in the `device` state, so say
695
+ // what the listing shows (an offline or unauthorized device) instead of a bare "not pinned".
696
+ noPinReason() {
697
+ const devices = this.listDevices();
698
+ // A failed listing could not tell us anything, so it never reads as "nothing attached".
699
+ if (devices === null)
700
+ return "could not list devices (adb devices failed)";
701
+ if (devices.length === 0)
702
+ return "no device is attached";
703
+ if (devices.some((d) => d.state === "device")) {
704
+ return "no device is pinned, so the forwarded port cannot be checked";
705
+ }
706
+ return `no device is ready: ${devices.map((d) => `${d.serial} (${d.state})`).join(", ")}`;
707
+ }
708
+ // Removes the forward this process made, and only while the listing still shows it as ours
709
+ // (same serial, same socket). Best effort: a forward left behind stays until the device
710
+ // disconnects or the adb server restarts.
711
+ releaseForward() {
712
+ const serial = process.env.ANDROID_SERIAL;
713
+ if (!this.ownForwardPort || this.ownedPort === null || !serial || !ADB)
714
+ return;
715
+ try {
716
+ const list = execSync(`${ADB} forward --list`, {
717
+ timeout: 5000,
718
+ encoding: "utf-8",
719
+ stdio: ["ignore", "pipe", "ignore"],
720
+ });
721
+ const ours = `${serial} tcp:${this.ownedPort} localabstract:${SOCKET_NAME}`;
722
+ if (!list.split("\n").some((line) => line.trim() === ours))
723
+ return;
724
+ execSync(`${ADB} forward --remove tcp:${this.ownedPort}`, {
725
+ timeout: 5000,
726
+ stdio: ["ignore", "ignore", "ignore"],
727
+ });
728
+ // Gone now, so a second call (end of run, then exit hook) has nothing to remove.
729
+ this.ownedPort = null;
730
+ }
731
+ catch {
732
+ // Best effort.
733
+ }
734
+ }
586
735
  // Called before every HTTP-based device read (see transport.ts's doc comment for why:
587
736
  // this process's own portForwarded cache cannot detect a repoint made by a SEPARATE
588
737
  // process sharing the host-global port). A full forward --remove + add on every read
@@ -592,7 +741,9 @@ export class AndroidTransport {
592
741
  // RADAR_PORT at our pinned serial.
593
742
  reassertForward() {
594
743
  const serial = process.env.ANDROID_SERIAL;
595
- if (serial && ADB) {
744
+ // Before our own port exists, RADAR_PORT is still the shared default and may be someone else's.
745
+ const portIsOurs = !this.ownForwardPort || this.ownedPort !== null;
746
+ if (serial && ADB && portIsOurs) {
596
747
  try {
597
748
  const list = execSync(`${ADB} forward --list`, {
598
749
  timeout: 5000,
@@ -603,8 +754,12 @@ export class AndroidTransport {
603
754
  return true;
604
755
  }
605
756
  catch {
606
- // Listing failed; fall through to the unconditional rebuild below, which
607
- // surfaces a concrete error if adb itself is unreachable.
757
+ // Could not tell is not "gone": a rebuild here would take a second port while the
758
+ // first is still live. Only own-port mode refuses; the shared port keeps the rebuild.
759
+ if (this.ownForwardPort) {
760
+ this.lastForwardError = "adb could not list forwards";
761
+ return false;
762
+ }
608
763
  }
609
764
  }
610
765
  return this.rebuildForward();
@@ -621,12 +776,16 @@ export class AndroidTransport {
621
776
  }
622
777
  /**
623
778
  * reassertForward, off the event loop. Same listing-first-then-rebuild logic and the same
624
- * state fields, but every adb call runs through execFileAsync so a caller that must keep
625
- * serving HTTP while adb is slow (the dashboard's boot-arm chain) is never blocked, even
626
- * inside a single call. The sync twin stays for the MCP request paths, which have nothing
627
- * else to do while adb runs.
779
+ * state fields for the shared port, but every adb call runs through execFileAsync so a
780
+ * caller that must keep serving HTTP while adb is slow (the dashboard's boot-arm chain) is
781
+ * never blocked, even inside a single call. The sync twin stays for the MCP request paths,
782
+ * which have nothing else to do while adb runs. An own-port transport takes the sync twin.
628
783
  */
629
784
  async reassertForwardAsync() {
785
+ // Own-port rules (keep the port on a failed listing, never touch the shared port) live
786
+ // only in the sync path, so this one defers to it instead of repeating them.
787
+ if (this.ownForwardPort)
788
+ return this.reassertForward();
630
789
  const serial = process.env.ANDROID_SERIAL;
631
790
  if (serial && ADB) {
632
791
  try {
@@ -643,8 +802,8 @@ export class AndroidTransport {
643
802
  }
644
803
  return this.rebuildForwardAsync();
645
804
  }
646
- // rebuildForward, off the event loop. Mirrors the sync twin step for step: drop any
647
- // existing mapping (failure is harmless), then add ours and record the outcome.
805
+ // rebuildForward's shared-port branch, off the event loop: drop any existing mapping
806
+ // (failure is harmless), then add ours and record the outcome.
648
807
  async rebuildForwardAsync() {
649
808
  if (!ADB) {
650
809
  this.lastForwardError = adbNotFoundError();
@@ -951,6 +1110,34 @@ export class AndroidTransport {
951
1110
  source: "logcat_ring",
952
1111
  };
953
1112
  }
1113
+ getDeviceFacts() {
1114
+ const run = (args) => {
1115
+ if (!ADB)
1116
+ throw new Error("adb not found");
1117
+ return execFileSync(ADB, args, {
1118
+ timeout: 5000,
1119
+ encoding: "utf-8",
1120
+ maxBuffer: 32 * 1024 * 1024,
1121
+ stdio: ["ignore", "pipe", "ignore"],
1122
+ });
1123
+ };
1124
+ return readDeviceFacts(run, slackDebugPackage(), this.getSelectedDevice()?.serial ?? null);
1125
+ }
1126
+ deviceClockMs() {
1127
+ if (!ADB)
1128
+ return null;
1129
+ try {
1130
+ const out = execFileSync(ADB, ["shell", "date", "+%s"], {
1131
+ timeout: 5000,
1132
+ encoding: "utf-8",
1133
+ stdio: ["ignore", "pipe", "ignore"],
1134
+ });
1135
+ return parseDeviceClockMs(out);
1136
+ }
1137
+ catch {
1138
+ return null;
1139
+ }
1140
+ }
954
1141
  stopLogCapture() {
955
1142
  stopCapture();
956
1143
  this.logSession.stop();
@@ -25,11 +25,12 @@ export declare const RADAR_VERSION: string;
25
25
  */
26
26
  export declare let RADAR_PORT: number;
27
27
  /**
28
- * Override RADAR_PORT after module load. Called exactly once, only by the webapp
29
- * auto-detect/explicit-platform path in mcp/index.ts's createTransport() -- never on the
30
- * android path, so android's RADAR_PORT resolution stays byte-for-byte identical to
31
- * today. ES module `let` exports are live bindings, so every existing importer (stream.ts,
32
- * android.ts, index.ts's radarRequest) sees the new value immediately, with no re-import.
28
+ * Override RADAR_PORT after module load. Called by the webapp auto-detect/explicit-platform
29
+ * path in mcp/index.ts's createTransport(), and by the headless snapshot command's own-port
30
+ * forward (AndroidTransport with ownForwardPort) -- never on the MCP server's android path,
31
+ * so android's RADAR_PORT resolution there stays byte-for-byte identical to today. ES module
32
+ * `let` exports are live bindings, so every existing importer (stream.ts, android.ts,
33
+ * index.ts's radarRequest) sees the new value immediately, with no re-import.
33
34
  */
34
35
  export declare function setRadarPort(port: number): void;
35
36
  /** Host address for the forwarded connection. */
@@ -38,11 +38,12 @@ export const RADAR_VERSION = (() => {
38
38
  */
39
39
  export let RADAR_PORT = Number(process.env.SLACK_RADAR_DEVICE_PORT) || 8099;
40
40
  /**
41
- * Override RADAR_PORT after module load. Called exactly once, only by the webapp
42
- * auto-detect/explicit-platform path in mcp/index.ts's createTransport() -- never on the
43
- * android path, so android's RADAR_PORT resolution stays byte-for-byte identical to
44
- * today. ES module `let` exports are live bindings, so every existing importer (stream.ts,
45
- * android.ts, index.ts's radarRequest) sees the new value immediately, with no re-import.
41
+ * Override RADAR_PORT after module load. Called by the webapp auto-detect/explicit-platform
42
+ * path in mcp/index.ts's createTransport(), and by the headless snapshot command's own-port
43
+ * forward (AndroidTransport with ownForwardPort) -- never on the MCP server's android path,
44
+ * so android's RADAR_PORT resolution there stays byte-for-byte identical to today. ES module
45
+ * `let` exports are live bindings, so every existing importer (stream.ts, android.ts,
46
+ * index.ts's radarRequest) sees the new value immediately, with no re-import.
46
47
  */
47
48
  export function setRadarPort(port) {
48
49
  RADAR_PORT = port;
@@ -6,13 +6,22 @@
6
6
  */
7
7
  export declare function friendlyFeatureFlagError(error: unknown): string;
8
8
  /**
9
- * The one sentence for a flag whose latest value differs from what the app runs. A flag the app
10
- * read once keeps that value until restart, so `enabled` (latest or override) can differ from
11
- * `session_enabled`. Only two real booleans that differ earn a note: an absent or non-boolean
12
- * session_enabled is "not known", and saying nothing there is the honest answer.
9
+ * The sentence (`note`) and the short tab text (`label`) for a flag whose latest value differs from
10
+ * what the app runs. An experiment's label names the group itself, since a group has no ON/OFF to
11
+ * flip. A flag the app read once keeps that value until restart, so the latest value (`enabled` on a toggle,
12
+ * `group_name` on an experiment; fetched or override) can differ from the session value
13
+ * (`session_enabled`, `session_group_name`). Only two real values of
14
+ * the right type that differ earn a note: an absent or mistyped session value is "not known", and
15
+ * saying nothing there is the honest answer. An experiment's "" is a read that found no group, and
16
+ * its note is hedged because read-once code may still use the session group, not that it must.
13
17
  */
14
18
  export declare function flagRestartNote(row: {
15
19
  enabled?: unknown;
16
20
  session_enabled?: unknown;
21
+ group_name?: unknown;
22
+ session_group_name?: unknown;
17
23
  is_overridden?: unknown;
18
- }): string | undefined;
24
+ }): {
25
+ note: string;
26
+ label: string;
27
+ } | undefined;