@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
@@ -0,0 +1,208 @@
1
+ import fs from "fs";
2
+ import os from "os";
3
+ import path from "path";
4
+ import { randomBytes } from "crypto";
5
+ export const CASE_NAME = /^[A-Za-z0-9_-]{1,64}$/;
6
+ export const MAX_CASE_FILE_BYTES = 256 * 1024;
7
+ export const testCaseDir = () => path.join(os.homedir(), ".slack-radar", "test-cases");
8
+ function filler(label) {
9
+ return `${label} {{seq}} ${"made up replay text ".repeat(205)}`;
10
+ }
11
+ export const BUILTIN_SEED = { type: "message", channel: "{{test_channel}}", ts: "{{seq_ts}}", client_msg_id: "{{seq_uuid}}", text: filler("seed"), user: "UZRDR0000001" };
12
+ export const BUILTIN_CASES = new Map([
13
+ ["message_changed", { repeat: 100, rate_per_second: 10, events: [BUILTIN_SEED, {
14
+ type: "message", subtype: "message_changed", channel: "{{test_channel}}",
15
+ message: { ts: "{{seq_ts}}", text: filler("edit"), client_msg_id: "{{seq_uuid}}" },
16
+ }] }],
17
+ ["message_replied", { repeat: 100, rate_per_second: 10, events: [BUILTIN_SEED, {
18
+ type: "message", subtype: "message_replied", channel: "{{test_channel}}",
19
+ 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}}" }] },
20
+ }] }],
21
+ ]);
22
+ export function caseStem(name) {
23
+ return name.replace(/\.json$/, "");
24
+ }
25
+ export function loadCase(name, dir = testCaseDir()) {
26
+ const stem = caseStem(name);
27
+ if (!CASE_NAME.test(stem))
28
+ return { error: "case must match [A-Za-z0-9_-]{1,64}, optionally followed by .json" };
29
+ const filename = path.join(dir, `${stem}.json`);
30
+ let fd;
31
+ try {
32
+ fd = fs.openSync(filename, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK);
33
+ const stat = fs.fstatSync(fd);
34
+ if (!stat.isFile())
35
+ return { error: `${filename} must be a regular file` };
36
+ if (stat.size > MAX_CASE_FILE_BYTES)
37
+ return { error: `${filename} exceeds 256 KB` };
38
+ const text = fs.readFileSync(fd, "utf8");
39
+ let obj;
40
+ try {
41
+ obj = JSON.parse(text.replace(/^\uFEFF/, ""));
42
+ }
43
+ catch (error) {
44
+ const message = error.message;
45
+ const line = message.match(/line (\d+) column (\d+)/);
46
+ const position = message.match(/position (\d+)/);
47
+ const location = line ? ` at line ${line[1]} column ${line[2]}` : position ? ` at position ${position[1]}` : "";
48
+ return { error: `${filename} is not valid JSON${location}` };
49
+ }
50
+ if (typeof obj !== "object" || obj === null || Array.isArray(obj) || !Array.isArray(obj.events)) {
51
+ return { error: `${filename} needs an events array in an object` };
52
+ }
53
+ if (!("rate_per_second" in obj))
54
+ return { error: `${filename} needs a rate_per_second key (a number, or null for a burst)` };
55
+ return obj;
56
+ }
57
+ catch (error) {
58
+ if (!["ENOENT", "ENOTDIR"].includes(error.code ?? ""))
59
+ return { error: `${filename}: ${error.message}` };
60
+ const builtin = BUILTIN_CASES.get(stem);
61
+ if (builtin)
62
+ return builtin;
63
+ let stems = [];
64
+ try {
65
+ stems = fs.readdirSync(dir).filter((entry) => entry.endsWith(".json")).map(caseStem).sort();
66
+ }
67
+ catch { }
68
+ return { error: `no case named ${stem}. Built in: ${[...BUILTIN_CASES.keys()].join(", ")}. In ${dir}: ${stems.join(", ") || "none"}` };
69
+ }
70
+ finally {
71
+ if (fd !== undefined)
72
+ fs.closeSync(fd);
73
+ }
74
+ }
75
+ export function buildRunBody(caseDef, overrides, runId) {
76
+ return JSON.stringify({ run_id: runId, repeat: overrides.repeat ?? caseDef.repeat ?? 1,
77
+ rate_per_second: "rate_per_second" in overrides ? overrides.rate_per_second : caseDef.rate_per_second, events: caseDef.events });
78
+ }
79
+ export function pairLabel(event) {
80
+ return event.subtype ? `${String(event.type)}.${String(event.subtype)}` : String(event.type);
81
+ }
82
+ export function checkCaseName(name, overwrite, dir = testCaseDir()) {
83
+ const stem = caseStem(name);
84
+ if (!CASE_NAME.test(stem))
85
+ return { error: "case must match [A-Za-z0-9_-]{1,64}, optionally followed by .json", reason: "bad_name" };
86
+ if (overwrite)
87
+ return null;
88
+ // macOS disks ignore case, so Message_Changed would shadow the built-in too
89
+ if ([...BUILTIN_CASES.keys()].some((builtin) => builtin === stem.toLowerCase()))
90
+ return { error: `${stem} is built in; pick another name or pass overwrite`, reason: "name_taken" };
91
+ const target = path.join(dir, `${stem}.json`);
92
+ if (fs.existsSync(target) || isLink(target))
93
+ return { error: `${target} exists; pick another name or pass overwrite`, reason: "name_taken" };
94
+ return null;
95
+ }
96
+ // existsSync follows links, so a dangling one would look free
97
+ function isLink(file) {
98
+ try {
99
+ return fs.lstatSync(file).isSymbolicLink();
100
+ }
101
+ catch {
102
+ return false;
103
+ }
104
+ }
105
+ export function saveCase(name, caseDef, overwrite, dir = testCaseDir()) {
106
+ const problem = checkCaseName(name, overwrite, dir);
107
+ if (problem)
108
+ return problem;
109
+ const target = path.join(dir, `${caseStem(name)}.json`);
110
+ const text = `${JSON.stringify(caseDef, null, 2)}\n`;
111
+ const body = buildRunBody(caseDef, {}, "x".repeat(36));
112
+ const bytes = Math.max(Buffer.byteLength(text), Buffer.byteLength(body));
113
+ if (bytes > MAX_CASE_FILE_BYTES) {
114
+ return { error: `the case is ${Math.ceil(bytes / 1024)} KB, the device takes at most 256 KB. Lower repeat does not help, save fewer events` };
115
+ }
116
+ try {
117
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
118
+ }
119
+ catch (error) {
120
+ return { error: `${dir}: ${error.message}`, reason: "store_failed" };
121
+ }
122
+ // mkdir applies the mode only to folders it creates
123
+ if (dir === testCaseDir()) {
124
+ for (const p of [dir, path.dirname(dir)]) {
125
+ try {
126
+ fs.chmodSync(p, 0o700);
127
+ }
128
+ catch { }
129
+ }
130
+ }
131
+ if (!overwrite) {
132
+ try {
133
+ fs.writeFileSync(target, text, { mode: 0o600, flag: "wx" });
134
+ }
135
+ catch (error) {
136
+ if (error.code === "EEXIST")
137
+ return { error: `${target} exists; pick another name or pass overwrite`, reason: "name_taken" };
138
+ return { error: `${target}: ${error.message}`, reason: "store_failed" };
139
+ }
140
+ return { path: target };
141
+ }
142
+ const temp = path.join(dir, `.${caseStem(name)}.${randomBytes(6).toString("hex")}.tmp`);
143
+ try {
144
+ fs.writeFileSync(temp, text, { mode: 0o600, flag: "wx" });
145
+ fs.renameSync(temp, target);
146
+ }
147
+ catch (error) {
148
+ try {
149
+ fs.unlinkSync(temp);
150
+ }
151
+ catch { }
152
+ return { error: `${target}: ${error.message}`, reason: "store_failed" };
153
+ }
154
+ return { path: target };
155
+ }
156
+ /** Removes a saved case file. lstat counts a dangling link as present, and unlink never follows a link, so deleting one leaves its target. */
157
+ export function deleteCase(name, dir = testCaseDir()) {
158
+ const stem = caseStem(name);
159
+ if (!CASE_NAME.test(stem))
160
+ return { error: "case must match [A-Za-z0-9_-]{1,64}, optionally followed by .json" };
161
+ const target = path.join(dir, `${stem}.json`);
162
+ try {
163
+ fs.lstatSync(target);
164
+ }
165
+ catch (error) {
166
+ const code = error.code;
167
+ if (code !== "ENOENT" && code !== "ENOTDIR")
168
+ return { error: `${target}: ${error.message}` };
169
+ return { error: BUILTIN_CASES.has(stem) ? `${stem} is built in and cannot be deleted` : `no saved case named ${stem}` };
170
+ }
171
+ try {
172
+ fs.unlinkSync(target);
173
+ }
174
+ catch (error) {
175
+ return { error: `${target}: ${error.message}` };
176
+ }
177
+ return { deleted: stem };
178
+ }
179
+ function summarize(caseDef) {
180
+ const types = {};
181
+ for (const event of caseDef.events) {
182
+ const label = event && typeof event === "object" ? pairLabel(event) : "invalid";
183
+ types[label] = (types[label] ?? 0) + 1;
184
+ }
185
+ return { repeat: caseDef.repeat ?? 1, rate_per_second: caseDef.rate_per_second, events: caseDef.events.length, types };
186
+ }
187
+ export function listCases(dir = testCaseDir()) {
188
+ let stems = [];
189
+ try {
190
+ stems = fs.readdirSync(dir).filter((entry) => entry.endsWith(".json")).map(caseStem).filter((stem) => CASE_NAME.test(stem)).sort();
191
+ }
192
+ catch { }
193
+ const shadowed = new Set(stems);
194
+ const cases = [];
195
+ for (const [name, caseDef] of BUILTIN_CASES) {
196
+ if (!shadowed.has(name))
197
+ cases.push({ name, built_in: true, ...summarize(caseDef) });
198
+ }
199
+ for (const stem of stems) {
200
+ const file = path.join(dir, `${stem}.json`);
201
+ const loaded = loadCase(stem, dir);
202
+ if ("error" in loaded)
203
+ cases.push({ name: stem, path: file, error: loaded.error, ...(BUILTIN_CASES.has(stem) ? { replaces_built_in: true } : {}) });
204
+ else
205
+ cases.push({ name: stem, built_in: false, path: file, ...(BUILTIN_CASES.has(stem) ? { replaces_built_in: true } : {}), ...summarize(loaded) });
206
+ }
207
+ return { dir, cases };
208
+ }
@@ -174,6 +174,12 @@ export interface DeviceTransport {
174
174
  * to resetState() when absent.
175
175
  */
176
176
  dropForward?(): void;
177
+ /**
178
+ * Remove the adb forward this process made for itself. A no-op unless the transport forwards
179
+ * its own free port, and it only removes a forward the listing still shows as this process's.
180
+ * Best effort; never throws.
181
+ */
182
+ releaseForward?(): void;
177
183
  /**
178
184
  * Re-issue the adb forward for this process's pinned device, UNCONDITIONALLY --
179
185
  * unlike ensureForward(), a cached "already forwarded" is not trusted. The forward
@@ -233,6 +239,24 @@ export interface DeviceTransport {
233
239
  * Optional: omitted by platforms with no device log stream (webapp).
234
240
  */
235
241
  getRecentLogs?(tag: string, limit: number, grep?: string): LogResult;
242
+ /**
243
+ * Facts about the attached device and the app under test, for a snapshot header. Each field is
244
+ * read on its own, so one failed read leaves that field null and never throws.
245
+ *
246
+ * Optional: only Android (adb) has these today.
247
+ */
248
+ getDeviceFacts?(): {
249
+ device: Record<string, string | boolean | null>;
250
+ app: Record<string, string | null>;
251
+ };
252
+ /**
253
+ * The device's wall clock in epoch milliseconds (whole seconds times 1000), or null when it
254
+ * cannot be read. Event timestamps are device wall clock, so a run window must use this and
255
+ * not the host clock.
256
+ *
257
+ * Optional: only Android (adb) has this today.
258
+ */
259
+ deviceClockMs?(): number | null;
236
260
  /**
237
261
  * Returns the currently active user ID, or null if none is set. On Android
238
262
  * this is the profile (e.g. "0" for personal, "10" for work); on iOS it
@@ -366,7 +390,9 @@ export interface DeviceTransport {
366
390
  */
367
391
  selectDeviceAsync?(serial: string | null): Promise<DevicePick>;
368
392
  /**
369
- * Async variant of reassertForward for non-blocking boot/enable flows. Optional.
393
+ * Async variant of reassertForward for non-blocking boot/enable flows. Optional. Non-blocking
394
+ * for a transport on the shared port; a transport with its own port runs the sync check
395
+ * here, so its adb calls block.
370
396
  */
371
397
  reassertForwardAsync?(): Promise<boolean>;
372
398
  /**
@@ -563,7 +563,7 @@ function infoPlist(executable, port) {
563
563
  */
564
564
  function buildIcns(resourcesDir) {
565
565
  const here = path.dirname(fileURLToPath(import.meta.url));
566
- const png = path.join(here, "public", "icons", "radar-1024.png");
566
+ const png = path.join(here, "public", "icons", "icon-1024.png");
567
567
  if (!fs.existsSync(png))
568
568
  return false;
569
569
  const iconset = path.join(resourcesDir, "radar.iconset");
@@ -409,6 +409,7 @@
409
409
  .voice-legend .st::before { width:3px; height:11px; border:0; border-radius:0; background:repeating-linear-gradient(to bottom, var(--warn-2) 0 4px, transparent 4px 7px); }
410
410
  .voice-legend .e::before { width:7px; height:14px; border-radius:0; background:radial-gradient(circle at 50% 3.5px, var(--error) 3.5px, transparent 4px), linear-gradient(var(--error),var(--error)) 50% 100%/3px 10px no-repeat; }
411
411
  .voice-legend .mx::before { width:6px; height:14px; border-radius:0; background:linear-gradient(var(--text),var(--text)) 50% 0/6px 6px no-repeat, linear-gradient(var(--text),var(--text)) 50% 100%/3px 6px no-repeat; }
412
+ .voice-legend .ys::before { background:var(--warn-2); height:4px; vertical-align:2px; }
412
413
  .voice-legend .mu::before { border:1px dashed var(--purple); background:repeating-linear-gradient(to bottom, var(--purple) 0 1px, transparent 1px 3px); }
413
414
  .voice-legend .mb::before { width:7px; height:11px; border-radius:3.5px; background:var(--muted); }
414
415
  /* A scale note, not a marker kind: a swatch would imply a marker colour that does not exist. */
@@ -512,6 +513,7 @@
512
513
  .dbsec { color:var(--muted); font-size:10.5px; text-transform:uppercase; letter-spacing:.06em; margin:6px 0 6px; } .dbsec:not(:first-child){ margin-top:14px; }
513
514
  .dbitem { padding:6px 9px; border-radius:7px; cursor:pointer; font-size:12.5px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
514
515
  .dbitem:hover { background:var(--hover-soft); } .dbitem.sel { background:var(--sel-soft); color:var(--accent); } .dbitem .rows { float:right; color:var(--muted); font-size:11px; }
516
+ .dbitem.bad { color:var(--muted); } /* a saved case that failed to load; still pickable so it can be deleted */
515
517
  .dbitem.kbd { outline:2px solid var(--accent); outline-offset:-2px; } /* keyboard-focused row */
516
518
  .dbhistbtn { background:var(--surface); border:1px solid var(--border-2); border-radius:8px; color:var(--muted); padding:0 12px; font:inherit; font-size:12.5px; cursor:pointer; display:flex; align-items:center; gap:6px; }
517
519
  .dbhistbtn:hover { color:var(--text); border-color:var(--border-3); } .dbhistbtn.on { color:var(--accent); border-color:var(--accent); }
@@ -18,6 +18,7 @@ import { Filters } from "./filters.js";
18
18
  import { DbBrowser } from "./db.js";
19
19
  import { FlagsBrowser } from "./flags.js";
20
20
  import { PrefsBrowser } from "./prefs.js";
21
+ import { TestCases } from "./test-cases.js";
21
22
  import { ScreenOverlay } from "./screen.js";
22
23
  // Dismissal is per-browser on purpose: the marker file is per-machine, so without a local flag
23
24
  // the hint would come back on every load for a user who already chose to ignore it.
@@ -419,7 +420,7 @@ function StreamView({ spec }) {
419
420
  }
420
421
  // Exported for the test that pins the tab list; App is the only caller.
421
422
  export function Blank() {
422
- return html `<div class="sub"><span class="summary">Pick a dashboard above.</span><span class="tech">Live, Network, RTM, Clogs, Traces, Logs, Switchboard, Database, Preferences, Feature Flags. Or ask a terminal Claude Code session to build a custom view.</span></div>`;
423
+ return html `<div class="sub"><span class="summary">Pick a dashboard above.</span><span class="tech">Live, Network, RTM, Clogs, Traces, Logs, Switchboard, Database, Preferences, Feature Flags, Test cases. Or ask a terminal Claude Code session to build a custom view.</span></div>`;
423
424
  }
424
425
  function App() {
425
426
  const spec = useStoreValue(store, "spec", () => store.spec);
@@ -498,6 +499,16 @@ function App() {
498
499
  <${FlagsBrowser} key="flags" />
499
500
  `;
500
501
  }
502
+ else if (spec.source === "testcases") {
503
+ // Remounts on a device switch (dbResync, like Prefs) so the old device's run is dropped.
504
+ view = html `
505
+ <div class="sub">
506
+ <span class="summary">${spec.summary || "Test cases"}</span>
507
+ <span class="tech">source=testcases (replays on the device, debug builds with test_runs)</span>
508
+ </div>
509
+ <${TestCases} key=${"testcases-" + dbResync} />
510
+ `;
511
+ }
501
512
  else if (spec.source === "prefs") {
502
513
  // The Prefs browser is a self-contained, point-in-time container: it does NOT import the store
503
514
  // (no SSE engine / timers on a tab that has no live feed). key folds in dbResync (PR #94
@@ -19,15 +19,32 @@ export function friendlyFeatureFlagError(error) {
19
19
  return error;
20
20
  }
21
21
  /**
22
- * The one sentence for a flag whose latest value differs from what the app runs. A flag the app
23
- * read once keeps that value until restart, so `enabled` (latest or override) can differ from
24
- * `session_enabled`. Only two real booleans that differ earn a note: an absent or non-boolean
25
- * session_enabled is "not known", and saying nothing there is the honest answer.
22
+ * The sentence (`note`) and the short tab text (`label`) for a flag whose latest value differs from
23
+ * what the app runs. An experiment's label names the group itself, since a group has no ON/OFF to
24
+ * flip. A flag the app read once keeps that value until restart, so the latest value (`enabled` on a toggle,
25
+ * `group_name` on an experiment; fetched or override) can differ from the session value
26
+ * (`session_enabled`, `session_group_name`). Only two real values of
27
+ * the right type that differ earn a note: an absent or mistyped session value is "not known", and
28
+ * saying nothing there is the honest answer. An experiment's "" is a read that found no group, and
29
+ * its note is hedged because read-once code may still use the session group, not that it must.
26
30
  */
27
31
  export function flagRestartNote(row) {
32
+ const source = row.is_overridden === true ? "override" : "fetched";
33
+ const { group_name: group, session_group_name: sessionGroup } = row;
34
+ if (typeof group === "string" && typeof sessionGroup === "string") {
35
+ if (group === sessionGroup)
36
+ return undefined;
37
+ const used = sessionGroup || "no group";
38
+ return {
39
+ note: `read-once code may still use ${used} until restart, ${source} ${group || "no group"}`,
40
+ label: `read-once may use ${used}`,
41
+ };
42
+ }
28
43
  const { enabled, session_enabled: session } = row;
29
44
  if (typeof enabled !== "boolean" || typeof session !== "boolean" || enabled === session)
30
45
  return undefined;
31
- const source = row.is_overridden === true ? "override" : "fetched";
32
- return `app uses ${session} until restart, ${source} ${enabled}`;
46
+ return {
47
+ note: `app uses ${session} until restart, ${source} ${enabled}`,
48
+ label: `runs ${session ? "ON" : "OFF"} until restart`,
49
+ };
33
50
  }
@@ -7,9 +7,10 @@ import { html } from "./html.js";
7
7
  import { useState, useEffect, useRef, useCallback, useMemo } from "preact/hooks";
8
8
  import { store, shortUrl, shortPkg, MODES, modeServed, fmtNum, searchText, parseExcludeTerm, isGappedFieldTerm } from "./store.js";
9
9
  import { gappedFieldHint } from "./filters.js";
10
- import { STREAM_KINDS, LOG_LEVEL_ORDER, levelRank, EXCLUDE_MAX_TERMS, EXCLUDE_MAX_TERM_LENGTH, SWITCHBOARD_KINDS } from "./registry.js";
10
+ import { STREAM_KINDS, LOG_LEVEL_ORDER, levelRank, EXCLUDE_MAX_TERMS, EXCLUDE_MAX_TERM_LENGTH, SWITCHBOARD_KINDS, isStateSource } from "./registry.js";
11
11
  import { parseFilter, tokenize, isCompleteTerm, isQuote } from "./filter.js";
12
12
  import { inSessionCut, sameSessionCut } from "./voice-model.js";
13
+ import { SaveCase } from "./save-case.js";
13
14
  import { cardLabel, connectionEndedNormally, reconnectTryLabel, savedTurnLabel, switchboardClockLabel } from "./switchboard-note.js";
14
15
  const ROW_H = 24;
15
16
  const OVERSCAN = 10;
@@ -205,8 +206,8 @@ export function switchboardSummary(ev) {
205
206
  return `${text(ev.phase)}${d != null ? ` ${fmtNum(d)} ms` : ""}`;
206
207
  }
207
208
  case "player": {
208
- const g = num(ev.gap_ms), q = num(ev.bytes_queued);
209
- return `${text(ev.event)}${g != null ? ` gap ${fmtNum(g)} ms` : ""}${q != null ? ` queued ${fmtNum(q)} B` : ""}`;
209
+ const g = num(ev.gap_ms), q = num(ev.bytes_queued), d = num(ev.dropped_chunks);
210
+ return `${text(ev.event)}${g != null ? ` gap ${fmtNum(g)} ms` : ""}${q != null ? ` queued ${fmtNum(q)} B` : ""}${d != null ? ` dropped ${fmtNum(d)} mic chunk${d === 1 ? "" : "s"}` : ""}`;
210
211
  }
211
212
  // Shows size, reach, and peak loudness, not averaged rms, since averaging would wash out
212
213
  // the one loud spike a debugger is usually looking for.
@@ -806,6 +807,19 @@ export function Feed({ spec, onInspect, selectedId }) {
806
807
  highlightRef.current = null;
807
808
  onInspect && onInspect(null);
808
809
  }, [onInspect]);
810
+ // Only real device record ids can be fetched back by the server, so the selection is narrowed to those.
811
+ // Worked out when the selection or the filters change, since walking the whole cache on every
812
+ // streamed batch makes a busy feed sluggish.
813
+ const { saveIds, saveStamps } = useMemo(() => {
814
+ const rows = sel.size && source === "rtm"
815
+ ? store.viewFrames().filter((r) => r._type === "rtm" && typeof r.id === "number" && sel.has(r.id))
816
+ : [];
817
+ return {
818
+ saveIds: rows.map((r) => r.id),
819
+ // Sent with the ids so the server can tell a row from a restarted app's event with the same id.
820
+ saveStamps: rows.every((r) => typeof r.timestamp === "number") ? rows.map((r) => r.timestamp) : undefined,
821
+ };
822
+ }, [sel, source, matchKey]);
809
823
  const copySel = useCallback(() => {
810
824
  if (!sel.size)
811
825
  return;
@@ -1052,7 +1066,7 @@ export function Feed({ spec, onInspect, selectedId }) {
1052
1066
  // refusal is said next to the box and keeps the draft: a term that vanishes with no chip
1053
1067
  // reads as a bug, not as a rule. A comma is refused too: the Filters panel splits its input
1054
1068
  // on commas, so a term holding one would come back as two on the first edit there.
1055
- const isStream = source !== "db" && source !== "prefs" && source !== "flags";
1069
+ const isStream = !isStateSource(source);
1056
1070
  const [exclOpen, setExclOpen] = useState(false);
1057
1071
  const [exclDraft, setExclDraft] = useState("");
1058
1072
  // The note under the box: a refusal keeps the draft and marks the input invalid; a hint (a term
@@ -1541,6 +1555,7 @@ export function Feed({ spec, onInspect, selectedId }) {
1541
1555
  <button class="fbtn" disabled=${!total} onClick=${clearView}
1542
1556
  title="empty this dashboard's view. The device keeps its own buffers, so reconnecting or switching source backfills recent records again. To wipe the device too, ask Claude Code for clear_buffers.">Clear</button>
1543
1557
  <button class="fbtn" disabled=${!sel.size} onClick=${copySel}>Copy ${sel.size || ""}</button>
1558
+ ${source === "rtm" ? html `<${SaveCase} ids=${saveIds} timestamps=${saveStamps} />` : null}
1544
1559
  ${sel.size ? html `<button class="fbtn" onClick=${clearSel}>Clear sel</button>` : null}
1545
1560
  <span class=${"fstatus " + (paused ? "st-paused" : following ? "st-live" : "st-locked")}>${paused ? "⏸ paused" : following ? "● live" : "⏸ locked"}</span>
1546
1561
  <span class="fcount">${total} rows${sel.size ? " · " + sel.size + " selected" : ""}</span>
@@ -5,7 +5,7 @@ import { html } from "./html.js";
5
5
  import { useState, useEffect, useRef } from "preact/hooks";
6
6
  import { store, parseExcludeTerm, isGappedFieldTerm } from "./store.js";
7
7
  import { useStorePulse } from "./hooks.js";
8
- import { MATCH_FIELDS, FIELD_VALUES, FILTER_SOURCES, EXCLUDE_MAX_TERMS, EXCLUDE_MAX_TERM_LENGTH } from "./registry.js";
8
+ import { MATCH_FIELDS, FIELD_VALUES, FILTER_SOURCES, isStateSource, EXCLUDE_MAX_TERMS, EXCLUDE_MAX_TERM_LENGTH } from "./registry.js";
9
9
  // The exclude input holds the terms as one string; commas or newlines separate them (a paste
10
10
  // from a log usually brings newlines). Trimmed, empties dropped, deduplicated case-insensitively
11
11
  // (the server keeps the first spelling too, so what comes back is what was sent), capped here so
@@ -173,8 +173,8 @@ export function Filters({ spec, remembered = false }) {
173
173
  // rejection from this panel is the last thing it needs.
174
174
  if (source !== "log" && source !== "all")
175
175
  delete next.minLevel;
176
- // Same for exclusions on the browsers (db/prefs/flags): no rows with text to exclude from.
177
- if (source === "db" || source === "prefs" || source === "flags")
176
+ // Same for exclusions on the state browsers: no rows with text to exclude from.
177
+ if (isStateSource(source))
178
178
  delete next.exclude;
179
179
  const match = {};
180
180
  for (const r of rows)
@@ -195,7 +195,7 @@ export function Filters({ spec, remembered = false }) {
195
195
  // untouched input keeps the store's list verbatim: the input joins terms with commas and
196
196
  // splits on them, so rebuilding from it would cut an agent-set term like "a, b" in two on
197
197
  // every Apply, and the store's list, not the panel's copy, carries a chip pressed meanwhile.
198
- if (!(source === "db" || source === "prefs" || source === "flags") && excl !== joinExclude(spec.exclude)) {
198
+ if (!isStateSource(source) && excl !== joinExclude(spec.exclude)) {
199
199
  const terms = parseExclude(excl);
200
200
  if (terms.length)
201
201
  next.exclude = terms;
@@ -229,7 +229,7 @@ export function Filters({ spec, remembered = false }) {
229
229
  ${rows.map((r, i) => html `<${MatchRow} field=${r.field} value=${r.value} fields=${fields} onChange=${(nx) => setRows(rows.map((x, j) => (j === i ? nx : x)))} onRemove=${() => setRows(rows.filter((_, j) => j !== i))} />`)}
230
230
  <button class="fadd" onClick=${() => setRows([...rows, { field: fields[0] || "", value: "" }])}>+ add match field</button>
231
231
  ${source === "network" || source === "all" ? html `<div class="frow"><label>body contains</label><input value=${body} placeholder="substring in request/response body" onInput=${(e) => setBody(e.currentTarget.value)} /></div>` : null}
232
- ${source === "db" || source === "prefs" || source === "flags" ? null : html `<div class="frow excluderow"><label title=${"comma separated, so a term cannot contain one; a field:value term (no space after the colon) hides rows whose field equals the value, case-insensitive; up to " + EXCLUDE_MAX_TERMS + " terms of up to " + EXCLUDE_MAX_TERM_LENGTH + " characters; saved with this " + (remembered ? "tab and remembered when you come back" : "view")}>exclude</label><input class="f_excl" value=${excl} placeholder="term, term" aria-label="exclude terms, comma separated" onInput=${(e) => setExcl(e.currentTarget.value)} /></div>
232
+ ${isStateSource(source) ? null : html `<div class="frow excluderow"><label title=${"comma separated, so a term cannot contain one; a field:value term (no space after the colon) hides rows whose field equals the value, case-insensitive; up to " + EXCLUDE_MAX_TERMS + " terms of up to " + EXCLUDE_MAX_TERM_LENGTH + " characters; saved with this " + (remembered ? "tab and remembered when you come back" : "view")}>exclude</label><input class="f_excl" value=${excl} placeholder="term, term" aria-label="exclude terms, comma separated" onInput=${(e) => setExcl(e.currentTarget.value)} /></div>
233
233
  ${splitExclude(excl).terms.length > EXCLUDE_MAX_TERMS ? html `<div class="fhint fexclhint">up to ${EXCLUDE_MAX_TERMS} terms; the first ${EXCLUDE_MAX_TERMS} are kept</div>` : null}
234
234
  ${splitExclude(excl).dropped > 0 ? html `<div class="fhint fexclhint">up to ${EXCLUDE_MAX_TERM_LENGTH} characters; terms over ${EXCLUDE_MAX_TERM_LENGTH} characters are dropped</div>` : null}
235
235
  ${(() => { const gapped = splitExclude(excl).terms.find((t) => isGappedFieldTerm(t, (f) => store.fieldSeen(source, f))); return gapped === undefined ? null : html `<div class="fhint fexclhint">${gappedFieldHint(gapped)}</div>`; })()}`}
@@ -20,6 +20,8 @@
20
20
  // type "toggle" | "experiment"
21
21
  // enabled toggles only: the latest boolean (override if set, else the server value),
22
22
  // which the app may not run until restart.
23
+ // session_group_name experiments only: the group the app's first read returned (or a read returns
24
+ // now, if unread); read-once code may still use it until restart; "" is no group. Absent on older builds: not known, nothing shown.
23
25
  // session_enabled toggles only: the flag's own value the app runs this session. Absent on older
24
26
  // builds and experiments; absent or non-boolean means not known, so nothing is
25
27
  // shown.
@@ -97,10 +99,10 @@ const DIM_TITLE = "every row of this flag in this scope shows this same value";
97
99
  // Shown next to the pill when the app still runs an older value than the latest one. The visible
98
100
  // text says what the app runs; the title is the shared sentence.
99
101
  function restartMark(x) {
100
- const note = flagRestartNote(x);
101
- if (note === undefined)
102
+ const r = flagRestartNote(x);
103
+ if (r === undefined)
102
104
  return null;
103
- return html `<span class="flagrestart" title=${note}>runs ${x.session_enabled ? "ON" : "OFF"} until restart</span>`;
105
+ return html `<span class="flagrestart" title=${r.note}>${r.label}</span>`;
104
106
  }
105
107
  // Render a flag value. Booleans (toggles) show ON/OFF; a variant group-name string shows as a
106
108
  // text pill ("" / "control" read as the off/baseline arm). `dim` mutes a value that every row of
@@ -71,6 +71,7 @@ export const SOURCES = {
71
71
  prefs: { label: "Preferences", kind: "state", origin: "device" },
72
72
  // Feature flags: a point-in-time snapshot like db/prefs (own container, no SSE feed).
73
73
  flags: { label: "Feature Flags", kind: "state", origin: "device" },
74
+ testcases: { label: "Test cases", kind: "state", origin: "device" },
74
75
  };
75
76
  // The set of streaming source kinds the store admits off the SSE stream (derived from SOURCES,
76
77
  // excluding the non-stream db + the unified "all" alias).
@@ -107,7 +108,7 @@ export const DETAILABLE_KINDS = Object.entries(SOURCES)
107
108
  export const EAGER_CAPTURE_KINDS = Object.entries(SOURCES)
108
109
  .filter(([, v]) => v.hasDetailEndpoint && v.eagerCapture)
109
110
  .map(([k]) => k);
110
- // A "state" source is a point-in-time browser (db, prefs, flags), NOT a live stream. The store
111
+ // A "state" source is a point-in-time browser (db, prefs, flags, testcases), NOT a live stream. The store
111
112
  // fully quiets its SSE engine + tick for these (they run their own fetch/stream), so this is the
112
113
  // single check the store branches on — derived from the registry so a new state source cannot
113
114
  // drift out of sync with the store's quieting logic.
@@ -122,7 +123,7 @@ export function hasDetailEndpoint(kind) {
122
123
  // see widgets.ts). A new widget = one key here + one component.
123
124
  export const WIDGETS = ["counter", "rate", "sparkline", "graph"];
124
125
  // Source order for the modebar / global tab-switch (matches the MODES preset order).
125
- export const SOURCE_ORDER = ["all", "network", "rtm", "clog", "trace", "log", "switchboard", "db", "prefs", "flags"];
126
+ export const SOURCE_ORDER = ["all", "network", "rtm", "clog", "trace", "log", "switchboard", "db", "prefs", "flags", "testcases"];
126
127
  // The source options the Filters panel offers: every streaming source (state sources like db/prefs
127
128
  // are their own containers, not feed filters). Derived from SOURCES so adding a streaming source
128
129
  // surfaces it in Filters with no edit there. Ordered by SOURCE_ORDER (the modebar order) for a stable, familiar list.
@@ -0,0 +1,92 @@
1
+ // "Save as test case" on the RTM feed toolbar: names the case, posts the selected event ids to the
2
+ // dashboard server and shows the answer as one short status note.
3
+ import { html } from "./html.js";
4
+ import { useState, useEffect, useRef } from "preact/hooks";
5
+ const counts = (label, v) => {
6
+ if (!v || typeof v !== "object")
7
+ return "";
8
+ const parts = Object.entries(v).map(([k, n]) => `${k} ${n}`);
9
+ return parts.length ? `${label} ${parts.join(", ")}` : "";
10
+ };
11
+ /** One line for a save answer. Shows the file stem only, so the home path stays out of the page. */
12
+ export function saveCaseNote(answer) {
13
+ const missing = Array.isArray(answer.missing) && answer.missing.length ? `missing ids ${answer.missing.join(", ")}` : "";
14
+ const note = typeof answer.note === "string" ? answer.note : "";
15
+ if (typeof answer.saved !== "string") {
16
+ const error = typeof answer.error === "string" ? answer.error : "request failed";
17
+ return [error, counts("kept", answer.kept), counts("dropped", answer.dropped), missing].filter(Boolean).join("; ");
18
+ }
19
+ const stem = answer.saved.split(/[\\/]/).pop().replace(/\.json$/, "");
20
+ return [
21
+ `saved ${stem}: ${answer.events} ${answer.events === 1 ? "event" : "events"}`,
22
+ counts("kept", answer.kept),
23
+ counts("dropped", answer.dropped),
24
+ missing,
25
+ answer.seeded ? "added a seed message" : "",
26
+ counts("left out block fields", answer.removed_block_fields),
27
+ note,
28
+ ].filter(Boolean).join("; ");
29
+ }
30
+ const MAX_IDS = 200;
31
+ export function SaveCase({ ids, timestamps }) {
32
+ const tooMany = ids.length > MAX_IDS;
33
+ const tooManyReason = `select at most ${MAX_IDS} rows (${ids.length} selected)`;
34
+ const [open, setOpen] = useState(false);
35
+ const [name, setName] = useState("");
36
+ const [busy, setBusy] = useState(false);
37
+ const [note, setNote] = useState(null);
38
+ const inputRef = useRef(null);
39
+ useEffect(() => {
40
+ const el = inputRef.current;
41
+ if (open && el && typeof el.focus === "function")
42
+ el.focus();
43
+ }, [open]);
44
+ const save = async () => {
45
+ if (busy || !name.trim())
46
+ return;
47
+ setBusy(true);
48
+ try {
49
+ const res = await fetch("/test-cases", {
50
+ method: "POST",
51
+ headers: { "X-Radar-Dashboard": "1", "Content-Type": "application/json" },
52
+ body: JSON.stringify({ name: name.trim(), ids, ...(timestamps ? { timestamps } : {}) }),
53
+ });
54
+ const answer = await res.json();
55
+ if (!answer || typeof answer !== "object")
56
+ throw new Error("not an object");
57
+ const ok = typeof answer.saved === "string";
58
+ setNote({ text: saveCaseNote(answer), ok });
59
+ if (ok) {
60
+ setOpen(false);
61
+ setName("");
62
+ }
63
+ }
64
+ catch {
65
+ setNote({ text: "request failed", ok: false });
66
+ }
67
+ finally {
68
+ setBusy(false);
69
+ }
70
+ };
71
+ return html `<span class="fexcludewrap">
72
+ <button class="fbtn" type="button" disabled=${!ids.length || tooMany} title=${tooMany ? tooManyReason : "save the selected events as a test case you can replay with run_test_case"}
73
+ aria-label=${tooMany ? "Save as test case, " + tooManyReason : undefined}
74
+ onClick=${() => { setNote(null); setOpen(true); }}>Save as test case</button>
75
+ ${open ? html `<input class="fexclude-input" ref=${inputRef} placeholder="name: letters, digits, _ or -, then Enter" autocomplete="off" value=${name}
76
+ aria-label="test case name" disabled=${busy}
77
+ onInput=${(e) => { setName(e.currentTarget.value); setNote(null); }}
78
+ onKeyDown=${(e) => {
79
+ if (e.key === "Enter") {
80
+ e.preventDefault();
81
+ void save();
82
+ }
83
+ else if (e.key === "Escape") {
84
+ e.preventDefault();
85
+ setOpen(false);
86
+ setName("");
87
+ setNote(null);
88
+ }
89
+ }} />` : null}
90
+ ${note ? html `<span class=${"fexclude-note" + (note.ok ? " fexclude-note-plain" : "")} role="status">${note.text}</span>` : null}
91
+ </span>`;
92
+ }
@@ -131,6 +131,7 @@ export const MODES = [
131
131
  { key: "db", label: "Database", spec: { title: "Device DB", summary: "Browse the on-device SQLite databases (read-only snapshot).", source: "db" } },
132
132
  { key: "prefs", label: "Preferences", spec: { title: "Device Preferences", summary: "Browse the on-device SharedPreferences (including feature-flag overrides), read-only.", source: "prefs" } },
133
133
  { key: "flags", label: "Feature Flags", spec: { title: "Feature Flags", summary: "Every feature flag and experiment the Slack app knows about, with its current effective value (ON/OFF for toggles, group name for experiments), its scope, and whether it is locally overridden. Live-updates as flags and experiments change on the device. Filter by name.", source: "flags" } },
134
+ { key: "testcases", label: "Test cases", spec: { title: "Test cases", summary: "Replay built-in and saved RTM test cases on the device and read the timings.", source: "testcases" } },
134
135
  ];
135
136
  const DEFAULT_LOG_PACKAGE = MODES[0].spec.match?.package ?? "";
136
137
  // Dashboard mode key -> the ping `sources` name that must be present for the tab to work. Only
@@ -143,6 +144,7 @@ export const MODE_SOURCE = {
143
144
  clog: "clogs",
144
145
  trace: "traces",
145
146
  flags: "feature_flags",
147
+ testcases: "test_runs",
146
148
  // The voice transport plugin declares itself under its own name (kind stream), so a build
147
149
  // without it hides the tab instead of showing an empty feed that can never fill.
148
150
  switchboard: "switchboard",
@@ -1334,7 +1336,7 @@ export class Store {
1334
1336
  this._capQueue.length = 0;
1335
1337
  this.graph = this.buildGraph();
1336
1338
  this.emit("spec", this.spec);
1337
- // State browsers (db/prefs/flags) + blank: fully quiet the streaming engine so it does not
1339
+ // State browsers + blank: fully quiet the streaming engine so it does not
1338
1340
  // compete with point-in-time operations (each state tab runs its own fetch/stream). Close the
1339
1341
  // SSE stream AND stop the per-second tick. The 100k cache is left intact.
1340
1342
  if (this.spec.blank || isStateSource(this.spec.source)) {
@@ -3005,7 +3007,7 @@ export function switchboardFields(ev) {
3005
3007
  case "state": return [kind, ev.state_kind, ev.from, ev.to, ev.cause];
3006
3008
  case "frame": return [kind, ev.direction, ev.frame_type, num(ev.bytes)];
3007
3009
  case "phase": return [kind, ev.phase, num(ev.duration_ms)];
3008
- case "player": return [kind, ev.event, num(ev.gap_ms), num(ev.bytes_queued)];
3010
+ case "player": return [kind, ev.event, num(ev.gap_ms), num(ev.bytes_queued), num(ev.dropped_chunks)];
3009
3011
  case "levels": return [kind, num(ev.sample_count)];
3010
3012
  // The raw clock token, not the row's words, the same way a frame keeps "unknown".
3011
3013
  case "turn": return [kind, ev.clock, num(ev.response_ms)];