@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
@@ -4,6 +4,11 @@ import os from "os";
4
4
  import path from "path";
5
5
  import { RADAR_VERSION } from "../shared/constants.js";
6
6
  import { getCaptureFilePath, readTailBytes } from "../shared/logcat-capture.js";
7
+ import { switchboardListPath } from "../shared/switchboard.js";
8
+ import { buildApiPath } from "./api-paths.js";
9
+ import { asObj, rowsOf } from "./json-rows.js";
10
+ import { redactDeep, redactText } from "./redact.js";
11
+ import { buildSnapshotSummary } from "./snapshot-summary.js";
7
12
  /**
8
13
  * `capture_snapshot` composer: bundles everything Radar has seen into a
9
14
  * single on-disk artifact so a user can attach it to a Jira, drop it in a
@@ -11,9 +16,11 @@ import { getCaptureFilePath, readTailBytes } from "../shared/logcat-capture.js";
11
16
  * tool outputs.
12
17
  *
13
18
  * Snapshot contents:
14
- * - `bundle.json` — device-side buffers (net + RTM + clogs + traces) plus metadata
19
+ * - `summary.md` — the short read-me-first digest of the run
20
+ * - `bundle.json` — device-side buffers (net + RTM + clogs + traces + flags +
21
+ * voice sessions), failed-call details, device and app facts, metadata
15
22
  * - `screenshot.png` — current screen (optional)
16
- * - `logcat.tail.log` — last N lines of the active capture file (optional)
23
+ * - `logcat.tail.log` — last N lines of the log (optional)
17
24
  *
18
25
  * Written to `~/.slack-radar/snapshots/snapshot-<ts>/`. No cleanup: snapshots
19
26
  * are user-triggered, small, and should persist for post-hoc inspection.
@@ -24,30 +31,44 @@ const DEFAULT_LOG_TAIL_LINES = 500;
24
31
  const MAX_LOG_TAIL_LINES = 10_000;
25
32
  const DEFAULT_LOG_TAIL_BYTES = 1 * 1024 * 1024; // 1 MB bound on file read
26
33
  // Restrictive permissions on the snapshot dir and its files. The bundle
27
- // contains network request/response bodies (including auth headers),
28
- // message content, and user IDs — readable only by the owning user.
34
+ // can hold request details, message content and user IDs, so it is
35
+ // readable only by the owning user.
29
36
  const DIR_MODE = 0o700;
30
37
  const FILE_MODE = 0o600;
31
- const BUNDLE_README = `Slack Radar snapshot
38
+ // Failed-call detail pass limits.
39
+ const DETAIL_READ_CAP = 100;
40
+ const DETAIL_KEEP_CAP = 25;
41
+ const DETAIL_BUDGET_MS = 20_000;
42
+ const REQUEST_BODY_CAP = 4 * 1024;
43
+ const RESPONSE_BODY_CAP = 8 * 1024;
44
+ const SWITCHBOARD_KEEP = 20;
45
+ const CONTENTS_LINE = "summaries of network, RTM and clog rows and of trace spans, details (headers and bodies) of failed or requested network calls, feature flags, voice-session summaries, device logs (the app's own log buffer, or logcat from every app on the device), user and org IDs, and device and app facts";
46
+ function privacyNotice(redacted) {
47
+ return redacted
48
+ ? `bundle.json holds ${CONTENTS_LINE}. Auth headers, cookies and token-shaped strings are blanked by pattern, best effort, so review before sharing externally. screenshot.png is never redacted.`
49
+ : `Redaction is off. bundle.json holds ${CONTENTS_LINE}, with auth headers, cookies and tokens left as the device sent them. Review before sharing externally.`;
50
+ }
51
+ function bundleReadme(redacted) {
52
+ return `Slack Radar snapshot
32
53
  ====================
33
54
 
34
55
  This directory is a point-in-time bundle of Radar state.
35
56
 
36
57
  Files:
37
- - bundle.json: device-side network/RTM/clog/trace buffers, counts, and metadata.
58
+ - summary.md: short digest of the run. Read this first.
59
+ - bundle.json: device-side network/RTM/clog/trace buffers, feature flags, voice
60
+ sessions, failed-call details, device and app facts, counts, and metadata.
38
61
  Its mcp_version field records which @slack/radar-mcp produced this bundle.
39
- - logcat.tail.log (optional): last N lines of the on-device logcat capture.
62
+ - logcat.tail.log (optional): last N lines of the device log.
40
63
  - screenshot.png (optional): current screen.
41
64
 
42
- Privacy: bundle.json contains raw API request/response bodies (auth headers,
43
- tokens), RTM message content, user IDs, channel IDs, clog payloads, and
44
- performance trace spans. Review before sharing externally. This bundle lives
45
- on your local disk only; nothing is uploaded anywhere by Radar.
65
+ Privacy: ${privacyNotice(redacted)}
66
+ This bundle lives on your local disk only; nothing is uploaded anywhere by Radar.
46
67
 
47
68
  To inspect: cat bundle.json | jq .
48
69
  To share: zip -r snapshot.zip . then attach the zip.
49
70
  `;
50
- const PRIVACY_NOTICE = "bundle.json contains raw API request/response bodies (including auth headers), RTM message content, user IDs, clog payloads, and performance trace spans. Review before sharing externally.";
71
+ }
51
72
  /**
52
73
  * Resolve the output directory for a snapshot. Exported for tests.
53
74
  */
@@ -95,9 +116,162 @@ export function readRecentLogTail(requestedLimit = DEFAULT_LOG_TAIL_LINES) {
95
116
  const tail = lines.slice(Math.max(0, lines.length - limit));
96
117
  return { text: tail.join("\n"), truncated };
97
118
  }
119
+ /** A call whose recorded status says it failed: 400 and up, or 0 and below. */
120
+ export function isFailedCall(row) {
121
+ const s = row.status_code;
122
+ return typeof s === "number" && Number.isFinite(s) && (s >= 400 || s <= 0);
123
+ }
124
+ /**
125
+ * The device buffers a snapshot reads, in fetch order. `rows` names the list inside the
126
+ * envelope; `keep` builds the run-window filter (none for flags, which are not timed).
127
+ */
128
+ const BUFFERS = [
129
+ { key: "network", path: buildBufferPath("network"), rows: "calls", label: "network buffer", keep: atOrAfter },
130
+ { key: "rtm", path: buildBufferPath("rtm"), rows: "events", label: "rtm buffer", keep: atOrAfter },
131
+ { key: "clogs", path: buildBufferPath("clogs"), rows: "clogs", label: "clog buffer", keep: atOrAfter },
132
+ { key: "traces", path: buildBufferPath("traces"), rows: "traces", label: "trace buffer", keep: atOrAfter },
133
+ { key: "feature_flags", path: "/api/feature_flags", rows: "feature_flags", label: "feature_flags buffer" },
134
+ {
135
+ key: "switchboard",
136
+ path: switchboardListPath(),
137
+ rows: "sessions",
138
+ label: "switchboard buffer",
139
+ // A session still open has no end yet, so it always overlaps the window.
140
+ keep: (since) => (s) => s.ended_at == null || Number(s.ended_at) >= since,
141
+ },
142
+ ];
143
+ /** Copy of a list envelope with only the rows that pass `keep`; other fields untouched. */
144
+ function filterEnvelope(body, key, keep) {
145
+ const b = asObj(body);
146
+ if (!b || !Array.isArray(b[key]))
147
+ return body;
148
+ return { ...b, [key]: b[key].filter((r) => keep(asObj(r) ?? {})) };
149
+ }
150
+ function atOrAfter(since) {
151
+ // A row with no usable timestamp cannot be judged, so it stays.
152
+ return (row) => typeof row.timestamp !== "number" || row.timestamp >= since;
153
+ }
154
+ function cut(text, cap) {
155
+ return text.length > cap ? { text: text.slice(0, cap), cut: true } : { text, cut: false };
156
+ }
157
+ function bodyError(responseBody) {
158
+ if (typeof responseBody !== "string")
159
+ return { ok: null, error: null };
160
+ try {
161
+ const parsed = asObj(JSON.parse(responseBody));
162
+ if (!parsed)
163
+ return { ok: null, error: null };
164
+ const ok = typeof parsed.ok === "boolean" ? parsed.ok : null;
165
+ const e = parsed.error;
166
+ const error = typeof e === "string" ? e : e == null ? null : JSON.stringify(e).slice(0, 200);
167
+ return { ok, error };
168
+ }
169
+ catch {
170
+ return { ok: null, error: null };
171
+ }
172
+ }
173
+ /** Keeps the call in the bucket up to the cap; past it the bucket says it dropped some. */
174
+ function keepCapped(bucket, call) {
175
+ if (bucket.calls.length < DETAIL_KEEP_CAP)
176
+ bucket.calls.push(call);
177
+ else
178
+ bucket.truncated = true;
179
+ }
180
+ /** A body cut to `cap`; redacted first so a cut cannot split a secret value from its key. */
181
+ function cutBody(v, cap, redact) {
182
+ if (typeof v !== "string")
183
+ return { value: v, cut: false };
184
+ const r = cut(redact ? redactText(v) : v, cap);
185
+ return { value: r.text, cut: r.cut };
186
+ }
98
187
  /**
99
- * Write a snapshot bundle to disk. The caller supplies `fetchBuffer` (a
100
- * callback that hits the device's HTTP endpoint for a given buffer name)
188
+ * Reads /api/network/<id> for the newest calls and keeps the failed ones (and the ones a
189
+ * caller asked for by URL) with headers and cut bodies. Bodies are redacted BEFORE they are
190
+ * cut, so a cut cannot split a secret value from the key that marks it.
191
+ */
192
+ async function collectNetworkDetails(calls, fetchJson, detailUrls, redact, budgetMs) {
193
+ const newest = calls.slice().sort((a, b) => Number(b.timestamp ?? 0) - Number(a.timestamp ?? 0));
194
+ const wanted = (c) => typeof c.url === "string" && detailUrls.some((u) => u !== "" && c.url.includes(u));
195
+ const failures = { checked: 0, calls: [], truncated: false, unread: 0 };
196
+ const matches = { checked: 0, calls: [], truncated: false };
197
+ let checked = 0;
198
+ const started = Date.now();
199
+ let budgetSpent = false;
200
+ // A call whose status already says it failed stays listed even when its details could not
201
+ // be read; the row from the list is all there is, and detail_error says why. Only a skipped
202
+ // read counts as unread: a read that threw or came back empty was already counted as checked.
203
+ const keepBare = (call, why, skipped = false) => {
204
+ if (!isFailedCall(call))
205
+ return;
206
+ if (skipped)
207
+ failures.unread = (failures.unread ?? 0) + 1;
208
+ keepCapped(failures, { ...call, detail_error: why });
209
+ };
210
+ for (let i = 0; i < newest.length; i++) {
211
+ const call = newest[i];
212
+ if (i >= DETAIL_READ_CAP) {
213
+ keepBare(call, "details not read: past the first 100 calls", true);
214
+ if (wanted(call))
215
+ matches.truncated = true;
216
+ continue;
217
+ }
218
+ if (!budgetSpent && Date.now() - started > budgetMs) {
219
+ budgetSpent = true;
220
+ failures.truncated = true;
221
+ if (detailUrls.length > 0)
222
+ matches.truncated = true;
223
+ }
224
+ if (budgetSpent) {
225
+ keepBare(call, "details not read: time budget spent", true);
226
+ continue;
227
+ }
228
+ const detailPath = buildApiPath("get_network_call_detail", { id: call.id });
229
+ if (!detailPath) {
230
+ keepBare(call, "details not read: no usable call id", true);
231
+ continue;
232
+ }
233
+ checked++;
234
+ let detail;
235
+ try {
236
+ detail = asObj(await fetchJson(detailPath));
237
+ }
238
+ catch (e) {
239
+ keepBare(call, `details not read: ${e.message}`);
240
+ continue;
241
+ }
242
+ if (!detail) {
243
+ keepBare(call, "details not read: empty reply");
244
+ continue;
245
+ }
246
+ const { ok, error } = bodyError(detail.response_body);
247
+ const isFailed = isFailedCall(call) || ok === false;
248
+ const isWanted = wanted(call);
249
+ if (!isFailed && !isWanted)
250
+ continue;
251
+ const req = cutBody(detail.request_body, REQUEST_BODY_CAP, redact);
252
+ const res = cutBody(detail.response_body, RESPONSE_BODY_CAP, redact);
253
+ const kept = {
254
+ ...call,
255
+ request_headers: detail.request_headers ?? null,
256
+ response_headers: detail.response_headers ?? null,
257
+ request_body: req.value ?? null,
258
+ response_body: res.value ?? null,
259
+ ...(req.cut ? { request_body_truncated: true } : {}),
260
+ ...(res.cut ? { response_body_truncated: true } : {}),
261
+ error,
262
+ };
263
+ if (isFailed)
264
+ keepCapped(failures, kept);
265
+ if (isWanted)
266
+ keepCapped(matches, kept);
267
+ }
268
+ failures.checked = checked;
269
+ matches.checked = checked;
270
+ return { failures, matches: detailUrls.length > 0 ? matches : null };
271
+ }
272
+ /**
273
+ * Write a snapshot bundle to disk. The caller supplies `fetchJson` (a
274
+ * callback that GETs a device-side Radar path and throws on a device error)
101
275
  * so this module does not need to know how `radarRequest` works — easier
102
276
  * to test and keeps the device-HTTP plumbing in `index.ts`.
103
277
  *
@@ -105,9 +279,11 @@ export function readRecentLogTail(requestedLimit = DEFAULT_LOG_TAIL_LINES) {
105
279
  * snapshot still lands on disk with whatever succeeded; failures are
106
280
  * collected in `result.errors` so the model can tell the user.
107
281
  */
108
- export async function createSnapshot(device, fetchBuffer, opts = {}, now = Date.now(), snapshotRoot = SNAPSHOT_DIR) {
282
+ export async function createSnapshot(device, fetchJson, opts = {}, now = Date.now(), snapshotRoot = SNAPSHOT_DIR) {
109
283
  const includeLogs = opts.includeLogs !== false;
110
284
  const includeScreenshot = opts.includeScreenshot !== false;
285
+ const redact = opts.redact !== false;
286
+ const since = typeof opts.since === "number" && Number.isFinite(opts.since) ? opts.since : null;
111
287
  // Clamp log_tail_lines at the composer boundary. The handler and schema
112
288
  // validate too; this is defense-in-depth so no downstream consumer sees
113
289
  // a pathological value.
@@ -118,78 +294,138 @@ export async function createSnapshot(device, fetchBuffer, opts = {}, now = Date.
118
294
  ? Math.floor(opts.logTailLines)
119
295
  : DEFAULT_LOG_TAIL_LINES;
120
296
  const dir = buildSnapshotDir(now, snapshotRoot);
121
- fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE });
297
+ fs.mkdirSync(snapshotRoot, { recursive: true, mode: DIR_MODE });
298
+ // The leaf is not recursive: in a shared --out root someone else could plant this name first,
299
+ // and an existing folder or symlink must fail with EEXIST instead of being written into.
300
+ fs.mkdirSync(dir, { mode: DIR_MODE });
122
301
  // `mkdirSync({ recursive: true, mode })` only applies the mode to
123
- // directories it CREATES. If `~/.slack-radar/` or `.../snapshots/`
124
- // already existed (e.g. created by a pre-R1 build or by the logcat
125
- // capture module with default umask → 0o755), they keep old perms.
126
- // Tighten them to 0o700 on every snapshot so the parent tree cannot
127
- // leak directory-listing on a shared host.
128
- for (const p of [snapshotRoot, path.dirname(snapshotRoot)]) {
129
- try {
130
- if (fs.existsSync(p))
131
- fs.chmodSync(p, DIR_MODE);
132
- }
133
- catch {
134
- // Best effort; not fatal.
302
+ // directories it CREATES. Only the default root (and its parent) get
303
+ // tightened: a root the caller picked is theirs, and chmodding it or its
304
+ // parent could lock them out of a shared directory.
305
+ if (snapshotRoot === SNAPSHOT_DIR) {
306
+ for (const p of [snapshotRoot, path.dirname(snapshotRoot)]) {
307
+ try {
308
+ if (fs.existsSync(p))
309
+ fs.chmodSync(p, DIR_MODE);
310
+ }
311
+ catch {
312
+ // Best effort; not fatal.
313
+ }
135
314
  }
136
315
  }
137
316
  const files = [];
138
- const errors = [];
139
- let network = null;
140
- let rtm = null;
141
- let clogs = null;
142
- let traces = null;
143
- const fetched = { network: false, rtm: false, clogs: false, traces: false };
144
- // Device-side buffers. Failures are individually caught so one failing
145
- // buffer does not nuke the whole snapshot. `fetched` distinguishes
146
- // "empty because the buffer was empty" from "null because the fetch
147
- // failed" — counts alone cannot tell these apart.
148
- try {
149
- network = await fetchBuffer("network");
150
- fetched.network = true;
151
- }
152
- catch (e) {
153
- errors.push(`network buffer: ${e.message}`);
154
- }
155
- try {
156
- rtm = await fetchBuffer("rtm");
157
- fetched.rtm = true;
317
+ const errors = [...(opts.notes ?? [])];
318
+ const buffers = {
319
+ network: null,
320
+ rtm: null,
321
+ clogs: null,
322
+ traces: null,
323
+ feature_flags: null,
324
+ switchboard: null,
325
+ };
326
+ const fetched = {
327
+ network: false,
328
+ rtm: false,
329
+ clogs: false,
330
+ traces: false,
331
+ feature_flags: false,
332
+ switchboard: false,
333
+ };
334
+ // Device-side buffers, one after the other. Failures are individually caught so one failing
335
+ // buffer does not nuke the whole snapshot. `fetched` distinguishes "empty because the buffer
336
+ // was empty" from "null because the fetch failed" — counts alone cannot tell these apart.
337
+ // Traces capture from app start (like clogs); an older debug build without /api/traces fails
338
+ // that one fetch and it lands in errors[] like any other buffer.
339
+ for (const buf of BUFFERS) {
340
+ try {
341
+ buffers[buf.key] = await fetchJson(buf.path);
342
+ fetched[buf.key] = true;
343
+ }
344
+ catch (e) {
345
+ errors.push(`${buf.label}: ${e.message}`);
346
+ }
158
347
  }
159
- catch (e) {
160
- errors.push(`rtm buffer: ${e.message}`);
348
+ // Run window. total_captured stays as the device sent it: it says how much the
349
+ // buffer held, which is still true after the cut.
350
+ if (since !== null) {
351
+ for (const buf of BUFFERS) {
352
+ if (buf.keep)
353
+ buffers[buf.key] = filterEnvelope(buffers[buf.key], buf.rows, buf.keep(since));
354
+ }
161
355
  }
162
- try {
163
- clogs = await fetchBuffer("clogs");
164
- fetched.clogs = true;
356
+ // Newest voice sessions first, so the cut keeps the ones a run most likely cares about.
357
+ const sb = asObj(buffers.switchboard);
358
+ if (sb && Array.isArray(sb.sessions)) {
359
+ const sessions = rowsOf(sb, "sessions")
360
+ .sort((x, y) => Number(y.began_at ?? 0) - Number(x.began_at ?? 0))
361
+ .slice(0, SWITCHBOARD_KEEP);
362
+ buffers.switchboard = { ...sb, sessions };
165
363
  }
166
- catch (e) {
167
- errors.push(`clog buffer: ${e.message}`);
364
+ const runWindow = {
365
+ since_ms: since,
366
+ until_ms: typeof opts.untilMs === "number" ? opts.untilMs : null,
367
+ source: since === null ? "none" : (opts.windowSource ?? "since_flag"),
368
+ };
369
+ // Failed calls, plus any the caller asked to keep by URL.
370
+ let networkFailures = null;
371
+ let networkMatches = null;
372
+ if (fetched.network) {
373
+ try {
374
+ const pass = await collectNetworkDetails(rowsOf(buffers.network, "calls"), fetchJson, opts.detailUrls ?? [], redact, opts.detailBudgetMs ?? DETAIL_BUDGET_MS);
375
+ networkFailures = pass.failures;
376
+ networkMatches = pass.matches;
377
+ }
378
+ catch (e) {
379
+ errors.push(`network details: ${e.message}`);
380
+ }
168
381
  }
169
- // Traces capture from app start (like clogs), so they are worth
170
- // bundling. An older debug build without the /api/traces route fails
171
- // this one fetch and it is recorded in errors[] like any other buffer;
172
- // the rest of the snapshot still lands.
382
+ // Facts about the device and app.
383
+ let deviceFacts = {};
384
+ let appFacts = {};
173
385
  try {
174
- traces = await fetchBuffer("traces");
175
- fetched.traces = true;
386
+ const facts = device.getDeviceFacts?.();
387
+ if (facts) {
388
+ deviceFacts = { ...facts.device };
389
+ appFacts = { ...facts.app };
390
+ }
176
391
  }
177
392
  catch (e) {
178
- errors.push(`trace buffer: ${e.message}`);
393
+ errors.push(`device facts: ${e.message}`);
179
394
  }
180
- // Logcat tail.
181
- let logTail = { text: "", truncated: false };
395
+ appFacts.android_user_id = device.getActiveUserId();
396
+ appFacts.signed_in_org_ids = [
397
+ ...new Set(rowsOf(buffers.feature_flags, "feature_flags")
398
+ .map((f) => f.org_id)
399
+ .filter((o) => typeof o === "string" && o !== "")),
400
+ ];
401
+ // Log tail. The capture file wins when it has lines; otherwise ask the device.
402
+ let logText = "";
403
+ let logTruncated = false;
404
+ let logSourceName = null;
182
405
  if (includeLogs) {
183
- try {
184
- logTail = readRecentLogTail(logTailLines);
185
- if (logTail.text) {
186
- const logFile = path.join(dir, "logcat.tail.log");
187
- fs.writeFileSync(logFile, logTail.text, { mode: FILE_MODE });
188
- files.push(logFile);
406
+ if (opts.logSource !== "device") {
407
+ try {
408
+ const tail = readRecentLogTail(logTailLines);
409
+ if (tail.text) {
410
+ logText = tail.text;
411
+ logTruncated = tail.truncated;
412
+ logSourceName = "logcat_capture";
413
+ }
414
+ }
415
+ catch (e) {
416
+ errors.push(`logcat tail: ${e.message}`);
189
417
  }
190
418
  }
191
- catch (e) {
192
- errors.push(`logcat tail: ${e.message}`);
419
+ if (!logText && device.getRecentLogs) {
420
+ try {
421
+ const r = device.getRecentLogs("", logTailLines);
422
+ logText = r.lines.join("\n");
423
+ // A read that worked and came back empty still has a source; the summary shows 0 lines from it.
424
+ logSourceName = r.source;
425
+ }
426
+ catch (e) {
427
+ errors.push(`logcat tail: ${e.message}`);
428
+ }
193
429
  }
194
430
  }
195
431
  // Screenshot. 720px default is plenty for bug reports; full-res is
@@ -222,12 +458,24 @@ export async function createSnapshot(device, fetchBuffer, opts = {}, now = Date.
222
458
  errors.push(`screenshot: ${e.message}`);
223
459
  }
224
460
  }
461
+ const notice = privacyNotice(redact);
462
+ const finalLogText = redact ? redactText(logText) : logText;
463
+ if (finalLogText) {
464
+ try {
465
+ const logFile = path.join(dir, "logcat.tail.log");
466
+ fs.writeFileSync(logFile, finalLogText, { mode: FILE_MODE });
467
+ files.push(logFile);
468
+ }
469
+ catch (e) {
470
+ errors.push(`logcat tail: ${e.message}`);
471
+ }
472
+ }
225
473
  // README. One-paragraph explainer so a receiver who opens the dir for
226
474
  // the first time knows what each file is and what privacy exposure it
227
475
  // carries.
228
476
  try {
229
477
  const readmeFile = path.join(dir, "README.txt");
230
- fs.writeFileSync(readmeFile, BUNDLE_README, { mode: FILE_MODE });
478
+ fs.writeFileSync(readmeFile, bundleReadme(redact), { mode: FILE_MODE });
231
479
  files.push(readmeFile);
232
480
  }
233
481
  catch (e) {
@@ -235,37 +483,50 @@ export async function createSnapshot(device, fetchBuffer, opts = {}, now = Date.
235
483
  }
236
484
  // Bundle JSON. Written last so counts reflect everything captured.
237
485
  const counts = {
238
- network: countItems(network),
239
- rtm: countItems(rtm),
240
- clogs: countItems(clogs),
241
- traces: countItems(traces),
242
- log_lines: logTail.text
243
- ? logTail.text.split("\n").filter(Boolean).length
244
- : 0,
245
- log_lines_truncated: logTail.truncated,
486
+ ...Object.fromEntries(BUFFERS.map((b) => [b.key, rowsOf(buffers[b.key], b.rows).length])),
487
+ log_lines: finalLogText ? finalLogText.split("\n").filter(Boolean).length : 0,
488
+ log_lines_truncated: logTruncated,
246
489
  screenshot: screenshotCaptured,
247
490
  };
248
- const bundle = {
491
+ const rawBundle = {
249
492
  // Format version of this bundle's schema — not the Radar version, which
250
493
  // is mcp_version below. Named to keep the two unmistakable in a shared file.
251
- bundle_format_version: 2,
494
+ bundle_format_version: 3,
252
495
  mcp_version: RADAR_VERSION,
253
496
  timestamp: now,
254
497
  platform: device.platform,
255
498
  active_user_id: device.getActiveUserId(),
256
499
  capture_file: getCaptureFilePath(),
257
- buffers: { network, rtm, clogs, traces },
500
+ run_window: runWindow,
501
+ device: deviceFacts,
502
+ app: appFacts,
503
+ buffers,
504
+ network_failures: networkFailures,
505
+ ...(networkMatches ? { network_matches: networkMatches } : {}),
506
+ logs: { source: logSourceName, lines: counts.log_lines, truncated: logTruncated },
258
507
  counts,
259
508
  fetched,
260
509
  errors,
261
- privacy_notice: PRIVACY_NOTICE,
510
+ redacted: redact,
511
+ privacy_notice: notice,
262
512
  };
513
+ const bundle = (redact ? redactDeep(rawBundle) : rawBundle);
514
+ let summaryPath = null;
515
+ try {
516
+ const p = path.join(dir, "summary.md");
517
+ fs.writeFileSync(p, buildSnapshotSummary(bundle, finalLogText), { mode: FILE_MODE });
518
+ summaryPath = p;
519
+ files.unshift(p);
520
+ }
521
+ catch (e) {
522
+ errors.push(`summary: ${e.message}`);
523
+ }
263
524
  const bundleFile = path.join(dir, "bundle.json");
264
525
  fs.writeFileSync(bundleFile, JSON.stringify(bundle, null, 2), {
265
526
  mode: FILE_MODE,
266
527
  });
267
528
  files.unshift(bundleFile);
268
- // Auto-zip: collapse the 4-file directory into a single shareable
529
+ // Auto-zip: collapse the directory into a single shareable
269
530
  // artifact. Users universally want to attach ONE file to Jira or drop
270
531
  // ONE file in Slack, not drag a directory. Best-effort: record the
271
532
  // failure and the user can zip manually.
@@ -274,11 +535,14 @@ export async function createSnapshot(device, fetchBuffer, opts = {}, now = Date.
274
535
  path: dir,
275
536
  files,
276
537
  zip_path: zipPath,
538
+ summary_path: summaryPath,
277
539
  timestamp: now,
278
540
  counts,
279
541
  fetched,
280
542
  errors,
281
- privacy_notice: PRIVACY_NOTICE,
543
+ privacy_notice: notice,
544
+ redacted: redact,
545
+ run_window: runWindow,
282
546
  };
283
547
  }
284
548
  // `zip` ships with macOS and most Linux distros but not every image (the
@@ -292,47 +556,50 @@ const ZIP_TOOLS = [
292
556
  function zipSnapshotDir(dir, errors) {
293
557
  const out = `${dir}.zip`;
294
558
  const failures = [];
295
- for (const tool of ZIP_TOOLS) {
296
- const result = spawnSync(tool.cmd, tool.args(out), {
297
- cwd: dir,
298
- timeout: 10000,
299
- });
300
- if (result.error?.code === "ENOENT") {
301
- continue;
302
- }
303
- if (result.status === 0) {
304
- try {
305
- fs.chmodSync(out, FILE_MODE);
559
+ // A caller --out root keeps its umask, so the archive must never appear
560
+ // there before it is 0600. mkdtemp makes a 0700 dir on the same filesystem,
561
+ // so the final rename is atomic.
562
+ let staging;
563
+ try {
564
+ staging = fs.mkdtempSync(path.join(path.dirname(dir), ".zip-"));
565
+ }
566
+ catch (e) {
567
+ errors.push(`zip failed: ${e instanceof Error ? e.message : String(e)}`);
568
+ return null;
569
+ }
570
+ const staged = path.join(staging, "snapshot.zip");
571
+ try {
572
+ for (const tool of ZIP_TOOLS) {
573
+ const result = spawnSync(tool.cmd, tool.args(staged), {
574
+ cwd: dir,
575
+ timeout: 10000,
576
+ });
577
+ if (result.error?.code === "ENOENT") {
578
+ continue;
306
579
  }
307
- catch {
308
- // Leave mode as-is; already a zip copy of owner-readable files.
580
+ if (result.status === 0) {
581
+ try {
582
+ fs.chmodSync(staged, FILE_MODE);
583
+ fs.renameSync(staged, out);
584
+ }
585
+ catch (e) {
586
+ failures.push(`${tool.cmd} wrote the archive but moving it failed: ${e instanceof Error ? e.message : String(e)}`);
587
+ break;
588
+ }
589
+ return out;
309
590
  }
310
- return out;
591
+ // A timeout or kill leaves status null, so say why instead.
592
+ const why = result.error?.message ?? result.signal ?? result.stderr?.toString().trim();
593
+ failures.push(`${tool.cmd} exited with status ${result.status ?? "null"}${why ? ": " + why : ""}`);
594
+ // A half-written archive would look like a good one to the user.
595
+ fs.rmSync(staged, { force: true });
311
596
  }
312
- // A timeout or kill leaves status null, so say why instead.
313
- const why = result.error?.message ?? result.signal ?? result.stderr?.toString().trim();
314
- failures.push(`${tool.cmd} exited with status ${result.status ?? "null"}${why ? ": " + why : ""}`);
315
- // A half-written archive would look like a good one to the user.
316
- fs.rmSync(out, { force: true });
597
+ errors.push(failures.length > 0
598
+ ? `zip failed: ${failures.join("; ")}`
599
+ : `zip not available: no ${ZIP_TOOLS.map((t) => t.cmd).join(" or ")} on PATH`);
600
+ return null;
317
601
  }
318
- errors.push(failures.length > 0
319
- ? `zip failed: ${failures.join("; ")}`
320
- : `zip not available: no ${ZIP_TOOLS.map((t) => t.cmd).join(" or ")} on PATH`);
321
- return null;
322
- }
323
- /**
324
- * Count items inside a buffer response. Handles the `{ calls: [...] }`,
325
- * `{ events: [...] }`, `{ clogs: [...] }`, `{ traces: [...] }` shapes the
326
- * radar HTTP server uses. Falls back to 0 on malformed responses.
327
- */
328
- function countItems(body) {
329
- if (!body || typeof body !== "object")
330
- return 0;
331
- const b = body;
332
- for (const key of ["calls", "events", "clogs", "traces", "items"]) {
333
- const v = b[key];
334
- if (Array.isArray(v))
335
- return v.length;
602
+ finally {
603
+ fs.rmSync(staging, { recursive: true, force: true });
336
604
  }
337
- return 0;
338
605
  }
@@ -5,4 +5,6 @@ type RadarCall = (path: string, init?: RadarRequestInit) => Promise<RadarRespons
5
5
  export declare function handleRunTestCase(args: Record<string, unknown>, call: RadarCall, dir?: string, newRunId?: () => string, now?: () => number): Promise<HandlerResult>;
6
6
  export declare function handleGetTestRun(args: Record<string, unknown>, call: RadarCall, sleep?: (ms: number) => Promise<void>, now?: () => number): Promise<HandlerResult>;
7
7
  export declare function handleStopTestRun(args: Record<string, unknown>, call: RadarCall): Promise<HandlerResult>;
8
+ export declare function handleListTestCases(dir?: string): HandlerResult;
9
+ export declare function handleSaveTestCase(args: Record<string, unknown>, call: RadarCall, dir?: string): Promise<HandlerResult>;
8
10
  export {};