@slack/radar-mcp 1.20.0 → 1.22.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 (91) hide show
  1. package/README.md +75 -17
  2. package/dist/mcp/api-paths.d.ts +11 -0
  3. package/dist/mcp/api-paths.js +56 -20
  4. package/dist/mcp/dashboard-identity.d.ts +6 -0
  5. package/dist/mcp/dashboard-identity.js +11 -0
  6. package/dist/mcp/index.js +138 -36
  7. package/dist/mcp/logs-result.d.ts +1 -0
  8. package/dist/mcp/logs-result.js +1 -0
  9. package/dist/mcp/network-detail.d.ts +5 -0
  10. package/dist/mcp/network-detail.js +86 -0
  11. package/dist/mcp/radar-export-get.d.ts +30 -0
  12. package/dist/mcp/radar-export-get.js +49 -0
  13. package/dist/mcp/radar-response.d.ts +11 -1
  14. package/dist/mcp/radar-response.js +23 -3
  15. package/dist/mcp/session-backfill.d.ts +9 -3
  16. package/dist/mcp/session-backfill.js +76 -17
  17. package/dist/mcp/session-detail.js +54 -2
  18. package/dist/mcp/session-enable.d.ts +1 -0
  19. package/dist/mcp/session-enable.js +146 -15
  20. package/dist/mcp/session-query.js +53 -11
  21. package/dist/mcp/snapshot.js +42 -26
  22. package/dist/mcp/sources-gate.js +5 -0
  23. package/dist/mcp/stale-dashboard.d.ts +23 -0
  24. package/dist/mcp/stale-dashboard.js +122 -0
  25. package/dist/mcp/switchboard-spool.d.ts +12 -0
  26. package/dist/mcp/switchboard-spool.js +107 -0
  27. package/dist/mcp/switchboard-tools.d.ts +18 -0
  28. package/dist/mcp/switchboard-tools.js +178 -0
  29. package/dist/mcp/tools.d.ts +4 -1
  30. package/dist/mcp/tools.js +114 -23
  31. package/dist/mcp/web-child-env.d.ts +4 -1
  32. package/dist/mcp/web-child-env.js +4 -1
  33. package/dist/shared/android.d.ts +43 -0
  34. package/dist/shared/android.js +227 -19
  35. package/dist/shared/constants.d.ts +19 -4
  36. package/dist/shared/constants.js +19 -4
  37. package/dist/shared/event-spool.js +3 -2
  38. package/dist/shared/feature-flags.d.ts +1 -0
  39. package/dist/shared/feature-flags.js +1 -0
  40. package/dist/shared/form-body.d.ts +18 -0
  41. package/dist/shared/form-body.js +251 -0
  42. package/dist/shared/ios-logs.d.ts +10 -0
  43. package/dist/shared/ios-logs.js +91 -0
  44. package/dist/shared/ios.d.ts +25 -2
  45. package/dist/shared/ios.js +157 -3
  46. package/dist/{web → shared}/log-session.d.ts +45 -31
  47. package/dist/shared/log-session.js +300 -0
  48. package/dist/shared/radar-request-raw.d.ts +7 -0
  49. package/dist/shared/radar-request-raw.js +89 -0
  50. package/dist/shared/radar-token.d.ts +25 -0
  51. package/dist/shared/radar-token.js +164 -0
  52. package/dist/shared/stream.d.ts +4 -1
  53. package/dist/shared/stream.js +107 -15
  54. package/dist/shared/switchboard-host-store.d.ts +21 -0
  55. package/dist/shared/switchboard-host-store.js +166 -0
  56. package/dist/shared/switchboard-note.d.ts +15 -0
  57. package/dist/shared/switchboard-note.js +92 -0
  58. package/dist/shared/switchboard-report-file.d.ts +5 -0
  59. package/dist/shared/switchboard-report-file.js +26 -0
  60. package/dist/shared/switchboard-report.d.ts +20 -0
  61. package/dist/shared/switchboard-report.js +406 -0
  62. package/dist/shared/switchboard.d.ts +118 -0
  63. package/dist/shared/switchboard.js +487 -0
  64. package/dist/shared/transport.d.ts +43 -3
  65. package/dist/shared/version.d.ts +2 -0
  66. package/dist/shared/version.js +18 -0
  67. package/dist/shared/wire.d.ts +46 -1
  68. package/dist/web/install-app.d.ts +57 -8
  69. package/dist/web/install-app.js +270 -60
  70. package/dist/web/macapp/RadarApp.swift +340 -22
  71. package/dist/web/public/index.html +216 -12
  72. package/dist/web/public/next/app.js +43 -22
  73. package/dist/web/public/next/db.js +4 -1
  74. package/dist/web/public/next/feed.js +604 -59
  75. package/dist/web/public/next/filters.js +158 -40
  76. package/dist/web/public/next/flags.js +3 -0
  77. package/dist/web/public/next/form-body.js +252 -0
  78. package/dist/web/public/next/inspector.js +171 -14
  79. package/dist/web/public/next/prefs.js +5 -2
  80. package/dist/web/public/next/registry.js +35 -3
  81. package/dist/web/public/next/store.js +947 -69
  82. package/dist/web/public/next/switchboard-note.js +93 -0
  83. package/dist/web/public/next/toast.js +9 -5
  84. package/dist/web/public/next/voice-model.js +712 -0
  85. package/dist/web/public/next/voice.js +552 -0
  86. package/dist/web/server.d.ts +20 -9
  87. package/dist/web/server.js +834 -174
  88. package/dist/web/spec.d.ts +11 -6
  89. package/dist/web/spec.js +62 -6
  90. package/package.json +4 -4
  91. package/dist/web/log-session.js +0 -166
@@ -1,4 +1,7 @@
1
- import { STREAM_KINDS, DEVICE_STREAM_KINDS, EAGER_CAPTURE_KINDS, isStateSource, levelRank, FIELD_VALUES } from "./registry.js";
1
+ import { STREAM_KINDS, DEVICE_STREAM_KINDS, EAGER_CAPTURE_KINDS, isStateSource, levelRank, FIELD_VALUES, EXCLUDE_MAX_TERMS, EXCLUDE_MAX_TERM_LENGTH, SWITCHBOARD_KINDS, CACHE_TTL_MS, normalizeStreamType } from "./registry.js";
2
+ import { byRecordTime, cutFromVotes, inSessionCut, outranks, runRows, sameSessionCut, sessionVote } from "./voice-model.js";
3
+ import { savedTurnLabel } from "./switchboard-note.js";
4
+ export const UNAUTHORIZED_HEAD = "device refused this session (HTTP 401)";
2
5
  // Logcat-scale retention. At the live firehose (~400+ events/sec on the unified Live tab) a
3
6
  // small ring recycles in seconds, so a rare signal (a once-per-5s heartbeat) gets evicted
4
7
  // before you can filter for it. Android Studio / Flipper keep the whole session and filter
@@ -6,10 +9,9 @@ import { STREAM_KINDS, DEVICE_STREAM_KINDS, EAGER_CAPTURE_KINDS, isStateSource,
6
9
  // 100k events ~ a few minutes of the full firehose, or hours of any single low-rate tag. The
7
10
  // cost is heap (bounded, ~tens of MB) + a full-buffer filter pass, which is why the feed only
8
11
  // does that pass on a user action and prepends incrementally while tailing (see feed.ts). TTL
9
- // is the secondary bound for a quiet session. These are named constants, not inline magic, so
10
- // the retention rationale stays attached to the numbers.
12
+ // (CACHE_TTL_MS, in registry.ts so voice-model.ts can read it without the store) is the
13
+ // secondary bound for a quiet session.
11
14
  const CACHE_CAP = 100000;
12
- const CACHE_TTL_MS = 60 * 60 * 1000;
13
15
  const EAGER_CAPTURE = new Set(EAGER_CAPTURE_KINDS); // sources whose detail is pre-fetched per frame
14
16
  const DETAIL_CACHE_CAP = 1500; // bounded full-detail cache (eager-captured + click-fetched)
15
17
  const CAPTURE_CONCURRENCY = 3; // max parallel background /detail fetches
@@ -32,25 +34,105 @@ function readAutoRearmSuppressed() {
32
34
  return false;
33
35
  }
34
36
  }
37
+ // Per-tab view options (the exclude chips), keyed by preset key and persisted like the
38
+ // auto-rearm choice. A preset tab click pushes the pristine
39
+ // MODES spec, which used to throw away the chips set on it; this is what specForTab reads to
40
+ // put them back. Custom specs never land here: they have no key to come back to.
41
+ const VIEW_MEMORY_KEY = "radar-view-memory";
42
+ // The server's caps on `exclude` are applied again on read, so a stored list the server would
43
+ // refuse never rides onto a tab click and leaves the tab unclickable.
44
+ // A stored exclude list, cut to what the server accepts: strings only, trimmed, empties and
45
+ // over-long terms dropped, deduplicated case-insensitively (first spelling kept), at most 20.
46
+ // Undefined when nothing valid remains.
47
+ function clampExclude(list) {
48
+ if (!Array.isArray(list))
49
+ return undefined;
50
+ const seen = new Set();
51
+ const out = [];
52
+ for (const t of list) {
53
+ if (typeof t !== "string")
54
+ continue;
55
+ const term = t.trim();
56
+ if (!term || term.length > EXCLUDE_MAX_TERM_LENGTH || /[,\n]/.test(term) || seen.has(term.toLowerCase()))
57
+ continue;
58
+ seen.add(term.toLowerCase());
59
+ out.push(term);
60
+ if (out.length === EXCLUDE_MAX_TERMS)
61
+ break;
62
+ }
63
+ return out.length ? out : undefined;
64
+ }
65
+ // The stored map, or null when there is no storage to read (private mode, tests without a
66
+ // localStorage): the caller keeps its own copy then, instead of taking "unreadable" for "empty".
67
+ function readStoredViewMemory() {
68
+ try {
69
+ const raw = localStorage.getItem(VIEW_MEMORY_KEY);
70
+ if (!raw)
71
+ return {};
72
+ const parsed = JSON.parse(raw);
73
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
74
+ return {};
75
+ // Only the one field, only in its shape, only within the server's caps: a stale or
76
+ // hand-edited value must not smuggle an arbitrary field, or a refused list, onto a pushed spec.
77
+ const out = {};
78
+ for (const [k, v] of Object.entries(parsed)) {
79
+ if (!v || typeof v !== "object")
80
+ continue;
81
+ const e = v;
82
+ const entry = {};
83
+ const exclude = clampExclude(e.exclude);
84
+ if (exclude)
85
+ entry.exclude = exclude;
86
+ if (Object.keys(entry).length)
87
+ out[k] = entry;
88
+ }
89
+ return out;
90
+ }
91
+ catch {
92
+ return null;
93
+ }
94
+ }
95
+ function readViewMemory() {
96
+ return readStoredViewMemory() ?? {};
97
+ }
98
+ function writeViewMemory(mem) {
99
+ try {
100
+ if (Object.keys(mem).length)
101
+ localStorage.setItem(VIEW_MEMORY_KEY, JSON.stringify(mem));
102
+ else
103
+ localStorage.removeItem(VIEW_MEMORY_KEY);
104
+ }
105
+ catch {
106
+ /* private mode: the memory lasts for this tab only */
107
+ }
108
+ }
35
109
  const POLL_PROFILE_MS = 5000;
36
110
  const GRAPH_N = 60;
37
111
  const PERSEC_N = 30;
38
- const SUGGEST_FIELDS = ["event_type", "event_name", "tag", "status_code", "channel", "url", "package", "trace_name", "span_name"];
112
+ const SUGGEST_FIELDS = ["event_type", "event_name", "tag", "status_code", "channel", "url", "package", "trace_name", "span_name", "kind", "frame_type", "state_kind", "phase", "event", "clock", "outcome"];
39
113
  const PACKAGE_CAP = 1000; // package values learned off the stream; bounded (was Infinity in the PoC, B4)
40
114
  // ---- pre-built dashboards: one tab each. Presets carry only generic placeholders; real
41
115
  // endpoints/channels/event-names are learned LIVE from the device stream. The one baked value
42
116
  // is com.Slack.internal.debug (the debug build's package), which is already public. ----
43
117
  export const MODES = [
44
- { key: "all", label: "Live", spec: { title: "Live", summary: "Live: network, RTM, analytics clogs, traces, and Slack-app logcat in one timeline. (Logs filtered to the Slack app; clear the package chip for all apps.)", source: "all", viz: ["rate", "sparkline", "feed", "inspector"], match: { package: "com.Slack.internal.debug" } } },
118
+ { key: "all", label: "Live", spec: { title: "Live", summary: "Live: network, RTM, analytics clogs, traces, Slack-app logs and Switchboard voice records in one timeline. The rate and sparkline count every source together, so a voice session raises them the way RTM traffic does. (Logs filtered to the Slack app; clear the package chip for all apps.)", source: "all", viz: ["rate", "sparkline", "feed", "inspector"], match: { package: "com.Slack.internal.debug" } } },
45
119
  { key: "network", label: "Network", spec: { title: "Network", summary: "Network calls per second vs average response time, every call listed, slow ones flagged.", source: "network", viz: ["rate", "graph", "feed", "inspector"], series: [{ metric: "ratePerSec", label: "calls/s", unit: "/s" }, { metric: "avg", field: "duration_ms", label: "avg ms", unit: "ms" }], highlight: { field: "duration_ms", op: ">", value: 800, label: "slow (>800ms)" }, rateWindowSec: 10 } },
46
120
  { key: "rtm", label: "RTM", spec: { title: "RTM", summary: "Real-time websocket events as they happen.", source: "rtm", viz: ["rate", "feed", "inspector"] } },
47
121
  { key: "clog", label: "Clogs", spec: { title: "Clogs", summary: "Analytics clog events, click any to see its full payload.", source: "clog", viz: ["rate", "feed", "inspector"] } },
48
122
  { key: "trace", label: "Traces", spec: { title: "Traces", summary: "Performance trace spans, click to see timing details and tags.", source: "trace", viz: ["rate", "graph", "feed", "inspector"], series: [{ metric: "ratePerSec", label: "spans/s", unit: "/s" }, { metric: "avg", field: "duration_ms", label: "avg ms", unit: "ms" }] } },
49
- { key: "log", label: "Logs", spec: { title: "Device Logs", summary: "Live Slack app logcat, color-coded by level. Scroll the full session buffer, select a range, copy raw lines.", source: "log", viz: ["feed", "inspector"], match: { package: "com.Slack.internal.debug" } } },
123
+ { key: "log", label: "Logs", spec: { title: "Device Logs", summary: "Live Slack app logs, color-coded by level. Scroll the full session buffer, select a range, copy raw lines.", source: "log", viz: ["feed", "inspector"], match: { package: "com.Slack.internal.debug" } } },
124
+ // The voice transport's own records (not logcat): session begin/end, connection, mic and speaking
125
+ // state changes, every websocket frame with its direction and size, phase timings, player re-arms and
126
+ // stalls. Events only for now; a waveform view comes later. No level here: the records
127
+ // carry no logcat priority, so like network/rtm/clog/trace the level selector does not apply and
128
+ // passesLevel lets every row through (the same carve-out the Live timeline gives those kinds).
129
+ // Noise is hidden with the filter box or an exclude chip, on the kind or the frame type.
130
+ { key: "switchboard", label: "Switchboard", spec: { title: "Switchboard", summary: "Slackbot voice transport events from the device: sessions, state changes, websocket frames in and out, phase timings and player events, as they happen.", source: "switchboard", viz: ["rate", "voice", "feed", "inspector"] } },
50
131
  { key: "db", label: "Database", spec: { title: "Device DB", summary: "Browse the on-device SQLite databases (read-only snapshot).", source: "db" } },
51
132
  { key: "prefs", label: "Preferences", spec: { title: "Device Preferences", summary: "Browse the on-device SharedPreferences (including feature-flag overrides), read-only.", source: "prefs" } },
52
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" } },
53
134
  ];
135
+ const DEFAULT_LOG_PACKAGE = MODES[0].spec.match?.package ?? "";
54
136
  // Dashboard mode key -> the ping `sources` name that must be present for the tab to work. Only
55
137
  // sources the device ships as plugins are gateable; the rest (network/db/prefs/...) always show,
56
138
  // and each joins this map when its device-side migration lands. Note the mode key is singular
@@ -61,6 +143,9 @@ export const MODE_SOURCE = {
61
143
  clog: "clogs",
62
144
  trace: "traces",
63
145
  flags: "feature_flags",
146
+ // The voice transport plugin declares itself under its own name (kind stream), so a build
147
+ // without it hides the tab instead of showing an empty feed that can never fill.
148
+ switchboard: "switchboard",
64
149
  };
65
150
  // True when the device serves this mode's source. Old builds declare nothing
66
151
  // (sources null) and keep every tab.
@@ -80,7 +165,7 @@ export function modeServed(key, sources) {
80
165
  // - object keys are sorted so key ORDER never matters.
81
166
  // The presets stay mutually distinct under this reduction (verified by test), so dropping the
82
167
  // copy never collapses two different dashboards into one.
83
- function canonicalSpecKey(spec) {
168
+ function canonicalSpecKey(spec, logPackage = DEFAULT_LOG_PACKAGE) {
84
169
  const norm = (v) => {
85
170
  if (Array.isArray(v))
86
171
  return v.map(norm);
@@ -96,10 +181,21 @@ function canonicalSpecKey(spec) {
96
181
  const cleaned = { ...spec };
97
182
  delete cleaned.title;
98
183
  delete cleaned.summary;
184
+ // The package advertised by /health describes the same built-in Slack-app filter.
185
+ // Normalize only for preset recognition; the authored spec itself is never rewritten.
186
+ if ((cleaned.source === "log" || cleaned.source === "all") &&
187
+ logPackage && cleaned.match?.package === logPackage) {
188
+ cleaned.match = { ...cleaned.match, package: DEFAULT_LOG_PACKAGE };
189
+ }
99
190
  // A level floor is a way of looking at the same tab, not a different tab: the Logs button
100
191
  // stays lit at "level ≥ WARN". `match.package` is deliberately still part of the key, so the app
101
192
  // selector next to it does move you off the preset; the two controls are not meant to agree.
102
193
  delete cleaned.minLevel;
194
+ // Exclusions are a view option too, the same kind of thing as the level: hiding a noisy line
195
+ // on Logs is still looking at Logs. So the tab stays lit with exclude chips on, and removing a
196
+ // chip does not flip it to Custom. (`match` stays in the key: it is what a preset IS, not how
197
+ // it is being looked at.)
198
+ delete cleaned.exclude;
103
199
  if (Array.isArray(cleaned.viz))
104
200
  cleaned.viz = cleaned.viz.filter((x) => x !== "counter");
105
201
  return JSON.stringify(norm(cleaned));
@@ -109,21 +205,40 @@ function canonicalSpecKey(spec) {
109
205
  // on a log-carrying tab), the way the text filter survives every tab switch. It never overrides
110
206
  // a level the target already carries, so an agent-authored view keeps its own; the Custom button
111
207
  // does not come through here at all.
112
- export function specForTab(next, current, remembered = "") {
208
+ //
209
+ // Then the tab's own memory (`memory`, the store's viewMemory unless a caller says otherwise): a
210
+ // preset with a remembered exclude list gets it back. That never overrides a field the target
211
+ // already carries, so an agent-authored spec that resolves to a preset still pushes exactly what
212
+ // the agent wrote.
213
+ export function specForTab(next, current, remembered = "", memory = store.viewMemory, logPackage = DEFAULT_LOG_PACKAGE) {
113
214
  const logish = (s) => s === "log" || s === "all";
114
- if (!logish(next.source) || next.minLevel !== undefined)
115
- return next;
116
- const min = current && logish(current.source)
117
- ? (typeof current.minLevel === "string" ? current.minLevel : "")
118
- : remembered;
119
- return min ? { ...next, minLevel: min } : next;
215
+ let out = next;
216
+ if (logish(next.source) && next.minLevel === undefined) {
217
+ const min = current && logish(current.source)
218
+ ? (typeof current.minLevel === "string" ? current.minLevel : "")
219
+ : remembered;
220
+ if (min)
221
+ out = { ...next, minLevel: min };
222
+ }
223
+ const key = specMatchesMode(next, logPackage);
224
+ const mem = key ? memory[key] : undefined;
225
+ if (!mem)
226
+ return out;
227
+ if (mem.exclude && next.exclude === undefined)
228
+ out = { ...out, exclude: [...mem.exclude] };
229
+ return out;
120
230
  }
121
- export function specMatchesMode(spec) {
231
+ export function specMatchesMode(spec, logPackage = DEFAULT_LOG_PACKAGE) {
122
232
  if (!spec || spec.blank)
123
233
  return null;
124
- const key = canonicalSpecKey(spec);
234
+ const key = canonicalSpecKey(spec, logPackage);
125
235
  return MODES.find((m) => canonicalSpecKey(m.spec) === key)?.key ?? null;
126
236
  }
237
+ // Whether a record of the run's session id belongs to the run itself rather than an older process's
238
+ // run under the same id. With no begin on record there is nothing to tell them apart by.
239
+ function inSwitchboardRun(ev, run) {
240
+ return run.beganAt === null || (typeof ev.timestamp === "number" && ev.timestamp >= run.beganAt);
241
+ }
127
242
  /**
128
243
  * This page's presence id, taken from the URL when whoever opened the page supplied one.
129
244
  *
@@ -144,7 +259,9 @@ export function pageTabId(search) {
144
259
  return supplied;
145
260
  return typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : String(Math.random()).slice(2);
146
261
  }
147
- class Store {
262
+ // Exported for the one test that needs a second instance (a simulated reload reading the same
263
+ // storage); the page uses the singleton `store` below.
264
+ export class Store {
148
265
  spec = { blank: true, viz: [] };
149
266
  conn = { state: "waiting", msg: "connecting…" };
150
267
  // Last self-heal check's outcome, fetched once at boot (see fetchSelfHeal). null until that
@@ -224,6 +341,10 @@ class Store {
224
341
  // "device offline, retrying…" overwrites the msg within one 2s tick and is factually wrong
225
342
  // for this outage mode (the device is fine; the session inside the app ended).
226
343
  sessionEnded = false;
344
+ // A device 401, held until something later outranks it: the device accepts us again (a connected
345
+ // frame, a healthy reply, a press or pick that arms), a reasoned frame names another cause, two
346
+ // health reads in a row fail or come back without a 401, or the bound device changes.
347
+ _refusalMsg = null;
227
348
  // True while ANY /enable flight is in progress — manual press or auto-re-arm — set by
228
349
  // reconnect() itself so one latch covers both initiators. Emitted as "enabling"; the
229
350
  // header's button disables and relabels off it.
@@ -277,9 +398,13 @@ class Store {
277
398
  // honour it too — otherwise the tab that pressed stop renders "off" while the tab next to it
278
399
  // keeps arming the device, and the control's whole purpose (make the arming stop) fails.
279
400
  // `storage` fires only in the OTHER tabs, which is exactly the gap the writer cannot cover.
280
- watchSuppressionAcrossTabs() {
401
+ watchStorageAcrossTabs() {
281
402
  try {
282
403
  window.addEventListener("storage", (e) => {
404
+ // The view memory is per browser origin too: a chip set in the window next door is
405
+ // this window's memory as well, and its next tab click must read it.
406
+ if (e.key === null || e.key === VIEW_MEMORY_KEY)
407
+ this.viewMemory = readStoredViewMemory() ?? this.viewMemory;
283
408
  if (e.key !== null && e.key !== AUTO_REARM_OFF_KEY)
284
409
  return;
285
410
  const next = readAutoRearmSuppressed();
@@ -398,6 +523,23 @@ class Store {
398
523
  return null;
399
524
  return this._enableErrorEpoch === this._outageEpoch ? this.enableError : null;
400
525
  }
526
+ get refusal() {
527
+ return this._refusalMsg;
528
+ }
529
+ setRefusal(msg) {
530
+ if (this._refusalMsg === msg)
531
+ return;
532
+ // Earlier answers do not belong to this refusal. A press made while already latched keeps
533
+ // its answer: it writes after this and re-latches sentence to sentence. A press or pick whose
534
+ // own health poll latches the refusal for the first time loses its answer here and shows
535
+ // the sentence alone, which is the same text it answered with.
536
+ if (this._refusalMsg === null && msg !== null) {
537
+ this.clearEnableError();
538
+ this.clearDeviceError();
539
+ }
540
+ this._refusalMsg = msg;
541
+ this.emit("refusal", msg);
542
+ }
401
543
  // Drop the reason outright. Used where the reason is not merely from another outage but describes a
402
544
  // question that was never answered, or a device we are no longer bound to. The epoch stamp handles
403
545
  // "belongs to a different outage"; this handles "belongs to nothing".
@@ -409,6 +551,13 @@ class Store {
409
551
  this._enableErrorEpoch = -1;
410
552
  this.emit("enable-error", this.visibleEnableError);
411
553
  }
554
+ clearDeviceError() {
555
+ if (this.deviceError === null)
556
+ return;
557
+ this.deviceError = null;
558
+ this.deviceErrorInstructs = false;
559
+ this.emit("device-error", null);
560
+ }
412
561
  // Capture-source names the device declares on ping (seam builds). null = old build with no
413
562
  // discovery, in which case every tab shows (today's behavior). Emitted as "sources" on change.
414
563
  deviceSources = null;
@@ -431,6 +580,11 @@ class Store {
431
580
  liveMatches = 0;
432
581
  graph = null;
433
582
  feedVersion = 0;
583
+ // Field names seen with a non-null value, per record type, for the whole session (an eviction
584
+ // does not unmark). Answers the chips' "does any row of this tab carry this field" in O(1)
585
+ // rather than a walk over the cache on every feed bump; "fields" is emitted only when a name
586
+ // is new, so a subscriber pays nothing for the stream's ordinary rows.
587
+ _fieldsSeen = new Map();
434
588
  // Bumped on every observed serial change (first pin included), emitted as "db-resync". The DB
435
589
  // tab keys its remount off this so it drops stale picked-db/table/results and re-fetches /dbs
436
590
  // when the bound device changes — including the null->serial FIRST pin, where the tab loaded
@@ -442,6 +596,10 @@ class Store {
442
596
  // and back to Logs lands on the same level. Read by specForTab. Any log-carrying spec counts,
443
597
  // an agent-authored one included: a log view Claude pushes with no level is the last level seen.
444
598
  lastLogLevel = "";
599
+ // What each preset tab was last looked at through (see VIEW_MEMORY_KEY). Loaded once here, at
600
+ // construction, so it is in place before the first spec push of the page; written by applySpec
601
+ // on every preset spec this page authored, read by specForTab on every preset push.
602
+ viewMemory = readViewMemory();
445
603
  detailCache = new Map();
446
604
  _capSeen = new Set();
447
605
  _capQueue = [];
@@ -453,8 +611,42 @@ class Store {
453
611
  _healthMisses = 0;
454
612
  _specKey = "";
455
613
  _localPushKey = null;
614
+ // Bumped when a push is applied at ack time (see setSpec), so a /spec GET that was already in
615
+ // flight when the ack landed is dropped rather than applied over the newer spec.
616
+ _specGen = 0;
456
617
  _lastBoundLabel = null;
457
618
  _backfillToken = 0;
619
+ // Per switchboard session id, the run currently held for it. Session ids restart with the app
620
+ // process, so one id can name several runs over a tab's life; see switchboardRunFor for when a
621
+ // begin starts a new one.
622
+ _switchboardRuns = new Map();
623
+ // server_session_id per session_id, for the id's current run only: learned from that run's
624
+ // `ready` record or its per-session refill's detail envelope, and dropped when a new run starts
625
+ // under the id. undefined means not learned yet; null means the summary reported the key but it
626
+ // was itself null (see voice-model.ts's serverSessionId).
627
+ _switchboardSummaryServerId = new Map();
628
+ // saved_turn_counts per session id, off the same refill envelope and dropped with it on a new run,
629
+ // with the newest record id that envelope carried: the counts are a snapshot through that id, and
630
+ // the panel adds the saved_turn rows newer than it. Absent until a refill lands one; an older
631
+ // build never sends it.
632
+ _switchboardSummarySavedTurnCounts = new Map();
633
+ // The two winning votes behind switchboardNewestCut(): the newest begin and the newest non-end
634
+ // record. Updated as rows land so a read is O(1); an eviction or clear that removes a winner
635
+ // marks them stale and the next read rescans the cache once.
636
+ _sbBestBegin = null;
637
+ _sbBestAny = null;
638
+ _sbVotesStale = false;
639
+ // The cut the feed was last bumped for (see announceCutMove).
640
+ _sbAnnouncedCut = null;
641
+ // The rows behind switchboardRunRows() and the cut they were built for (null: rebuild on the
642
+ // next read). A frame only appends to them or notes an evicted row, both O(1); sorting, dropping
643
+ // the evicted rows and copying out wait for a read, so a busy call costs O(run) once per read
644
+ // rather than per frame. _sbRunRowsView is the copy readers get, null once the rows changed.
645
+ _sbRunRows = null;
646
+ _sbRunRowsCut = null;
647
+ _sbRunRowsGone = new Set();
648
+ _sbRunRowsUnsorted = false;
649
+ _sbRunRowsView = null;
458
650
  // True while the connection is in a dropped/waiting state. Lets pollHealth detect the
459
651
  // drop->recover EDGE (device came back) so it can re-open the stream + backfill ONCE on
460
652
  // recovery, instead of every poll. Without this, an auto-recovered tab flips the dot to
@@ -498,15 +690,17 @@ class Store {
498
690
  return { "X-Radar-Dashboard": "1", "X-Radar-Tab": this._tabId, ...extra };
499
691
  }
500
692
  // ---- shared detail cache (bounded FIFO) ----
501
- cacheDetail(kind, id, detail) {
502
- const key = kind + ":" + id;
693
+ // Keyed like the ring (frameKey): id plus timestamp, so after an app restart reuses an id the
694
+ // new record does not read the old process's body out of this cache.
695
+ cacheDetail(kind, ev, detail) {
696
+ const key = this.frameKey(kind, ev);
503
697
  this.detailCache.set(key, detail);
504
698
  while (this.detailCache.size > DETAIL_CACHE_CAP) {
505
699
  this.detailCache.delete(this.detailCache.keys().next().value);
506
700
  }
507
701
  }
508
- getDetail(kind, id) {
509
- return this.detailCache.get(kind + ":" + id);
702
+ getDetail(kind, ev) {
703
+ return this.detailCache.get(this.frameKey(kind, ev));
510
704
  }
511
705
  // ---- eager body capture (any EAGER_CAPTURE tab, while it is open) ----
512
706
  // The device ring evicts old records (network keeps 400), so a row clicked later is gone. While a
@@ -524,25 +718,25 @@ class Store {
524
718
  return;
525
719
  if (src !== "all" && src !== kind)
526
720
  return;
527
- const key = kind + ":" + ev.id;
721
+ const key = this.frameKey(kind, ev);
528
722
  if (this._capSeen.has(key) || this.detailCache.has(key))
529
723
  return;
530
724
  this._capSeen.add(key);
531
725
  if (this._capSeen.size > CAP_SEEN_CAP)
532
726
  this._capSeen.delete(this._capSeen.values().next().value);
533
- this._capQueue.push({ kind, id: ev.id });
727
+ this._capQueue.push({ kind, ev });
534
728
  this._drainCapture();
535
729
  }
536
730
  _drainCapture() {
537
731
  while (this._capInflight < CAPTURE_CONCURRENCY && this._capQueue.length) {
538
- const { kind, id } = this._capQueue.shift();
732
+ const { kind, ev } = this._capQueue.shift();
539
733
  this._capInflight++;
540
- fetch("/detail?kind=" + kind + "&id=" + id)
734
+ fetch("/detail?kind=" + kind + "&id=" + ev.id)
541
735
  .then((r) => r.json())
542
736
  .then((d) => {
543
737
  // skip the eviction error / empty; only cache a real payload
544
738
  if (d && !(d.error && d.url == null && d.method == null)) {
545
- this.cacheDetail(kind, id, { ...d, _type: kind });
739
+ this.cacheDetail(kind, ev, { ...d, _type: kind });
546
740
  }
547
741
  })
548
742
  .catch(() => { })
@@ -575,7 +769,10 @@ class Store {
575
769
  // them). Deliberately NOT reset: subscribers, live timers and stream handles (start() and
576
770
  // openStream() own those lifecycles), and _tabId, which identifies the page for its whole life.
577
771
  _resetForTest() {
772
+ this.platform = null;
773
+ this.logPackage = DEFAULT_LOG_PACKAGE;
578
774
  this.lastLogLevel = "";
775
+ this.viewMemory = {};
579
776
  this.spec = { blank: true, viz: [] };
580
777
  this.conn = { state: "waiting", msg: "connecting…" };
581
778
  this.selfHeal = null;
@@ -594,6 +791,7 @@ class Store {
594
791
  this._enableErrorEpoch = -1;
595
792
  this.sessionEnded = false;
596
793
  this.enabling = false;
794
+ this._refusalMsg = null;
597
795
  this.autoRearming = false;
598
796
  this.autoRearmSuppressed = false;
599
797
  this.selfArmBlocked = null;
@@ -622,6 +820,10 @@ class Store {
622
820
  this.liveMatches = 0;
623
821
  this.graph = null;
624
822
  this.feedVersion = 0;
823
+ this._fieldsSeen = new Map();
824
+ // A fresh chain, or a write a test left in flight would hold the next test's writes behind it.
825
+ this._writeChain = Promise.resolve();
826
+ this.setSpecTimeoutMs = 8000;
625
827
  this.dbSerialVersion = 0;
626
828
  this.customActive = false;
627
829
  this.lastCustomSpec = null;
@@ -633,8 +835,21 @@ class Store {
633
835
  this._healthMisses = 0;
634
836
  this._specKey = "";
635
837
  this._localPushKey = null;
838
+ this._specGen = 0;
636
839
  this._lastBoundLabel = null;
637
840
  this._backfillToken = 0;
841
+ this._switchboardRuns = new Map();
842
+ this._switchboardSummaryServerId = new Map();
843
+ this._switchboardSummarySavedTurnCounts = new Map();
844
+ this._sbBestBegin = null;
845
+ this._sbBestAny = null;
846
+ this._sbVotesStale = false;
847
+ this._sbAnnouncedCut = null;
848
+ this._sbRunRows = null;
849
+ this._sbRunRowsCut = null;
850
+ this._sbRunRowsGone = new Set();
851
+ this._sbRunRowsUnsorted = false;
852
+ this._sbRunRowsView = null;
638
853
  this._dropped = false;
639
854
  this._lastSerial = null;
640
855
  // Cancel rather than just forget: a rAF queued before the reset would otherwise fire after
@@ -674,11 +889,15 @@ class Store {
674
889
  if (scopeToSource !== undefined && scopeToSource !== "all") {
675
890
  this.cache = this.cache.filter((c) => c.type !== scopeToSource);
676
891
  this.cacheKeys = new Set(this.cache.map((c) => this.frameKey(c.type, c.ev)));
892
+ this._fieldsSeen.delete(scopeToSource);
677
893
  }
678
894
  else {
679
895
  this.cache = [];
680
896
  this.cacheKeys = new Set();
897
+ this._fieldsSeen = new Map();
681
898
  }
899
+ this._sbVotesStale = true;
900
+ this._sbRunRows = null;
682
901
  this.seen = {};
683
902
  this.detailCache = new Map();
684
903
  this._capSeen = new Set();
@@ -703,6 +922,11 @@ class Store {
703
922
  // phone. Timers and spec are left running.
704
923
  clearDeviceCaches() {
705
924
  this.clearRecords();
925
+ // Session ids restart at 1 on every phone, so the old device's runs and server ids would
926
+ // claim the new device's sessions of the same id.
927
+ this._switchboardRuns = new Map();
928
+ this._switchboardSummaryServerId = new Map();
929
+ this._switchboardSummarySavedTurnCounts = new Map();
706
930
  // The old device's declared sources do not describe the new one; null until its next poll.
707
931
  this.updateSources(null);
708
932
  // Same for the screen capabilities: they come from the old device's platform, so a new phone
@@ -733,9 +957,10 @@ class Store {
733
957
  *
734
958
  * Emits "feed" synchronously rather than through bumpFeed's rAF batch. A clear is a direct
735
959
  * response to a click and must land on THIS frame; the batch exists to coalesce stream floods.
736
- * Note the feed's own "feed" handler is incremental (it diffs against store.cache.length, which
737
- * does not necessarily shrink to 0 -- other tabs' entries can remain) -- the caller re-snapshots
738
- * its view via viewFrames(), which filters by source and is what actually guarantees zero rows.
960
+ * Note the feed's own "feed" handler is incremental (it finds what is new by the cache entry
961
+ * that sat at its cursor; after a clear that entry is gone, so everything still held reads as
962
+ * new, and other tabs' entries can remain) -- the caller re-snapshots its view via
963
+ * viewFrames(), which filters by source and is what actually guarantees zero rows.
739
964
  */
740
965
  clearView() {
741
966
  this.clearRecords(this.spec.source || "all");
@@ -750,8 +975,14 @@ class Store {
750
975
  // and applied the still-blank spec bootDefault was in the middle of replacing, undoing the
751
976
  // local default bootDefault had just set and stranding the page on the blank placeholder
752
977
  // until the next 700ms tick happened to read the corrected value.
978
+ try {
979
+ // /health waits for the device ping, which can take up to four seconds.
980
+ const health = await (await fetch("/health", { signal: AbortSignal.timeout(6000) })).json();
981
+ this.updatePlatform(health.platform, health.log_package);
982
+ }
983
+ catch { /* retain Android defaults if health is unavailable */ }
753
984
  await this.bootDefault();
754
- this.watchSuppressionAcrossTabs();
985
+ this.watchStorageAcrossTabs();
755
986
  this.fetchSelfHeal();
756
987
  this.fetchSetupHint();
757
988
  this.pollSpec();
@@ -760,7 +991,7 @@ class Store {
760
991
  this._intervals.push(setInterval(() => this.pollHealth(), POLL_HEALTH_MS));
761
992
  this.pollProfile();
762
993
  this._intervals.push(setInterval(() => this.pollProfile(), POLL_PROFILE_MS));
763
- this._intervals.push(setInterval(() => this.evictCache(), 30000));
994
+ this._intervals.push(setInterval(() => this.evictOnTimer(), 30000));
764
995
  }
765
996
  // Stop all timers + the stream. Not used by the live page (the store is a singleton for the
766
997
  // life of the tab), but lets a test tear the engine down so it does not leak timers.
@@ -812,8 +1043,10 @@ class Store {
812
1043
  // the ambiguity is about which device to pin, not about whether a session is serving
813
1044
  // frames, and letting the override eat the refutation would leave the header claiming
814
1045
  // "no radar session" about a session that just spoke.
815
- if (state === "connected" && observed)
1046
+ if (state === "connected" && observed) {
816
1047
  this.refuteSessionEnded();
1048
+ this.setRefusal(null);
1049
+ }
817
1050
  // Unpinned multi-device is never "connected": frames can ride a stale forward from a prior
818
1051
  // pin and flip the dot green while the per-device surfaces (DB run-as) are broken by the
819
1052
  // ambiguity. Override any connected claim to a waiting "pick one" until a device is pinned.
@@ -851,6 +1084,7 @@ class Store {
851
1084
  }
852
1085
  async pollSpec() {
853
1086
  try {
1087
+ const gen = this._specGen;
854
1088
  const res = await fetch("/spec");
855
1089
  // The server already stamps its version on /spec (the adopt-path check);
856
1090
  // reuse it here so the header can show which Radar version is serving.
@@ -862,18 +1096,14 @@ class Store {
862
1096
  this.emit("version", ver);
863
1097
  }
864
1098
  const spec = await res.json();
1099
+ // A push was acked while this GET was on the wire: what it read predates that push, and
1100
+ // applying it would roll the page back until the next tick. The next poll reads the truth.
1101
+ if (gen !== this._specGen)
1102
+ return;
865
1103
  const key = JSON.stringify(spec);
866
1104
  if (key === this._specKey)
867
1105
  return;
868
- this._specKey = key;
869
- const isLocalEdit = key === this._localPushKey;
870
- if (isLocalEdit)
871
- this._localPushKey = null;
872
- this.customActive = !isLocalEdit && !!spec && !spec.blank && specMatchesMode(spec) === null;
873
- if (this.customActive && (!this.lastCustomSpec || JSON.stringify(this.lastCustomSpec) !== key)) {
874
- this.lastCustomSpec = spec;
875
- }
876
- this.applySpec(spec);
1106
+ this.adopt(spec, key, key === this._localPushKey);
877
1107
  }
878
1108
  catch {
879
1109
  /* transient; next poll retries */
@@ -889,8 +1119,11 @@ class Store {
889
1119
  // takes, even though the intent is always to land on Live. start() awaits this method
890
1120
  // before its own first pollSpec() runs, so that later read confirms the same spec
891
1121
  // rather than racing this one and overwriting it back to blank.
892
- this.applySpec(MODES[0].spec);
893
- await fetch("/setspec", { method: "POST", headers: this.authoredHeaders({ "Content-Type": "application/json" }), body: JSON.stringify(MODES[0].spec) }).catch(() => { });
1122
+ // Through specForTab, as a Live tab click is: the pristine preset would drop the exclusions
1123
+ // this browser remembers for Live on every fresh server. viewMemory is read at construction.
1124
+ const spec = specForTab(this.presetSpec(MODES[0].spec), null, this.lastLogLevel, this.viewMemory, this.logPackage);
1125
+ this.applySpec(spec, { local: true });
1126
+ await fetch("/setspec", { method: "POST", headers: this.authoredHeaders({ "Content-Type": "application/json" }), body: JSON.stringify(spec) }).catch(() => { });
894
1127
  }
895
1128
  }
896
1129
  catch {
@@ -931,30 +1164,148 @@ class Store {
931
1164
  markLocalPush(spec) {
932
1165
  this._localPushKey = JSON.stringify(spec);
933
1166
  }
934
- async setSpec(spec, opts = {}) {
1167
+ // Take `spec` as the current one. Shared by the poll (the server's spec changed under us, or
1168
+ // our own push echoed back) and by setSpec (our push was just acked). The key is set first so
1169
+ // the poll's later echo early-returns: one applySpec, one stream reconnect, memory written once.
1170
+ // `isLocalEdit` says this page authored the spec; only then does applySpec record the view.
1171
+ adopt(spec, key, isLocalEdit) {
1172
+ this._specKey = key;
1173
+ if (this._localPushKey === key)
1174
+ this._localPushKey = null;
1175
+ this.customActive = !isLocalEdit && !!spec && !spec.blank && this.matchesMode(spec) === null;
1176
+ if (this.customActive && (!this.lastCustomSpec || JSON.stringify(this.lastCustomSpec) !== key)) {
1177
+ this.lastCustomSpec = spec;
1178
+ }
1179
+ this.applySpec(spec, { local: isLocalEdit });
1180
+ }
1181
+ // Every local write goes through one chain: a link runs once the one before it has settled and
1182
+ // reads the spec the store holds at that moment (an accepted push is applied at ack time). Two
1183
+ // controls writing inside one round trip used to post two bodies off the same un-acked list, so
1184
+ // the second dropped the first's edit, and a queue kept in one component left the others racing
1185
+ // it. `fn` is handed that acked spec and returns the next one, or null to write nothing (the tab
1186
+ // it was pressed on is gone, the term is already on the list); a null resolves `skipped`.
1187
+ _writeChain = Promise.resolve();
1188
+ // How long one push may wait for the server before the chain moves on. A POST that never
1189
+ // answered used to hold every later write behind it for good. A field so a test can shorten it.
1190
+ setSpecTimeoutMs = 8000;
1191
+ updateSpec(fn, opts = {}) {
1192
+ const run = this._writeChain.then(() => {
1193
+ const next = fn(this.spec);
1194
+ if (next === null)
1195
+ return { ok: true, skipped: true };
1196
+ return this.postSpec(next, opts);
1197
+ });
1198
+ this._writeChain = run.catch(() => undefined);
1199
+ return run;
1200
+ }
1201
+ // Resolves on the server's answer, in the order the writes were made. An accepted spec is applied
1202
+ // at ack time, so every control (chips, level, app, Filters Apply, the exclude box) builds its
1203
+ // next edit on it at once rather than on a prop that lags until the poll brings the echo. A
1204
+ // refused or failed push applies nothing.
1205
+ setSpec(spec, opts = {}) {
1206
+ return this.updateSpec(() => spec, opts);
1207
+ }
1208
+ // A preset push (tab click, keyboard tab move, the device-switch reset) goes through specForTab
1209
+ // against the spec the store holds when the write's turn comes, not the one the click saw. Built
1210
+ // at click time, a Live click made while a Logs level change was in flight posted a body with no
1211
+ // level, and applySpec forgot the level with it.
1212
+ pushPreset(preset, opts = {}) {
1213
+ return this.updateSpec((base) => specForTab(this.presetSpec(preset), base, this.lastLogLevel, this.viewMemory, this.logPackage), opts);
1214
+ }
1215
+ async postSpec(spec, opts) {
935
1216
  if (opts.local)
936
1217
  this.markLocalPush(spec);
1218
+ const key = JSON.stringify(spec);
1219
+ let r;
1220
+ const ctrl = new AbortController();
1221
+ let timedOut = false;
1222
+ const timer = setTimeout(() => { timedOut = true; ctrl.abort(); }, this.setSpecTimeoutMs);
937
1223
  try {
938
1224
  // X-Radar-Dashboard marks this as an authored write (see the server's handleSetSpec): it is
939
1225
  // what lets the write count as a keep-alive, and a foreign origin cannot forge it. X-Radar-Tab
940
- // says the keep-alive is THIS window's rather than an agent session's.
941
- return await (await fetch("/setspec", { method: "POST", headers: this.authoredHeaders({ "Content-Type": "application/json" }), body: JSON.stringify(spec) })).json();
1226
+ // says the keep-alive is THIS window's rather than an agent session's. The race, not the
1227
+ // signal alone, bounds the wait: the signal ends a real request, the race ends the wait even
1228
+ // for a fetch that ignores it.
1229
+ r = await Promise.race([
1230
+ fetch("/setspec", { method: "POST", headers: this.authoredHeaders({ "Content-Type": "application/json" }), body: key, signal: ctrl.signal }).then((res) => res.json()),
1231
+ new Promise((_, reject) => ctrl.signal.addEventListener("abort", () => reject(new Error("timed out")), { once: true })),
1232
+ ]);
942
1233
  }
943
1234
  catch {
944
- return { ok: false, error: "request failed" };
1235
+ // The write may have landed and only the reply was lost, so the local-push key stays: if the
1236
+ // echo does arrive it is still this page's edit. The copy says so, or a chip that flips when
1237
+ // the poll brings that echo would look like it moved on its own.
1238
+ return { ok: false, error: timedOut ? "request timed out; the list follows the server when it answers" : "request failed" };
1239
+ }
1240
+ finally {
1241
+ clearTimeout(timer);
1242
+ }
1243
+ if (r && r.ok) {
1244
+ // A push of the spec already in force (a click on the lit tab, an untouched Apply) changes
1245
+ // nothing, so it must not reopen the stream or zero the counters; the poll dedupes the same way.
1246
+ if (key !== this._specKey) {
1247
+ this._specGen++;
1248
+ this.adopt(spec, key, !!opts.local);
1249
+ }
1250
+ else if (this._localPushKey === key) {
1251
+ this._localPushKey = null;
1252
+ }
1253
+ }
1254
+ else if (r && this._localPushKey === key) {
1255
+ // Refused by the server: nothing was stored, so no echo can arrive for this key.
1256
+ this._localPushKey = null;
945
1257
  }
1258
+ return r;
1259
+ }
1260
+ /** Return a platform-specific copy of a built-in preset without mutating MODES. */
1261
+ presetSpec(spec) {
1262
+ if ((spec.source !== "log" && spec.source !== "all") ||
1263
+ spec.match?.package !== DEFAULT_LOG_PACKAGE ||
1264
+ !this.logPackage ||
1265
+ this.logPackage === DEFAULT_LOG_PACKAGE) {
1266
+ return spec;
1267
+ }
1268
+ return { ...spec, match: { ...spec.match, package: this.logPackage } };
946
1269
  }
947
1270
  activeModeKey() {
948
- return this.customActive ? "__custom__" : specMatchesMode(this.spec);
1271
+ return this.customActive ? "__custom__" : this.matchesMode(this.spec);
1272
+ }
1273
+ matchesMode(spec) {
1274
+ return specMatchesMode(spec, this.logPackage);
949
1275
  }
950
1276
  // Rebuild all derived state for a new spec, reconnect the stream (so the server
951
1277
  // attaches/detaches the host-side logcat session for log/all sources), replay the cache, and
952
- // backfill the device ring. Mirrors vanilla build(spec).
953
- applySpec(spec) {
1278
+ // backfill the device ring. Mirrors vanilla build(spec). `local` says this page authored the
1279
+ // spec (a chip, the level selector, Filters Apply): only then is a preset's view
1280
+ // remembered, so a spec an agent pushes neither reads the memory (specForTab) nor rewrites it.
1281
+ platform = null;
1282
+ logPackage = DEFAULT_LOG_PACKAGE;
1283
+ applySpec(spec, opts = {}) {
1284
+ const prev = this.spec;
954
1285
  this.spec = spec || { blank: true, viz: [] };
1286
+ this.rekeyExclude();
955
1287
  if (this.spec.source === "log" || this.spec.source === "all") {
956
1288
  this.lastLogLevel = typeof this.spec.minLevel === "string" ? this.spec.minLevel : "";
957
1289
  }
1290
+ const modeKey = this.matchesMode(this.spec);
1291
+ if (modeKey && opts.local)
1292
+ this.rememberView(modeKey, this.spec);
1293
+ // A change to the exclude list alone (a kind chip pressed, a term typed or removed) is a view
1294
+ // filter over the cache the feed already holds: same source, same stream, same rows. So the
1295
+ // stream stays open and the backfill is not fetched again (a full rebuild here made every chip
1296
+ // press reconnect). The widgets are still recounted from the cache: hidden rows leave the rate,
1297
+ // sparkline and graph, as the contract says, so the aggregates are zeroed and replayed under
1298
+ // the new list. The "spec" emit is what makes the feed re-filter.
1299
+ if (differsOnlyInExclude(prev, this.spec)) {
1300
+ this.total = 0;
1301
+ this.liveMatches = 0;
1302
+ this.times = [];
1303
+ this.perSec = new Array(PERSEC_N).fill(0);
1304
+ this.graph = this.buildGraph();
1305
+ this.emit("spec", this.spec);
1306
+ this.replayCache();
1307
+ return;
1308
+ }
958
1309
  this.total = 0;
959
1310
  this.liveMatches = 0;
960
1311
  this.times = [];
@@ -979,6 +1330,27 @@ class Store {
979
1330
  this.replayCache();
980
1331
  this.backfill();
981
1332
  }
1333
+ // Record how a preset tab is being looked at: its exclude list. A list the spec no longer
1334
+ // carries leaves the entry (the last chip removed), so what is remembered is always the last
1335
+ // thing seen on the tab. The level is not kept here: Logs and Live share lastLogLevel for it.
1336
+ //
1337
+ // Read-modify-write on the stored map, touching only this key: two dashboard windows share
1338
+ // the storage, and a whole-map write from one would erase what the other remembered for its
1339
+ // tabs. Without storage the page's own copy is the map.
1340
+ rememberView(key, spec) {
1341
+ const mem = readStoredViewMemory() ?? this.viewMemory;
1342
+ const entry = { ...(mem[key] ?? {}) };
1343
+ if (Array.isArray(spec.exclude) && spec.exclude.length)
1344
+ entry.exclude = spec.exclude.map(String);
1345
+ else
1346
+ delete entry.exclude;
1347
+ if (Object.keys(entry).length)
1348
+ mem[key] = entry;
1349
+ else
1350
+ delete mem[key];
1351
+ this.viewMemory = mem;
1352
+ writeViewMemory(mem);
1353
+ }
982
1354
  // ---- stream ----
983
1355
  openStream() {
984
1356
  this.closeStream();
@@ -988,7 +1360,7 @@ class Store {
988
1360
  // poll re-opens + backfills (recovered()), not just flips the dot green.
989
1361
  es.onerror = () => {
990
1362
  this._dropped = true;
991
- this.setConn("waiting", "reconnecting…");
1363
+ this.setConn("waiting", this._refusalMsg === null ? "reconnecting…" : UNAUTHORIZED_HEAD);
992
1364
  };
993
1365
  this._es = es;
994
1366
  }
@@ -1006,17 +1378,19 @@ class Store {
1006
1378
  catch {
1007
1379
  return;
1008
1380
  }
1381
+ f.type = normalizeStreamType(f.type);
1009
1382
  if (f.type === "_status") {
1010
1383
  // reason is typed as a plain string on purpose: the client acts on the known value and
1011
1384
  // treats every other value as a retraction (see src/shared/wire.ts StatusReason), so a
1012
1385
  // server that adds a reason later needs no client change.
1013
1386
  const e = f.event;
1387
+ const refused = e.reason === "unauthorized" && typeof e.msg === "string";
1014
1388
  // conn first, reason second: a reasoned frame is itself a waiting report, and
1015
1389
  // noteNoSession's immediate re-arm attempt reads conn.state — handled the other way
1016
1390
  // around, a diagnosis arriving right after a connected blip would see the stale
1017
1391
  // "connected" and skip the immediate attempt it exists for. observed=true: a connected
1018
1392
  // _status is the proxy vouching its upstream actually answered.
1019
- this.setConn(e.state, e.msg, true);
1393
+ this.setConn(e.state, refused ? UNAUTHORIZED_HEAD : e.msg, true);
1020
1394
  // The reason is the outage's CURRENT diagnosis (see src/shared/wire.ts StatusReason): only
1021
1395
  // no_session latches, and any other reason, today "undiagnosed" and whatever a later server
1022
1396
  // adds, retires the latch. Dispatching on the retraction token itself would leave the latch
@@ -1026,6 +1400,13 @@ class Store {
1026
1400
  this.noteNoSession();
1027
1401
  else
1028
1402
  this.retireNoSession();
1403
+ // A reasoned frame is the current diagnosis, so a non-refusal releases the held refusal.
1404
+ if (!refused)
1405
+ this.setRefusal(null);
1406
+ }
1407
+ if (refused) {
1408
+ this._healthMisses = 0;
1409
+ this.setRefusal(e.msg);
1029
1410
  }
1030
1411
  return;
1031
1412
  }
@@ -1059,6 +1440,18 @@ class Store {
1059
1440
  }
1060
1441
  const ev = f.event || {};
1061
1442
  ev._type = f.type;
1443
+ if (f.type === "switchboard" && typeof ev.session_id === "number") {
1444
+ const run = this.switchboardRunFor(ev.session_id, ev, live);
1445
+ // Learn a ready record's server_session_id the moment it's seen, live or not, so the pill
1446
+ // keeps it after the ready row itself ages out of the capped cache. Only a ready from the
1447
+ // id's current run counts: one from an older process under the same id names another call.
1448
+ if (ev.kind === "session" && ev.event === "ready" && Object.hasOwn(ev, "server_session_id") && inSwitchboardRun(ev, run)) {
1449
+ this._switchboardSummaryServerId.set(ev.session_id, ev.server_session_id ?? null);
1450
+ }
1451
+ if (ev.kind === "saved_turn" && typeof ev.outcome === "string" && typeof ev.id === "number" && inSwitchboardRun(ev, run)) {
1452
+ run.savedTurns.set(ev.id, ev.outcome);
1453
+ }
1454
+ }
1062
1455
  const isNew = this.cacheFrame(f.type, ev);
1063
1456
  if (this.spec.source !== "all" && f.type !== this.spec.source)
1064
1457
  return;
@@ -1072,32 +1465,172 @@ class Store {
1072
1465
  return;
1073
1466
  this.accept(ev, live);
1074
1467
  }
1468
+ // The run of `sid` that `ev` belongs to, starting a new one when `ev` shows the id was reused.
1469
+ // A begin later than everything on record for the id's run is a new run under a reused id (ids
1470
+ // restart with the app process), whether it arrives live or by backfill: the old run's server id
1471
+ // is dropped and the new run refilled. An older or repeated begin changes nothing. A run's first
1472
+ // live record (a live begin, or a live row with no begin behind it: opened mid-call, or the
1473
+ // stream just connected) refills it once so its rows and server_session_id fill in beyond that
1474
+ // one record. A run only ever seen by backfill is not refilled, since a fresh store's backfill
1475
+ // can carry several sessions at once.
1476
+ switchboardRunFor(sid, ev, live) {
1477
+ const ts = typeof ev.timestamp === "number" ? ev.timestamp : null;
1478
+ const isBegin = ev.kind === "session" && ev.event === "begin";
1479
+ let run = this._switchboardRuns.get(sid);
1480
+ let reused = false;
1481
+ if (run && isBegin && ts !== null) {
1482
+ const known = run.beganAt ?? run.firstSeenAt;
1483
+ if (known !== null && ts > known)
1484
+ reused = true;
1485
+ // This run's own begin, arriving after some of its rows.
1486
+ else if (run.beganAt === null)
1487
+ run.beganAt = ts;
1488
+ }
1489
+ if (reused) {
1490
+ this._switchboardSummaryServerId.delete(sid);
1491
+ this._switchboardSummarySavedTurnCounts.delete(sid);
1492
+ }
1493
+ if (!run || reused) {
1494
+ run = { beganAt: isBegin ? ts : null, firstSeenAt: ts, filled: false, maxId: -Infinity, savedTurns: new Map() };
1495
+ this._switchboardRuns.set(sid, run);
1496
+ }
1497
+ if (typeof ev.id === "number" && ev.id > run.maxId && inSwitchboardRun(ev, run))
1498
+ run.maxId = ev.id;
1499
+ if (!run.filled && (live || reused)) {
1500
+ run.filled = true;
1501
+ void this.backfillSwitchboardSession(sid, run);
1502
+ }
1503
+ return run;
1504
+ }
1075
1505
  // ---- CACHE ring (dedup + bounded by count and age) ----
1076
1506
  frameKey(type, ev) {
1077
- return type + ":" + (ev.id != null ? ev.id : (ev.log_ts || "") + "|" + (ev.pid || "") + "|" + (ev.message || ev.event_type || ev.event_name || ""));
1507
+ // Every kind the stream gate admits carries an id (the device kinds mint theirs per app
1508
+ // process, so the counter restarts with the process; logs get a host-minted one), and a tab
1509
+ // left open on the same device keeps its cache (TTL 1h, capped by count), so on id alone the next process's records
1510
+ // collide with cached keys and drop as duplicates. The timestamp rides along: a restart cannot
1511
+ // reuse both, while a backfilled record and its live twin carry the same device timestamp and
1512
+ // still share one key. A device record with no id (no shipped build sends one) keeps its
1513
+ // timestamp in the key so a whole backfill does not fold into one row; a log line with no id
1514
+ // falls to a content composite.
1515
+ if (ev.id != null || type !== "log")
1516
+ return type + ":" + (ev.id ?? "") + "|" + (ev.timestamp ?? "");
1517
+ return type + ":" + (ev.log_ts || "") + "|" + (ev.pid || "") + "|" + (ev.message || ev.event_type || ev.event_name || "");
1078
1518
  }
1079
1519
  cacheFrame(type, ev) {
1080
1520
  const k = this.frameKey(type, ev);
1081
1521
  if (this.cacheKeys.has(k))
1082
1522
  return false;
1083
1523
  this.cacheKeys.add(k);
1084
- this.cache.push({ type, ev, ts: ev.timestamp || Date.now() });
1524
+ const entry = { type, ev, ts: ev.timestamp || Date.now() };
1525
+ this.cache.push(entry);
1526
+ if (type === "switchboard") {
1527
+ this.voteSwitchboard(entry);
1528
+ this.addToRunRows(ev);
1529
+ }
1085
1530
  this.observe(ev);
1531
+ this.noteFields(type, ev);
1086
1532
  this.evictCache();
1533
+ if (type === "switchboard" || this._sbVotesStale)
1534
+ this.announceCutMove();
1087
1535
  return true;
1088
1536
  }
1537
+ // True once a row of `source` ("all": of any type) has carried `field` with a non-null value this
1538
+ // session. A null is the device saying the field does not apply to this row, so it is not a
1539
+ // carrier: a term on it hides nothing until a row gives it a value.
1540
+ fieldSeen(source, field) {
1541
+ if (source === "all") {
1542
+ for (const set of this._fieldsSeen.values())
1543
+ if (set.has(field))
1544
+ return true;
1545
+ return false;
1546
+ }
1547
+ return this._fieldsSeen.get(source)?.has(field) ?? false;
1548
+ }
1549
+ // True once any row of `source` has been seen this session. With none there is no verdict to
1550
+ // give on a field.
1551
+ rowsSeen(source) {
1552
+ return source === "all" ? this._fieldsSeen.size > 0 : this._fieldsSeen.has(source);
1553
+ }
1554
+ noteFields(type, ev) {
1555
+ let set = this._fieldsSeen.get(type);
1556
+ let added = false;
1557
+ if (!set) {
1558
+ set = new Set();
1559
+ this._fieldsSeen.set(type, set);
1560
+ added = true;
1561
+ }
1562
+ for (const k in ev) {
1563
+ if (ev[k] == null || set.has(k))
1564
+ continue;
1565
+ set.add(k);
1566
+ added = true;
1567
+ }
1568
+ if (added)
1569
+ this.emit("fields", type);
1570
+ }
1089
1571
  evictCache() {
1090
1572
  const cutoff = Date.now() - CACHE_TTL_MS;
1091
1573
  const drop = () => {
1092
1574
  const old = this.cache.shift();
1093
- if (old)
1094
- this.cacheKeys.delete(this.frameKey(old.type, old.ev));
1575
+ if (!old)
1576
+ return;
1577
+ this.cacheKeys.delete(this.frameKey(old.type, old.ev));
1578
+ if (old === this._sbBestBegin?.entry || old === this._sbBestAny?.entry)
1579
+ this._sbVotesStale = true;
1580
+ if (old.type === "switchboard" && this._sbRunRows !== null && this._sbRunRowsCut !== null && inSessionCut(old.ev, this._sbRunRowsCut)) {
1581
+ this._sbRunRowsGone.add(old.ev);
1582
+ this._sbRunRowsView = null;
1583
+ }
1095
1584
  };
1096
1585
  while (this.cache.length && this.cache[0].ts < cutoff)
1097
1586
  drop();
1098
1587
  while (this.cache.length > this.cacheCap)
1099
1588
  drop();
1100
1589
  }
1590
+ // The periodic TTL sweep. No frame lands with it, so it announces a moved cut itself.
1591
+ evictOnTimer() {
1592
+ this.evictCache();
1593
+ this.announceCutMove();
1594
+ }
1595
+ // Bump the feed when the newest switchboard cut has moved since the last bump for it. The frame
1596
+ // that moves it may be of another kind (a log line evicting the newest begin at the cap) or not
1597
+ // pass the tab's filter, and neither reaches accept()'s own bump; the feed resnaps on the bump.
1598
+ announceCutMove() {
1599
+ const cut = this.switchboardNewestCut();
1600
+ if (sameSessionCut(cut, this._sbAnnouncedCut))
1601
+ return;
1602
+ this._sbAnnouncedCut = cut;
1603
+ this.bumpFeed();
1604
+ }
1605
+ voteSwitchboard(entry) {
1606
+ if (this._sbVotesStale)
1607
+ return; // the rescan in switchboardNewestCut will count it
1608
+ const vote = sessionVote(entry.ev);
1609
+ if (!vote)
1610
+ return;
1611
+ if (vote.begin && outranks(vote, this._sbBestBegin?.vote ?? null))
1612
+ this._sbBestBegin = { entry, vote };
1613
+ if (!vote.end && outranks(vote, this._sbBestAny?.vote ?? null))
1614
+ this._sbBestAny = { entry, vote };
1615
+ }
1616
+ // A new row joins the held run's rows in place when the run it belongs to is still the newest.
1617
+ // A row that moves the cut (a newer begin, or a newer session) drops them instead, and the next
1618
+ // read rebuilds them for the new run.
1619
+ addToRunRows(ev) {
1620
+ if (this._sbRunRows === null)
1621
+ return;
1622
+ if (this._sbVotesStale || !sameSessionCut(this.switchboardNewestCut(), this._sbRunRowsCut)) {
1623
+ this._sbRunRows = null;
1624
+ return;
1625
+ }
1626
+ if (this._sbRunRowsCut === null || !inSessionCut(ev, this._sbRunRowsCut))
1627
+ return;
1628
+ const rows = this._sbRunRows;
1629
+ if (rows.length && byRecordTime(rows[rows.length - 1], ev) > 0)
1630
+ this._sbRunRowsUnsorted = true;
1631
+ rows.push(ev);
1632
+ this._sbRunRowsView = null;
1633
+ }
1101
1634
  observe(ev) {
1102
1635
  for (const f of SUGGEST_FIELDS) {
1103
1636
  let v = ev[f];
@@ -1152,6 +1685,78 @@ class Store {
1152
1685
  this.accept(ev, false);
1153
1686
  }
1154
1687
  }
1688
+ // Refill one run's rows, capped at 2000 (a single live-view refill, not the full-session
1689
+ // export), so the panel and feed are not left with only the single record they saw live.
1690
+ // Routed through onFrame(..., false) so it dedupes against what the live stream already
1691
+ // delivered. /api/switchboard/<id> is gated, so this sends the authored header.
1692
+ async backfillSwitchboardSession(sessionId, run) {
1693
+ // Read before the fetch goes out: everything held now predates the device's snapshot.
1694
+ const heldThroughId = run.maxId;
1695
+ try {
1696
+ const res = await fetch(`/api/switchboard/${sessionId}?limit=2000`, { headers: this.authoredHeaders() });
1697
+ const detail = await res.json();
1698
+ // A new-build device always sends server_session_id on the summary (present, maybe null);
1699
+ // an older build omits the key entirely. voice-model.ts's serverSessionId reads the key's
1700
+ // presence as proof the session will eventually report an id, so use Object.hasOwn, not a
1701
+ // truthiness check on the value. A new run that started under the id while this fetch was
1702
+ // out owns the id's entry now, so this run's answer is not written over it.
1703
+ if (this._switchboardRuns.get(sessionId) === run && Object.hasOwn(detail ?? {}, "server_session_id")) {
1704
+ this._switchboardSummaryServerId.set(sessionId, detail.server_session_id ?? null);
1705
+ }
1706
+ // The device reads the summary and the page together, so the counts stop at the page's
1707
+ // highest id, or at the highest id held when the fetch went out if that is higher (an empty
1708
+ // page). With neither, every row the stream brings is newer.
1709
+ const counts = detail?.saved_turn_counts;
1710
+ const hasCounts = this._switchboardRuns.get(sessionId) === run && counts !== null && typeof counts === "object" && !Array.isArray(counts);
1711
+ if (hasCounts) {
1712
+ let throughId = heldThroughId;
1713
+ for (const e of detail?.events || []) {
1714
+ const id = e?.id;
1715
+ if (typeof id === "number" && id > throughId)
1716
+ throughId = id;
1717
+ }
1718
+ this._switchboardSummarySavedTurnCounts.set(sessionId, { counts: counts, throughId });
1719
+ }
1720
+ // A new run under the id, or a device switch, while the fetch was out: the page is another
1721
+ // run's (or another phone's) rows, and must not land in this cache.
1722
+ if (this._switchboardRuns.get(sessionId) !== run)
1723
+ return;
1724
+ for (const e of detail?.events || []) {
1725
+ this.onFrame({ data: JSON.stringify({ type: "switchboard", event: e }) }, false);
1726
+ }
1727
+ // The events may all be rows the tab already holds, which bump nothing; redraw for the counts.
1728
+ if (hasCounts)
1729
+ this.emit("tick", Date.now());
1730
+ }
1731
+ catch {
1732
+ /* device unreachable; the live stream still fills the session in going forward */
1733
+ }
1734
+ }
1735
+ // server_session_id for sessionId, as learned by the refill above: undefined when nothing has
1736
+ // landed yet, a string or null once it has.
1737
+ switchboardSummaryServerId(sessionId) {
1738
+ return this._switchboardSummaryServerId.get(sessionId);
1739
+ }
1740
+ // The saved_turn outcomes seen for sessionId's current run, by record id; undefined before any
1741
+ // record of the id.
1742
+ switchboardSavedTurnOutcomes(sessionId) {
1743
+ return this._switchboardRuns.get(sessionId)?.savedTurns;
1744
+ }
1745
+ // saved_turn_counts for sessionId, as learned by the refill above; undefined until one lands.
1746
+ switchboardSummarySavedTurnCounts(sessionId) {
1747
+ return this._switchboardSummarySavedTurnCounts.get(sessionId);
1748
+ }
1749
+ // A tab opened after the call sees the session only by backfill, which never refills a run (it
1750
+ // can carry several) and is capped, so the panel would have no summary counts and few rows. Fill
1751
+ // the newest session alone, once, the way its first live record would have.
1752
+ fillNewestSwitchboardRun() {
1753
+ const sid = this.switchboardNewestSessionId();
1754
+ const run = sid !== null ? this._switchboardRuns.get(sid) : undefined;
1755
+ if (sid === null || !run || run.filled)
1756
+ return;
1757
+ run.filled = true;
1758
+ void this.backfillSwitchboardSession(sid, run);
1759
+ }
1155
1760
  async backfill() {
1156
1761
  const myToken = ++this._backfillToken;
1157
1762
  const src = this.spec.source;
@@ -1165,6 +1770,7 @@ class Store {
1165
1770
  return;
1166
1771
  for (const f of r?.frames || [])
1167
1772
  this.onFrame({ data: JSON.stringify(f) }, false);
1773
+ this.fillNewestSwitchboardRun();
1168
1774
  }
1169
1775
  catch {
1170
1776
  /* device unreachable; live stream still self-heals */
@@ -1253,14 +1859,63 @@ class Store {
1253
1859
  const w = (this.spec.rateWindowSec || 10) * 1000;
1254
1860
  return this.times.filter((t) => t >= now - w).length;
1255
1861
  }
1862
+ // The run the Switchboard tab's feed shows, or null when the cache holds no switchboard row a
1863
+ // session can be read off of. Computed with voice-model.ts's vote and cut, so it agrees with
1864
+ // newestSessionId and sessionRows over the same rows. O(1) unless a winning vote was evicted.
1865
+ switchboardNewestCut() {
1866
+ if (this._sbVotesStale) {
1867
+ this._sbVotesStale = false;
1868
+ this._sbBestBegin = null;
1869
+ this._sbBestAny = null;
1870
+ for (const c of this.cache)
1871
+ if (c.type === "switchboard")
1872
+ this.voteSwitchboard(c);
1873
+ }
1874
+ return cutFromVotes(this._sbBestBegin?.vote ?? null, this._sbBestAny?.vote ?? null);
1875
+ }
1876
+ switchboardNewestSessionId() {
1877
+ return this.switchboardNewestCut()?.sessionId ?? null;
1878
+ }
1879
+ // The rows of switchboardNewestCut()'s run, oldest first, as sessionRows orders them: what the
1880
+ // panel draws and the Switchboard feed shows. The same array until a row of the run lands or
1881
+ // leaves or the cut moves, so a caller can memoize on it; only a moved cut or a clear walks the
1882
+ // cache.
1883
+ switchboardRunRows() {
1884
+ const cut = this.switchboardNewestCut();
1885
+ if (this._sbRunRows === null || !sameSessionCut(cut, this._sbRunRowsCut)) {
1886
+ this._sbRunRowsCut = cut;
1887
+ this._sbRunRows = cut === null ? [] : runRows(this.cache.filter((c) => c.type === "switchboard").map((c) => c.ev), cut);
1888
+ this._sbRunRowsGone.clear();
1889
+ this._sbRunRowsUnsorted = false;
1890
+ this._sbRunRowsView = null;
1891
+ }
1892
+ if (this._sbRunRowsView === null) {
1893
+ const gone = this._sbRunRowsGone;
1894
+ if (gone.size) {
1895
+ this._sbRunRows = this._sbRunRows.filter((r) => !gone.has(r));
1896
+ gone.clear();
1897
+ }
1898
+ if (this._sbRunRowsUnsorted) {
1899
+ this._sbRunRows.sort(byRecordTime);
1900
+ this._sbRunRowsUnsorted = false;
1901
+ }
1902
+ this._sbRunRowsView = this._sbRunRows.slice();
1903
+ }
1904
+ return this._sbRunRowsView;
1905
+ }
1256
1906
  // Events the current tab's feed should show, chronological (oldest->newest). The feed owns
1257
1907
  // inversion/sort; chronological keeps a locked scroll stable (appends never shift an index).
1908
+ // The Switchboard tab shows only the newest session's current run; every other tab, Live
1909
+ // included, shows every row.
1258
1910
  viewFrames() {
1259
1911
  const src = this.spec.source;
1912
+ const cut = src === "switchboard" ? this.switchboardNewestCut() : null;
1260
1913
  const out = [];
1261
1914
  for (const c of this.cache) {
1262
1915
  if (src !== "all" && c.type !== src)
1263
1916
  continue;
1917
+ if (cut !== null && !inSessionCut(c.ev, cut))
1918
+ continue;
1264
1919
  const ev = c.ev;
1265
1920
  ev._type = c.type;
1266
1921
  if (!this.matches(ev))
@@ -1286,12 +1941,67 @@ class Store {
1286
1941
  this.selectedDevice === null);
1287
1942
  }
1288
1943
  matches(ev) {
1289
- // The lowest priority to show. Only log rows carry one, so on the "all" timeline network,
1290
- // rtm, clog and trace rows pass untouched, the same carve-out `package` gets below. A row whose
1291
- // priority the order does not know ranks -1 and is hidden (see levelRank).
1292
- const min = this.spec.minLevel;
1293
- if (typeof min === "string" && min && ev._type === "log" && levelRank(ev.level) < levelRank(min))
1944
+ if (!this.passesLevel(ev))
1945
+ return false;
1946
+ if (!this.passesMatch(ev))
1294
1947
  return false;
1948
+ // Last, so a row `match` already dropped never pays for building the haystack.
1949
+ return !this.excluded(ev);
1950
+ }
1951
+ // The level part of matches() on its own: the lowest priority to show. Only log rows carry one,
1952
+ // so on the "all" timeline network, rtm, clog and trace rows pass untouched, the same carve-out
1953
+ // `package` gets in passesMatch. A row whose priority the order does not know ranks -1 and is
1954
+ // hidden (see levelRank). The feed's empty state charges a hidden row to the floor before
1955
+ // anything else, so it needs this gate apart from the others.
1956
+ passesLevel(ev) {
1957
+ const min = this.spec.minLevel;
1958
+ return !(typeof min === "string" && min && ev._type === "log" && levelRank(ev.level) < levelRank(min));
1959
+ }
1960
+ // The exclude part of matches() on its own. A plain term reads the same haystack as the feed's
1961
+ // filter box (searchText), so a term typed there and a term carried by the spec hide exactly
1962
+ // the same rows; a field:value term tests one field for equality instead (parseExcludeTerm).
1963
+ // The terms are parsed and lowercased once per spec, on its first use (see excludeTerms).
1964
+ excluded(ev) {
1965
+ return this.excludeReason(ev) !== null;
1966
+ }
1967
+ // Which exclude term hid the row: "kind" for a kind:<name> term naming one of the Switchboard
1968
+ // tab's kind chips (they write those, so the empty line can name the chip; a pushed kind:mystery
1969
+ // has no chip and reads as an exclusion), "term" for any other, null when none did. A row both
1970
+ // hide is charged to the kind chip, the control the reader can see. This
1971
+ // is the one call per judged row: matches() reaches it through excluded(), and the feed's
1972
+ // empty-state walk calls it directly for the verdict and the reason at once, so the walk-cost
1973
+ // tests count calls here.
1974
+ //
1975
+ // A field is read as an own property only: a term like constructor:x or __proto__:y names
1976
+ // something every object inherits, and must hide nothing.
1977
+ excludeReason(ev) {
1978
+ const ex = this.excludeTerms();
1979
+ if (!ex.length)
1980
+ return null;
1981
+ let hay = null;
1982
+ let reason = null;
1983
+ for (const t of ex) {
1984
+ if ("field" in t) {
1985
+ const have = Object.hasOwn(ev, t.field) ? ev[t.field] : undefined;
1986
+ if (have == null || String(have).toLowerCase() !== t.value)
1987
+ continue;
1988
+ if (t.field === "kind" && SWITCHBOARD_KINDS.includes(t.value))
1989
+ return "kind";
1990
+ reason = "term";
1991
+ }
1992
+ else if (reason === null) {
1993
+ if (hay === null)
1994
+ hay = searchText(ev);
1995
+ if (hay.includes(t.text))
1996
+ reason = "term";
1997
+ }
1998
+ }
1999
+ return reason;
2000
+ }
2001
+ // The `match` part of matches() on its own: what the view IS about, before the level, the
2002
+ // exclusions and the filter box decide what to show of it. The feed's empty state uses it to
2003
+ // tell "no rows for this view yet" from "rows here, all hidden".
2004
+ passesMatch(ev) {
1295
2005
  const m = this.spec.match;
1296
2006
  if (!m)
1297
2007
  return true;
@@ -1300,9 +2010,35 @@ class Store {
1300
2010
  // network/rtm/clog (they have no package, already come from the app).
1301
2011
  if (k === "package" && ev._type && ev._type !== "log")
1302
2012
  return true;
2013
+ // A switchboard session_id is a number the device mints in order, so a substring match on it
2014
+ // would let "1" pass session 12; when the filter is a whole number and the row's id reads as
2015
+ // one, equality is the test. Gated on the source like the package rule above: another source's
2016
+ // session_id field (or a filter that is not a bare number) keeps the substring rule.
2017
+ if (k === "session_id" && ev._type === "switchboard" && /^\s*\d+\s*$/.test(String(v))) {
2018
+ const have = Number(ev.session_id);
2019
+ if (ev.session_id != null && Number.isFinite(have))
2020
+ return have === Number(v);
2021
+ }
1303
2022
  return String(ev[k] ?? "").toLowerCase().includes(String(v).toLowerCase());
1304
2023
  });
1305
2024
  }
2025
+ // The spec's exclude terms, parsed and lowercased once per list rather than once per row. Keyed
2026
+ // once per spec in applySpec (rekeyExclude), which also covers a list edited in place before the
2027
+ // spec is re-applied; matches() then only compares the array's identity, so the per-row cost is
2028
+ // a pointer check. A caller that assigns store.spec directly (tests do) swaps the array, and the
2029
+ // identity miss re-keys on that first use.
2030
+ _excludeArr = undefined;
2031
+ _excludeParsed = [];
2032
+ rekeyExclude() {
2033
+ const ex = this.spec.exclude;
2034
+ this._excludeArr = ex;
2035
+ this._excludeParsed = Array.isArray(ex) ? ex.map((t) => parseExcludeTerm(String(t))) : [];
2036
+ }
2037
+ excludeTerms() {
2038
+ if (this.spec.exclude !== this._excludeArr)
2039
+ this.rekeyExclude();
2040
+ return this._excludeParsed;
2041
+ }
1306
2042
  breaches(ev) {
1307
2043
  const h = this.spec.highlight;
1308
2044
  if (!h)
@@ -1344,6 +2080,7 @@ class Store {
1344
2080
  // baseline through the device-list refresh AFTER the error was written, so the error is
1345
2081
  // about the device just pinned and must survive the edge it caused.
1346
2082
  this.clearEnableError();
2083
+ this.setRefusal(null);
1347
2084
  }
1348
2085
  this._lastSerial = serial;
1349
2086
  // The DB tab, unlike the feed, DOES carry stale state across a first pin: it loaded unpinned
@@ -1389,13 +2126,41 @@ class Store {
1389
2126
  this.screenCaps = raw;
1390
2127
  this.emit("screen-caps", this.screenCaps);
1391
2128
  }
2129
+ updatePlatform(raw, rawLogPackage) {
2130
+ if (typeof raw !== "string" || !raw)
2131
+ return;
2132
+ const previous = this.platform;
2133
+ const previousLogPackage = this.logPackage;
2134
+ const nextLogPackage = typeof rawLogPackage === "string" && rawLogPackage
2135
+ ? rawLogPackage
2136
+ : previousLogPackage;
2137
+ if (raw === previous && nextLogPackage === previousLogPackage)
2138
+ return;
2139
+ // Computed even on the first platform read: when start()'s /health loses its race,
2140
+ // bootDefault() has already applied the Android preset, and that spec still needs the
2141
+ // swap. A blank spec (the normal first read) maps to null and falls through below.
2142
+ const key = this.customActive ? "__custom__" : specMatchesMode(this.spec, previousLogPackage);
2143
+ this.platform = raw;
2144
+ this.logPackage = nextLogPackage;
2145
+ if (key !== "all" && key !== "log")
2146
+ return;
2147
+ const mode = MODES.find((candidate) => candidate.key === key);
2148
+ if (!mode)
2149
+ return;
2150
+ const next = specForTab(this.presetSpec(mode.spec), this.spec, this.lastLogLevel, this.viewMemory, this.logPackage);
2151
+ if (JSON.stringify(next) === JSON.stringify(this.spec))
2152
+ return;
2153
+ this.applySpec(next);
2154
+ void this.setSpec(next, { local: true });
2155
+ }
1392
2156
  async pollHealth() {
1393
2157
  // The auto-re-arm cadence rides this existing 2s tick instead of owning a timer: every
1394
2158
  // guard lives inside maybeAutoRearm, so this line is a no-op except mid-outage on a
1395
2159
  // diagnosed dead session. Fire-and-forget so a multi-second /enable flight cannot delay
1396
2160
  // the health read below.
1397
2161
  void this.maybeAutoRearm();
1398
- if (this.connClock() - this._lastEventTs < 6000) {
2162
+ // Pre-refusal device frames do not prove the device still accepts us.
2163
+ if (this._refusalMsg === null && this.connClock() - this._lastEventTs < 6000) {
1399
2164
  this._healthMisses = 0;
1400
2165
  this.recovered();
1401
2166
  // Deliberately does NOT count connection proof. This path re-reads the SAME _lastEventTs every
@@ -1407,6 +2172,7 @@ class Store {
1407
2172
  }
1408
2173
  try {
1409
2174
  const h = await (await fetch("/health")).json();
2175
+ this.updatePlatform(h.platform, h.log_package);
1410
2176
  // Screen caps ride every /health reply and come from the platform controller, not from the
1411
2177
  // app ping the gate below reads, so they update outside that gate.
1412
2178
  this.updateScreenCaps(h.screen);
@@ -1419,8 +2185,18 @@ class Store {
1419
2185
  if (h.device === true) {
1420
2186
  this.onHealthDeviceUp(h.sources);
1421
2187
  }
2188
+ else if (h.unauthorized === true && typeof h.unauthorized_msg === "string") {
2189
+ this._healthMisses = 0;
2190
+ this.retireNoSession();
2191
+ this.setRefusal(h.unauthorized_msg);
2192
+ this.setConn("waiting", UNAUTHORIZED_HEAD);
2193
+ }
1422
2194
  else if (++this._healthMisses >= 2) {
1423
2195
  this._dropped = true;
2196
+ // Two replies without 401 end the refusal; one ping can time out. The server counts every
2197
+ // /health ping it answers and after two without a 401 wakes the refused stream on its own,
2198
+ // retracting the refusal on the wire first, so there is nothing to reopen here.
2199
+ this.setRefusal(null);
1424
2200
  this.setConn("waiting", "device offline, retrying…");
1425
2201
  }
1426
2202
  // Whether this dashboard process may arm the device on its own. Read on every health
@@ -1436,6 +2212,8 @@ class Store {
1436
2212
  catch {
1437
2213
  if (++this._healthMisses >= 2) {
1438
2214
  this._dropped = true;
2215
+ // Two failed reads put the problem at the dashboard, so the refusal no longer applies.
2216
+ this.setRefusal(null);
1439
2217
  this.setConn("waiting", "reconnecting…");
1440
2218
  }
1441
2219
  }
@@ -1503,6 +2281,8 @@ class Store {
1503
2281
  }).then((r) => r.json()).catch(() => null),
1504
2282
  ]);
1505
2283
  const uid = healthR && healthR.boundUserId;
2284
+ if (healthR)
2285
+ this.updatePlatform(healthR.platform, healthR.log_package);
1506
2286
  // pollHealth's fresh-frame fast path can skip its /health fetch indefinitely on a chatty
1507
2287
  // stream; this 5s poll already fetched /health, so a device:true here is handled by the SAME
1508
2288
  // helper pollHealth uses (sources, misses, recovery, proof, connected — and through the
@@ -1522,9 +2302,18 @@ class Store {
1522
2302
  // the first attempt would wait for a reply instead of firing on the diagnosis.
1523
2303
  if (healthR)
1524
2304
  this.noteSelfArmBlocked(healthR.self_arm_blocked, healthR.device === true);
1525
- this.profiles = (profilesR && profilesR.profiles) || [];
2305
+ const profileList = profilesR && Array.isArray(profilesR.profiles) ? profilesR.profiles : null;
2306
+ this.profiles = profileList || [];
1526
2307
  if (uid == null) {
1527
- this.profileLabel = this._lastBoundLabel ? "last seen " + this._lastBoundLabel + " — reconnecting…" : "waiting for device…";
2308
+ // Not every transport has Android-style user/work profiles. A successful empty profile
2309
+ // response means the concept is inapplicable; a failed response remains unknown and must
2310
+ // keep the existing waiting/reconnecting message rather than hiding a real Android issue.
2311
+ this.profileLabel =
2312
+ healthR?.device === true && profileList?.length === 0
2313
+ ? ""
2314
+ : this._lastBoundLabel
2315
+ ? "last seen " + this._lastBoundLabel + " — reconnecting…"
2316
+ : "waiting for device…";
1528
2317
  this.emit("profile", this.profileLabel);
1529
2318
  return;
1530
2319
  }
@@ -1638,14 +2427,17 @@ class Store {
1638
2427
  return;
1639
2428
  }
1640
2429
  // A successful pick clears any prior enable failure.
1641
- this.deviceError = null;
1642
- this.deviceErrorInstructs = false;
1643
- this.emit("device-error", null);
2430
+ this.clearDeviceError();
1644
2431
  this.emit("devices", this.devices);
1645
2432
  // The pick ARMED the device, which refutes any standing reconnect reason whatever the serial
1646
2433
  // did -- the same rule as a successful reconnect. Cleared here, inline, because advancing the
1647
2434
  // baseline below means checkSerialEdge sees no change and can never fire for this switch.
1648
2435
  this.clearEnableError();
2436
+ this.setRefusal(null);
2437
+ // The head wording an armed Reconnect uses while the stream has not spoken yet. Only the
2438
+ // message changes; "connected" stays the wire's claim to make.
2439
+ if (this.conn.state !== "connected")
2440
+ this.setConn(this.conn.state, "re-enabled, reconnecting the stream…");
1649
2441
  // The baseline tracks what the SERVER confirmed: the reply echo when present, the requested
1650
2442
  // serial only as the fallback for a reply without one. Same policy as reconnect's advance.
1651
2443
  const bound = confirmed ?? serial;
@@ -1931,6 +2723,7 @@ class Store {
1931
2723
  // Deliberately NOT setConn("connected"): the stream has its own reconnect to do, and
1932
2724
  // only an observation of the WIRE may claim "live".
1933
2725
  this.refuteSessionEnded();
2726
+ this.setRefusal(null);
1934
2727
  // With sessionEnded retired, the header falls back to conn.msg verbatim — which is
1935
2728
  // still the outage diagnosis this reply just refuted. Replace the MESSAGE only, never
1936
2729
  // the state: "connected" stays the wire's claim to make. Worded as the recovery step it
@@ -2047,6 +2840,8 @@ export function describeConstraints(spec) {
2047
2840
  parts.push('body contains "' + spec.bodyContains + '"');
2048
2841
  if (typeof spec.minLevel === "string" && spec.minLevel)
2049
2842
  parts.push("level ≥ " + spec.minLevel);
2843
+ if (Array.isArray(spec.exclude) && spec.exclude.length)
2844
+ parts.push("excluding " + spec.exclude.map((t) => '"' + t + '"').join(", "));
2050
2845
  if (spec.highlight && spec.highlight.field)
2051
2846
  parts.push("flag " + spec.highlight.field + " " + (spec.highlight.op || ">") + " " + spec.highlight.value + (spec.highlight.label ? " (" + spec.highlight.label + ")" : ""));
2052
2847
  if (Array.isArray(spec.series) && spec.series.length)
@@ -2059,6 +2854,89 @@ export function describeConstraints(spec) {
2059
2854
  parts.push("rate window " + spec.rateWindowSec + "s");
2060
2855
  return parts.join(" · ");
2061
2856
  }
2857
+ // True when two specs are the same view apart from their exclude lists: every other field is
2858
+ // deep-equal (key order included; the controls build the next spec from a copy of the last, so
2859
+ // the order holds). A blank spec is never the same view as a stream one.
2860
+ export function differsOnlyInExclude(a, b) {
2861
+ if (!a || !b || a.blank || b.blank)
2862
+ return false;
2863
+ const strip = (s) => {
2864
+ const c = { ...s };
2865
+ delete c.exclude;
2866
+ return JSON.stringify(c);
2867
+ };
2868
+ return strip(a) === strip(b);
2869
+ }
2870
+ // A plain term shaped like a field term with a space after the colon (`kind: frame`). It is legal
2871
+ // and is kept as a substring term, but it hides nothing a field term would, so the exclude inputs
2872
+ // say why (gappedFieldHint in filters.ts) while still taking it. `seen` says whether a row of the
2873
+ // tab has carried the field; with one, the hint is only for such a name (kind on Switchboard), and
2874
+ // prose such as `Error: timeout` on Logs is a plain term meant as one, and draws none. Handed in
2875
+ // rather than read off the singleton, so the answer is the caller's store's.
2876
+ export function isGappedFieldTerm(term, seen) {
2877
+ const m = /^([a-z_][a-z0-9_]*):\s+\S/i.exec(term.trim());
2878
+ if (!m)
2879
+ return false;
2880
+ return seen === undefined || seen(m[1].toLowerCase());
2881
+ }
2882
+ // The exclude grammar. `kind:frame` hides rows whose `kind` is exactly "frame"; `frame` alone
2883
+ // hides any row whose summary text contains it (a state change whose cause mentions a frame
2884
+ // goes too). The field is a bare identifier and the value follows the colon with no gap, so
2885
+ // `12:30`, `: x`, `a b:c` and log prose like `Error: timeout` (a term people already save) stay
2886
+ // plain text, and a value opening with `//` is a URL's authority, so `http://x` stays plain too.
2887
+ // A qualified term never falls back to a substring. Both halves are lowercased here, once per spec.
2888
+ export function parseExcludeTerm(term) {
2889
+ const m = /^([a-z_][a-z0-9_]*):(\S.*)$/i.exec(term.trim());
2890
+ if (m) {
2891
+ const value = m[2].trim();
2892
+ if (!value.startsWith("//"))
2893
+ return { field: m[1].toLowerCase(), value: value.toLowerCase() };
2894
+ }
2895
+ return { text: term.toLowerCase() };
2896
+ }
2897
+ // One searchable string per frame for the text filter AND for a spec's `exclude` terms (the
2898
+ // store's matches reads it too, so the two cannot drift onto different haystacks). The row KIND is
2899
+ // deliberately NOT part of this string: a kind token would make "-log" silently exclude clogs
2900
+ // (log ⊂ clog). Kind matching happens by EQUALITY via the filter predicate's second argument
2901
+ // instead (see filterKind in feed.ts).
2902
+ export function searchText(ev) {
2903
+ if ((ev._type || "") === "log")
2904
+ return [ev.level, ev.package, ev.tag, ev.message].filter(Boolean).join(" ").toLowerCase();
2905
+ if ((ev._type || "") === "trace")
2906
+ return [ev.trace_name, ev.span_name].filter(Boolean).join(" ").toLowerCase();
2907
+ if ((ev._type || "") === "switchboard")
2908
+ return [...switchboardFields(ev), ev.session_id].filter((x) => x != null && x !== "").join(" ").toLowerCase();
2909
+ return [ev.direction, ev.method, ev.event_type, ev.event_name, shortUrl(ev.url), ev.channel].filter(Boolean).join(" ").toLowerCase();
2910
+ }
2911
+ // A switchboard record's kind followed by that kind's key fields, in a fixed order, e.g.
2912
+ // ["frame", "incoming", "tts.state", 120], ["state", "connection", "Connecting", "Connected"],
2913
+ // ["phase", "socket", 412], ["player", "rearm", 38, 4096], ["session", "begin"],
2914
+ // ["turn", "no_card", 1840], ["saved_turn", "missing_field", "dropped: missing field"]. This list is the
2915
+ // search haystack; the row summary (feed.ts switchboardSummary) reads the same fields by name, and
2916
+ // a test holds the two together. The record's `id` is deliberately not searchable, as for the other kinds.
2917
+ export function switchboardFields(ev) {
2918
+ const kind = ev.kind || "";
2919
+ const num = (v) => (typeof v === "number" ? v : undefined);
2920
+ switch (kind) {
2921
+ // Searchable here like any other switchboard field, not just shown on the summary pill.
2922
+ case "session": return [kind, ev.event, ev.server_session_id];
2923
+ case "state": return [kind, ev.state_kind, ev.from, ev.to, ev.cause];
2924
+ case "frame": return [kind, ev.direction, ev.frame_type, num(ev.bytes)];
2925
+ case "phase": return [kind, ev.phase, num(ev.duration_ms)];
2926
+ case "player": return [kind, ev.event, num(ev.gap_ms), num(ev.bytes_queued)];
2927
+ case "levels": return [kind, num(ev.sample_count)];
2928
+ // The raw clock token, not the row's words, the same way a frame keeps "unknown".
2929
+ case "turn": return [kind, ev.clock, num(ev.response_ms)];
2930
+ // The raw outcome token too, then the row's words ("dropped: missing field", "saved (line
2931
+ // moved on), thread") so a search for what the row says finds it; an unknown outcome's words
2932
+ // are its token, quoted when it collides with a label word.
2933
+ case "saved_turn": {
2934
+ const label = savedTurnLabel(ev.outcome, ev.has_thread);
2935
+ return [kind, ev.outcome, label && label !== ev.outcome ? label : undefined];
2936
+ }
2937
+ default: return [kind];
2938
+ }
2939
+ }
2062
2940
  export function shortUrl(u) {
2063
2941
  try {
2064
2942
  return new URL(String(u)).pathname.replace("/api/", "");