@slack/radar-mcp 1.19.0 → 1.21.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 (44) hide show
  1. package/README.md +48 -8
  2. package/dist/mcp/api-paths.d.ts +11 -0
  3. package/dist/mcp/api-paths.js +67 -16
  4. package/dist/mcp/index.js +24 -7
  5. package/dist/mcp/network-detail.d.ts +5 -0
  6. package/dist/mcp/network-detail.js +86 -0
  7. package/dist/mcp/radar-response.d.ts +7 -0
  8. package/dist/mcp/radar-response.js +15 -0
  9. package/dist/mcp/session-backfill.d.ts +9 -3
  10. package/dist/mcp/session-backfill.js +77 -17
  11. package/dist/mcp/session-detail.js +54 -2
  12. package/dist/mcp/session-query.js +53 -11
  13. package/dist/mcp/sources-gate.js +4 -0
  14. package/dist/mcp/switchboard-tools.d.ts +9 -0
  15. package/dist/mcp/switchboard-tools.js +40 -0
  16. package/dist/mcp/tools.js +69 -18
  17. package/dist/shared/constants.d.ts +14 -3
  18. package/dist/shared/constants.js +14 -3
  19. package/dist/shared/event-spool.js +3 -2
  20. package/dist/shared/form-body.d.ts +18 -0
  21. package/dist/shared/form-body.js +251 -0
  22. package/dist/shared/stream.d.ts +1 -1
  23. package/dist/shared/switchboard.d.ts +9 -0
  24. package/dist/shared/switchboard.js +54 -0
  25. package/dist/shared/wire.d.ts +32 -0
  26. package/dist/web/install-app.d.ts +64 -1
  27. package/dist/web/install-app.js +174 -24
  28. package/dist/web/macapp/RadarApp.swift +1287 -71
  29. package/dist/web/public/index.html +216 -11
  30. package/dist/web/public/next/app.js +22 -12
  31. package/dist/web/public/next/db.js +180 -18
  32. package/dist/web/public/next/feed.js +571 -53
  33. package/dist/web/public/next/filters.js +160 -34
  34. package/dist/web/public/next/form-body.js +252 -0
  35. package/dist/web/public/next/inspector.js +103 -12
  36. package/dist/web/public/next/registry.js +33 -3
  37. package/dist/web/public/next/store.js +577 -53
  38. package/dist/web/public/next/voice-model.js +532 -0
  39. package/dist/web/public/next/voice.js +397 -0
  40. package/dist/web/server.d.ts +110 -6
  41. package/dist/web/server.js +436 -40
  42. package/dist/web/spec.d.ts +13 -6
  43. package/dist/web/spec.js +89 -6
  44. package/package.json +3 -3
@@ -1,4 +1,4 @@
1
- import { STREAM_KINDS, DEVICE_STREAM_KINDS, EAGER_CAPTURE_KINDS, isStateSource } 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 } from "./registry.js";
2
2
  // Logcat-scale retention. At the live firehose (~400+ events/sec on the unified Live tab) a
3
3
  // small ring recycles in seconds, so a rare signal (a once-per-5s heartbeat) gets evicted
4
4
  // before you can filter for it. Android Studio / Flipper keep the whole session and filter
@@ -6,10 +6,9 @@ import { STREAM_KINDS, DEVICE_STREAM_KINDS, EAGER_CAPTURE_KINDS, isStateSource }
6
6
  // 100k events ~ a few minutes of the full firehose, or hours of any single low-rate tag. The
7
7
  // cost is heap (bounded, ~tens of MB) + a full-buffer filter pass, which is why the feed only
8
8
  // 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.
9
+ // (CACHE_TTL_MS, in registry.ts so voice-model.ts can read it without the store) is the
10
+ // secondary bound for a quiet session.
11
11
  const CACHE_CAP = 100000;
12
- const CACHE_TTL_MS = 60 * 60 * 1000;
13
12
  const EAGER_CAPTURE = new Set(EAGER_CAPTURE_KINDS); // sources whose detail is pre-fetched per frame
14
13
  const DETAIL_CACHE_CAP = 1500; // bounded full-detail cache (eager-captured + click-fetched)
15
14
  const CAPTURE_CONCURRENCY = 3; // max parallel background /detail fetches
@@ -32,21 +31,100 @@ function readAutoRearmSuppressed() {
32
31
  return false;
33
32
  }
34
33
  }
34
+ // Per-tab view options (the exclude chips), keyed by preset key and persisted like the
35
+ // auto-rearm choice. A preset tab click pushes the pristine
36
+ // MODES spec, which used to throw away the chips set on it; this is what specForTab reads to
37
+ // put them back. Custom specs never land here: they have no key to come back to.
38
+ const VIEW_MEMORY_KEY = "radar-view-memory";
39
+ // The server's caps on `exclude` are applied again on read, so a stored list the server would
40
+ // refuse never rides onto a tab click and leaves the tab unclickable.
41
+ // A stored exclude list, cut to what the server accepts: strings only, trimmed, empties and
42
+ // over-long terms dropped, deduplicated case-insensitively (first spelling kept), at most 20.
43
+ // Undefined when nothing valid remains.
44
+ function clampExclude(list) {
45
+ if (!Array.isArray(list))
46
+ return undefined;
47
+ const seen = new Set();
48
+ const out = [];
49
+ for (const t of list) {
50
+ if (typeof t !== "string")
51
+ continue;
52
+ const term = t.trim();
53
+ if (!term || term.length > EXCLUDE_MAX_TERM_LENGTH || /[,\n]/.test(term) || seen.has(term.toLowerCase()))
54
+ continue;
55
+ seen.add(term.toLowerCase());
56
+ out.push(term);
57
+ if (out.length === EXCLUDE_MAX_TERMS)
58
+ break;
59
+ }
60
+ return out.length ? out : undefined;
61
+ }
62
+ // The stored map, or null when there is no storage to read (private mode, tests without a
63
+ // localStorage): the caller keeps its own copy then, instead of taking "unreadable" for "empty".
64
+ function readStoredViewMemory() {
65
+ try {
66
+ const raw = localStorage.getItem(VIEW_MEMORY_KEY);
67
+ if (!raw)
68
+ return {};
69
+ const parsed = JSON.parse(raw);
70
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
71
+ return {};
72
+ // Only the one field, only in its shape, only within the server's caps: a stale or
73
+ // hand-edited value must not smuggle an arbitrary field, or a refused list, onto a pushed spec.
74
+ const out = {};
75
+ for (const [k, v] of Object.entries(parsed)) {
76
+ if (!v || typeof v !== "object")
77
+ continue;
78
+ const e = v;
79
+ const entry = {};
80
+ const exclude = clampExclude(e.exclude);
81
+ if (exclude)
82
+ entry.exclude = exclude;
83
+ if (Object.keys(entry).length)
84
+ out[k] = entry;
85
+ }
86
+ return out;
87
+ }
88
+ catch {
89
+ return null;
90
+ }
91
+ }
92
+ function readViewMemory() {
93
+ return readStoredViewMemory() ?? {};
94
+ }
95
+ function writeViewMemory(mem) {
96
+ try {
97
+ if (Object.keys(mem).length)
98
+ localStorage.setItem(VIEW_MEMORY_KEY, JSON.stringify(mem));
99
+ else
100
+ localStorage.removeItem(VIEW_MEMORY_KEY);
101
+ }
102
+ catch {
103
+ /* private mode: the memory lasts for this tab only */
104
+ }
105
+ }
35
106
  const POLL_PROFILE_MS = 5000;
36
107
  const GRAPH_N = 60;
37
108
  const PERSEC_N = 30;
38
- const SUGGEST_FIELDS = ["event_type", "event_name", "tag", "status_code", "channel", "url", "package", "trace_name", "span_name"];
109
+ const SUGGEST_FIELDS = ["event_type", "event_name", "tag", "status_code", "channel", "url", "package", "trace_name", "span_name", "kind", "frame_type", "state_kind", "phase", "event"];
39
110
  const PACKAGE_CAP = 1000; // package values learned off the stream; bounded (was Infinity in the PoC, B4)
40
111
  // ---- pre-built dashboards: one tab each. Presets carry only generic placeholders; real
41
112
  // endpoints/channels/event-names are learned LIVE from the device stream. The one baked value
42
113
  // is com.Slack.internal.debug (the debug build's package), which is already public. ----
43
114
  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" } } },
115
+ { key: "all", label: "Live", spec: { title: "Live", summary: "Live: network, RTM, analytics clogs, traces, Slack-app logcat 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
116
  { 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
117
  { key: "rtm", label: "RTM", spec: { title: "RTM", summary: "Real-time websocket events as they happen.", source: "rtm", viz: ["rate", "feed", "inspector"] } },
47
118
  { 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
119
  { 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
120
  { 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" } } },
121
+ // The voice transport's own records (not logcat): session begin/end, connection, mic and speaking
122
+ // state changes, every websocket frame with its direction and size, phase timings, player re-arms and
123
+ // stalls. Events only for now; a waveform view comes later. No level here: the records
124
+ // carry no logcat priority, so like network/rtm/clog/trace the level selector does not apply and
125
+ // passesLevel lets every row through (the same carve-out the Live timeline gives those kinds).
126
+ // Noise is hidden with the filter box or an exclude chip, on the kind or the frame type.
127
+ { 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
128
  { key: "db", label: "Database", spec: { title: "Device DB", summary: "Browse the on-device SQLite databases (read-only snapshot).", source: "db" } },
51
129
  { key: "prefs", label: "Preferences", spec: { title: "Device Preferences", summary: "Browse the on-device SharedPreferences (including feature-flag overrides), read-only.", source: "prefs" } },
52
130
  { 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" } },
@@ -61,6 +139,9 @@ export const MODE_SOURCE = {
61
139
  clog: "clogs",
62
140
  trace: "traces",
63
141
  flags: "feature_flags",
142
+ // The voice transport plugin declares itself under its own name (kind stream), so a build
143
+ // without it hides the tab instead of showing an empty feed that can never fill.
144
+ switchboard: "switchboard",
64
145
  };
65
146
  // True when the device serves this mode's source. Old builds declare nothing
66
147
  // (sources null) and keep every tab.
@@ -96,17 +177,76 @@ function canonicalSpecKey(spec) {
96
177
  const cleaned = { ...spec };
97
178
  delete cleaned.title;
98
179
  delete cleaned.summary;
180
+ // A level floor is a way of looking at the same tab, not a different tab: the Logs button
181
+ // stays lit at "level ≥ WARN". `match.package` is deliberately still part of the key, so the app
182
+ // selector next to it does move you off the preset; the two controls are not meant to agree.
183
+ delete cleaned.minLevel;
184
+ // Exclusions are a view option too, the same kind of thing as the level: hiding a noisy line
185
+ // on Logs is still looking at Logs. So the tab stays lit with exclude chips on, and removing a
186
+ // chip does not flip it to Custom. (`match` stays in the key: it is what a preset IS, not how
187
+ // it is being looked at.)
188
+ delete cleaned.exclude;
99
189
  if (Array.isArray(cleaned.viz))
100
190
  cleaned.viz = cleaned.viz.filter((x) => x !== "counter");
101
191
  return JSON.stringify(norm(cleaned));
102
192
  }
193
+ // The spec a PRESET tab pushes. The level floor follows the person between the two tabs that
194
+ // have log rows, and waits out a visit to any other tab (`remembered` is the store's last level
195
+ // on a log-carrying tab), the way the text filter survives every tab switch. It never overrides
196
+ // a level the target already carries, so an agent-authored view keeps its own; the Custom button
197
+ // does not come through here at all.
198
+ //
199
+ // Then the tab's own memory (`memory`, the store's viewMemory unless a caller says otherwise): a
200
+ // preset with a remembered exclude list gets it back. That never overrides a field the target
201
+ // already carries, so an agent-authored spec that resolves to a preset still pushes exactly what
202
+ // the agent wrote.
203
+ export function specForTab(next, current, remembered = "", memory = store.viewMemory) {
204
+ const logish = (s) => s === "log" || s === "all";
205
+ let out = next;
206
+ if (logish(next.source) && next.minLevel === undefined) {
207
+ const min = current && logish(current.source)
208
+ ? (typeof current.minLevel === "string" ? current.minLevel : "")
209
+ : remembered;
210
+ if (min)
211
+ out = { ...next, minLevel: min };
212
+ }
213
+ const key = specMatchesMode(next);
214
+ const mem = key ? memory[key] : undefined;
215
+ if (!mem)
216
+ return out;
217
+ if (mem.exclude && next.exclude === undefined)
218
+ out = { ...out, exclude: [...mem.exclude] };
219
+ return out;
220
+ }
103
221
  export function specMatchesMode(spec) {
104
222
  if (!spec || spec.blank)
105
223
  return null;
106
224
  const key = canonicalSpecKey(spec);
107
225
  return MODES.find((m) => canonicalSpecKey(m.spec) === key)?.key ?? null;
108
226
  }
109
- class Store {
227
+ /**
228
+ * This page's presence id, taken from the URL when whoever opened the page supplied one.
229
+ *
230
+ * The dock app supplies one. It has to know this page's id before the page exists, because the
231
+ * question it asks the server is "is anyone other than my own window using this dashboard", and a page
232
+ * that mints its own id in here leaves the app no way to name it. A plain browser tab arrives with no
233
+ * parameter and mints its own, exactly as every tab did before.
234
+ *
235
+ * `presence`, not `tab`, because the dashboard's own tabs (Live, Network, Clogs) are the other thing
236
+ * `?tab=` would read as, and this is not one of those.
237
+ *
238
+ * Exported so a test can drive the URL branch without a browser.
239
+ */
240
+ export function pageTabId(search) {
241
+ const query = search ?? (typeof location !== "undefined" ? location.search : "");
242
+ const supplied = new URLSearchParams(query).get("presence");
243
+ if (supplied)
244
+ return supplied;
245
+ return typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : String(Math.random()).slice(2);
246
+ }
247
+ // Exported for the one test that needs a second instance (a simulated reload reading the same
248
+ // storage); the page uses the singleton `store` below.
249
+ export class Store {
110
250
  spec = { blank: true, viz: [] };
111
251
  conn = { state: "waiting", msg: "connecting…" };
112
252
  // Last self-heal check's outcome, fetched once at boot (see fetchSelfHeal). null until that
@@ -239,9 +379,13 @@ class Store {
239
379
  // honour it too — otherwise the tab that pressed stop renders "off" while the tab next to it
240
380
  // keeps arming the device, and the control's whole purpose (make the arming stop) fails.
241
381
  // `storage` fires only in the OTHER tabs, which is exactly the gap the writer cannot cover.
242
- watchSuppressionAcrossTabs() {
382
+ watchStorageAcrossTabs() {
243
383
  try {
244
384
  window.addEventListener("storage", (e) => {
385
+ // The view memory is per browser origin too: a chip set in the window next door is
386
+ // this window's memory as well, and its next tab click must read it.
387
+ if (e.key === null || e.key === VIEW_MEMORY_KEY)
388
+ this.viewMemory = readStoredViewMemory() ?? this.viewMemory;
245
389
  if (e.key !== null && e.key !== AUTO_REARM_OFF_KEY)
246
390
  return;
247
391
  const next = readAutoRearmSuppressed();
@@ -393,6 +537,11 @@ class Store {
393
537
  liveMatches = 0;
394
538
  graph = null;
395
539
  feedVersion = 0;
540
+ // Field names seen with a non-null value, per record type, for the whole session (an eviction
541
+ // does not unmark). Answers the chips' "does any row of this tab carry this field" in O(1)
542
+ // rather than a walk over the cache on every feed bump; "fields" is emitted only when a name
543
+ // is new, so a subscriber pays nothing for the stream's ordinary rows.
544
+ _fieldsSeen = new Map();
396
545
  // Bumped on every observed serial change (first pin included), emitted as "db-resync". The DB
397
546
  // tab keys its remount off this so it drops stale picked-db/table/results and re-fetches /dbs
398
547
  // when the bound device changes — including the null->serial FIRST pin, where the tab loaded
@@ -400,6 +549,14 @@ class Store {
400
549
  dbSerialVersion = 0;
401
550
  customActive = false;
402
551
  lastCustomSpec = null;
552
+ // The level floor last seen on a log-carrying tab ("" when none), so a trip through Network
553
+ // and back to Logs lands on the same level. Read by specForTab. Any log-carrying spec counts,
554
+ // an agent-authored one included: a log view Claude pushes with no level is the last level seen.
555
+ lastLogLevel = "";
556
+ // What each preset tab was last looked at through (see VIEW_MEMORY_KEY). Loaded once here, at
557
+ // construction, so it is in place before the first spec push of the page; written by applySpec
558
+ // on every preset spec this page authored, read by specForTab on every preset push.
559
+ viewMemory = readViewMemory();
403
560
  detailCache = new Map();
404
561
  _capSeen = new Set();
405
562
  _capQueue = [];
@@ -411,6 +568,9 @@ class Store {
411
568
  _healthMisses = 0;
412
569
  _specKey = "";
413
570
  _localPushKey = null;
571
+ // Bumped when a push is applied at ack time (see setSpec), so a /spec GET that was already in
572
+ // flight when the ack landed is dropped rather than applied over the newer spec.
573
+ _specGen = 0;
414
574
  _lastBoundLabel = null;
415
575
  _backfillToken = 0;
416
576
  // True while the connection is in a dropped/waiting state. Lets pollHealth detect the
@@ -430,23 +590,43 @@ class Store {
430
590
  // and reads as a genuine new frame to a paused/frozen feed subscriber.
431
591
  _rafHandle = null;
432
592
  _intervals = [];
433
- // Per-tab presence id, generated once when this Store is constructed. Rides pollProfile's 5s
593
+ // Per-tab presence id, settled once when this Store is constructed. Rides pollProfile's 5s
434
594
  // /health fetch (below) so the server can tell how many tabs are live and auto-close when the
435
- // last one is gone. In-memory only, never persisted: a page reload naturally gets a fresh id,
436
- // which is fine — the old id ages out of the server's presence map. Rides pollProfile, NOT
437
- // pollHealth: pollHealth early-returns without fetching while a stream is busy (<6s since the
438
- // last event), so a user actively watching a chatty stream would send zero presence signals.
439
- _tabId = typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : String(Math.random()).slice(2);
595
+ // last one is gone. In-memory only, never persisted. A reload of a page the dock app opened keeps
596
+ // the same id, because it comes from the URL; a reload of a plain browser tab gets a fresh one and
597
+ // the old id ages out of the server's presence map, which is what always happened. Rides
598
+ // pollProfile, NOT pollHealth: pollHealth early-returns without fetching while a stream is busy
599
+ // (<6s since the last event), so a user actively watching a chatty stream would send zero presence
600
+ // signals.
601
+ _tabId = pageTabId();
602
+ /**
603
+ * The headers an authored write carries: the proof the server's gate wants, plus which tab is
604
+ * writing.
605
+ *
606
+ * The pair has to travel together, and a method rather than four header literals is how that stays
607
+ * true. An authored write that proves it came from a dashboard but not WHICH one is credited to an
608
+ * agent session (see the server's creditAuthoredWrite), and a session claim is the one thing the
609
+ * dock app never overrides: it would refuse to replace a stale dashboard, and refuse to stop its own
610
+ * server on quit, because this window changed a filter.
611
+ *
612
+ * Sent on the writes the server CREDITS, which is /setspec and /enable. A db query or a screen
613
+ * consent buys no keep-alive, so it needs no identity.
614
+ */
615
+ authoredHeaders(extra = {}) {
616
+ return { "X-Radar-Dashboard": "1", "X-Radar-Tab": this._tabId, ...extra };
617
+ }
440
618
  // ---- shared detail cache (bounded FIFO) ----
441
- cacheDetail(kind, id, detail) {
442
- const key = kind + ":" + id;
619
+ // Keyed like the ring (frameKey): id plus timestamp, so after an app restart reuses an id the
620
+ // new record does not read the old process's body out of this cache.
621
+ cacheDetail(kind, ev, detail) {
622
+ const key = this.frameKey(kind, ev);
443
623
  this.detailCache.set(key, detail);
444
624
  while (this.detailCache.size > DETAIL_CACHE_CAP) {
445
625
  this.detailCache.delete(this.detailCache.keys().next().value);
446
626
  }
447
627
  }
448
- getDetail(kind, id) {
449
- return this.detailCache.get(kind + ":" + id);
628
+ getDetail(kind, ev) {
629
+ return this.detailCache.get(this.frameKey(kind, ev));
450
630
  }
451
631
  // ---- eager body capture (any EAGER_CAPTURE tab, while it is open) ----
452
632
  // The device ring evicts old records (network keeps 400), so a row clicked later is gone. While a
@@ -464,25 +644,25 @@ class Store {
464
644
  return;
465
645
  if (src !== "all" && src !== kind)
466
646
  return;
467
- const key = kind + ":" + ev.id;
647
+ const key = this.frameKey(kind, ev);
468
648
  if (this._capSeen.has(key) || this.detailCache.has(key))
469
649
  return;
470
650
  this._capSeen.add(key);
471
651
  if (this._capSeen.size > CAP_SEEN_CAP)
472
652
  this._capSeen.delete(this._capSeen.values().next().value);
473
- this._capQueue.push({ kind, id: ev.id });
653
+ this._capQueue.push({ kind, ev });
474
654
  this._drainCapture();
475
655
  }
476
656
  _drainCapture() {
477
657
  while (this._capInflight < CAPTURE_CONCURRENCY && this._capQueue.length) {
478
- const { kind, id } = this._capQueue.shift();
658
+ const { kind, ev } = this._capQueue.shift();
479
659
  this._capInflight++;
480
- fetch("/detail?kind=" + kind + "&id=" + id)
660
+ fetch("/detail?kind=" + kind + "&id=" + ev.id)
481
661
  .then((r) => r.json())
482
662
  .then((d) => {
483
663
  // skip the eviction error / empty; only cache a real payload
484
664
  if (d && !(d.error && d.url == null && d.method == null)) {
485
- this.cacheDetail(kind, id, { ...d, _type: kind });
665
+ this.cacheDetail(kind, ev, { ...d, _type: kind });
486
666
  }
487
667
  })
488
668
  .catch(() => { })
@@ -515,6 +695,8 @@ class Store {
515
695
  // them). Deliberately NOT reset: subscribers, live timers and stream handles (start() and
516
696
  // openStream() own those lifecycles), and _tabId, which identifies the page for its whole life.
517
697
  _resetForTest() {
698
+ this.lastLogLevel = "";
699
+ this.viewMemory = {};
518
700
  this.spec = { blank: true, viz: [] };
519
701
  this.conn = { state: "waiting", msg: "connecting…" };
520
702
  this.selfHeal = null;
@@ -561,6 +743,10 @@ class Store {
561
743
  this.liveMatches = 0;
562
744
  this.graph = null;
563
745
  this.feedVersion = 0;
746
+ this._fieldsSeen = new Map();
747
+ // A fresh chain, or a write a test left in flight would hold the next test's writes behind it.
748
+ this._writeChain = Promise.resolve();
749
+ this.setSpecTimeoutMs = 8000;
564
750
  this.dbSerialVersion = 0;
565
751
  this.customActive = false;
566
752
  this.lastCustomSpec = null;
@@ -572,6 +758,7 @@ class Store {
572
758
  this._healthMisses = 0;
573
759
  this._specKey = "";
574
760
  this._localPushKey = null;
761
+ this._specGen = 0;
575
762
  this._lastBoundLabel = null;
576
763
  this._backfillToken = 0;
577
764
  this._dropped = false;
@@ -613,10 +800,12 @@ class Store {
613
800
  if (scopeToSource !== undefined && scopeToSource !== "all") {
614
801
  this.cache = this.cache.filter((c) => c.type !== scopeToSource);
615
802
  this.cacheKeys = new Set(this.cache.map((c) => this.frameKey(c.type, c.ev)));
803
+ this._fieldsSeen.delete(scopeToSource);
616
804
  }
617
805
  else {
618
806
  this.cache = [];
619
807
  this.cacheKeys = new Set();
808
+ this._fieldsSeen = new Map();
620
809
  }
621
810
  this.seen = {};
622
811
  this.detailCache = new Map();
@@ -672,9 +861,10 @@ class Store {
672
861
  *
673
862
  * Emits "feed" synchronously rather than through bumpFeed's rAF batch. A clear is a direct
674
863
  * response to a click and must land on THIS frame; the batch exists to coalesce stream floods.
675
- * Note the feed's own "feed" handler is incremental (it diffs against store.cache.length, which
676
- * does not necessarily shrink to 0 -- other tabs' entries can remain) -- the caller re-snapshots
677
- * its view via viewFrames(), which filters by source and is what actually guarantees zero rows.
864
+ * Note the feed's own "feed" handler is incremental (it finds what is new by the cache entry
865
+ * that sat at its cursor; after a clear that entry is gone, so everything still held reads as
866
+ * new, and other tabs' entries can remain) -- the caller re-snapshots its view via
867
+ * viewFrames(), which filters by source and is what actually guarantees zero rows.
678
868
  */
679
869
  clearView() {
680
870
  this.clearRecords(this.spec.source || "all");
@@ -690,7 +880,7 @@ class Store {
690
880
  // local default bootDefault had just set and stranding the page on the blank placeholder
691
881
  // until the next 700ms tick happened to read the corrected value.
692
882
  await this.bootDefault();
693
- this.watchSuppressionAcrossTabs();
883
+ this.watchStorageAcrossTabs();
694
884
  this.fetchSelfHeal();
695
885
  this.fetchSetupHint();
696
886
  this.pollSpec();
@@ -790,6 +980,7 @@ class Store {
790
980
  }
791
981
  async pollSpec() {
792
982
  try {
983
+ const gen = this._specGen;
793
984
  const res = await fetch("/spec");
794
985
  // The server already stamps its version on /spec (the adopt-path check);
795
986
  // reuse it here so the header can show which Radar version is serving.
@@ -801,18 +992,14 @@ class Store {
801
992
  this.emit("version", ver);
802
993
  }
803
994
  const spec = await res.json();
995
+ // A push was acked while this GET was on the wire: what it read predates that push, and
996
+ // applying it would roll the page back until the next tick. The next poll reads the truth.
997
+ if (gen !== this._specGen)
998
+ return;
804
999
  const key = JSON.stringify(spec);
805
1000
  if (key === this._specKey)
806
1001
  return;
807
- this._specKey = key;
808
- const isLocalEdit = key === this._localPushKey;
809
- if (isLocalEdit)
810
- this._localPushKey = null;
811
- this.customActive = !isLocalEdit && !!spec && !spec.blank && specMatchesMode(spec) === null;
812
- if (this.customActive && (!this.lastCustomSpec || JSON.stringify(this.lastCustomSpec) !== key)) {
813
- this.lastCustomSpec = spec;
814
- }
815
- this.applySpec(spec);
1002
+ this.adopt(spec, key, key === this._localPushKey);
816
1003
  }
817
1004
  catch {
818
1005
  /* transient; next poll retries */
@@ -828,8 +1015,11 @@ class Store {
828
1015
  // takes, even though the intent is always to land on Live. start() awaits this method
829
1016
  // before its own first pollSpec() runs, so that later read confirms the same spec
830
1017
  // rather than racing this one and overwriting it back to blank.
831
- this.applySpec(MODES[0].spec);
832
- await fetch("/setspec", { method: "POST", headers: { "Content-Type": "application/json", "X-Radar-Dashboard": "1" }, body: JSON.stringify(MODES[0].spec) }).catch(() => { });
1018
+ // Through specForTab, as a Live tab click is: the pristine preset would drop the exclusions
1019
+ // this browser remembers for Live on every fresh server. viewMemory is read at construction.
1020
+ const spec = specForTab(MODES[0].spec, null, this.lastLogLevel, this.viewMemory);
1021
+ this.applySpec(spec, { local: true });
1022
+ await fetch("/setspec", { method: "POST", headers: this.authoredHeaders({ "Content-Type": "application/json" }), body: JSON.stringify(spec) }).catch(() => { });
833
1023
  }
834
1024
  }
835
1025
  catch {
@@ -870,26 +1060,133 @@ class Store {
870
1060
  markLocalPush(spec) {
871
1061
  this._localPushKey = JSON.stringify(spec);
872
1062
  }
873
- async setSpec(spec, opts = {}) {
1063
+ // Take `spec` as the current one. Shared by the poll (the server's spec changed under us, or
1064
+ // our own push echoed back) and by setSpec (our push was just acked). The key is set first so
1065
+ // the poll's later echo early-returns: one applySpec, one stream reconnect, memory written once.
1066
+ // `isLocalEdit` says this page authored the spec; only then does applySpec record the view.
1067
+ adopt(spec, key, isLocalEdit) {
1068
+ this._specKey = key;
1069
+ if (this._localPushKey === key)
1070
+ this._localPushKey = null;
1071
+ this.customActive = !isLocalEdit && !!spec && !spec.blank && specMatchesMode(spec) === null;
1072
+ if (this.customActive && (!this.lastCustomSpec || JSON.stringify(this.lastCustomSpec) !== key)) {
1073
+ this.lastCustomSpec = spec;
1074
+ }
1075
+ this.applySpec(spec, { local: isLocalEdit });
1076
+ }
1077
+ // Every local write goes through one chain: a link runs once the one before it has settled and
1078
+ // reads the spec the store holds at that moment (an accepted push is applied at ack time). Two
1079
+ // controls writing inside one round trip used to post two bodies off the same un-acked list, so
1080
+ // the second dropped the first's edit, and a queue kept in one component left the others racing
1081
+ // it. `fn` is handed that acked spec and returns the next one, or null to write nothing (the tab
1082
+ // it was pressed on is gone, the term is already on the list); a null resolves `skipped`.
1083
+ _writeChain = Promise.resolve();
1084
+ // How long one push may wait for the server before the chain moves on. A POST that never
1085
+ // answered used to hold every later write behind it for good. A field so a test can shorten it.
1086
+ setSpecTimeoutMs = 8000;
1087
+ updateSpec(fn, opts = {}) {
1088
+ const run = this._writeChain.then(() => {
1089
+ const next = fn(this.spec);
1090
+ if (next === null)
1091
+ return { ok: true, skipped: true };
1092
+ return this.postSpec(next, opts);
1093
+ });
1094
+ this._writeChain = run.catch(() => undefined);
1095
+ return run;
1096
+ }
1097
+ // Resolves on the server's answer, in the order the writes were made. An accepted spec is applied
1098
+ // at ack time, so every control (chips, level, app, Filters Apply, the exclude box) builds its
1099
+ // next edit on it at once rather than on a prop that lags until the poll brings the echo. A
1100
+ // refused or failed push applies nothing.
1101
+ setSpec(spec, opts = {}) {
1102
+ return this.updateSpec(() => spec, opts);
1103
+ }
1104
+ // A preset push (tab click, keyboard tab move, the device-switch reset) goes through specForTab
1105
+ // against the spec the store holds when the write's turn comes, not the one the click saw. Built
1106
+ // at click time, a Live click made while a Logs level change was in flight posted a body with no
1107
+ // level, and applySpec forgot the level with it.
1108
+ pushPreset(preset, opts = {}) {
1109
+ return this.updateSpec((base) => specForTab(preset, base, this.lastLogLevel, this.viewMemory), opts);
1110
+ }
1111
+ async postSpec(spec, opts) {
874
1112
  if (opts.local)
875
1113
  this.markLocalPush(spec);
1114
+ const key = JSON.stringify(spec);
1115
+ let r;
1116
+ const ctrl = new AbortController();
1117
+ let timedOut = false;
1118
+ const timer = setTimeout(() => { timedOut = true; ctrl.abort(); }, this.setSpecTimeoutMs);
876
1119
  try {
877
1120
  // X-Radar-Dashboard marks this as an authored write (see the server's handleSetSpec): it is
878
- // what lets the write count as a keep-alive, and a foreign origin cannot forge it.
879
- return await (await fetch("/setspec", { method: "POST", headers: { "Content-Type": "application/json", "X-Radar-Dashboard": "1" }, body: JSON.stringify(spec) })).json();
1121
+ // what lets the write count as a keep-alive, and a foreign origin cannot forge it. X-Radar-Tab
1122
+ // says the keep-alive is THIS window's rather than an agent session's. The race, not the
1123
+ // signal alone, bounds the wait: the signal ends a real request, the race ends the wait even
1124
+ // for a fetch that ignores it.
1125
+ r = await Promise.race([
1126
+ fetch("/setspec", { method: "POST", headers: this.authoredHeaders({ "Content-Type": "application/json" }), body: key, signal: ctrl.signal }).then((res) => res.json()),
1127
+ new Promise((_, reject) => ctrl.signal.addEventListener("abort", () => reject(new Error("timed out")), { once: true })),
1128
+ ]);
880
1129
  }
881
1130
  catch {
882
- return { ok: false, error: "request failed" };
1131
+ // The write may have landed and only the reply was lost, so the local-push key stays: if the
1132
+ // echo does arrive it is still this page's edit. The copy says so, or a chip that flips when
1133
+ // the poll brings that echo would look like it moved on its own.
1134
+ return { ok: false, error: timedOut ? "request timed out; the list follows the server when it answers" : "request failed" };
883
1135
  }
1136
+ finally {
1137
+ clearTimeout(timer);
1138
+ }
1139
+ if (r && r.ok) {
1140
+ // A push of the spec already in force (a click on the lit tab, an untouched Apply) changes
1141
+ // nothing, so it must not reopen the stream or zero the counters; the poll dedupes the same way.
1142
+ if (key !== this._specKey) {
1143
+ this._specGen++;
1144
+ this.adopt(spec, key, !!opts.local);
1145
+ }
1146
+ else if (this._localPushKey === key) {
1147
+ this._localPushKey = null;
1148
+ }
1149
+ }
1150
+ else if (r && this._localPushKey === key) {
1151
+ // Refused by the server: nothing was stored, so no echo can arrive for this key.
1152
+ this._localPushKey = null;
1153
+ }
1154
+ return r;
884
1155
  }
885
1156
  activeModeKey() {
886
1157
  return this.customActive ? "__custom__" : specMatchesMode(this.spec);
887
1158
  }
888
1159
  // Rebuild all derived state for a new spec, reconnect the stream (so the server
889
1160
  // attaches/detaches the host-side logcat session for log/all sources), replay the cache, and
890
- // backfill the device ring. Mirrors vanilla build(spec).
891
- applySpec(spec) {
1161
+ // backfill the device ring. Mirrors vanilla build(spec). `local` says this page authored the
1162
+ // spec (a chip, the level selector, Filters Apply): only then is a preset's view
1163
+ // remembered, so a spec an agent pushes neither reads the memory (specForTab) nor rewrites it.
1164
+ applySpec(spec, opts = {}) {
1165
+ const prev = this.spec;
892
1166
  this.spec = spec || { blank: true, viz: [] };
1167
+ this.rekeyExclude();
1168
+ if (this.spec.source === "log" || this.spec.source === "all") {
1169
+ this.lastLogLevel = typeof this.spec.minLevel === "string" ? this.spec.minLevel : "";
1170
+ }
1171
+ const modeKey = specMatchesMode(this.spec);
1172
+ if (modeKey && opts.local)
1173
+ this.rememberView(modeKey, this.spec);
1174
+ // A change to the exclude list alone (a kind chip pressed, a term typed or removed) is a view
1175
+ // filter over the cache the feed already holds: same source, same stream, same rows. So the
1176
+ // stream stays open and the backfill is not fetched again (a full rebuild here made every chip
1177
+ // press reconnect). The widgets are still recounted from the cache: hidden rows leave the rate,
1178
+ // sparkline and graph, as the contract says, so the aggregates are zeroed and replayed under
1179
+ // the new list. The "spec" emit is what makes the feed re-filter.
1180
+ if (differsOnlyInExclude(prev, this.spec)) {
1181
+ this.total = 0;
1182
+ this.liveMatches = 0;
1183
+ this.times = [];
1184
+ this.perSec = new Array(PERSEC_N).fill(0);
1185
+ this.graph = this.buildGraph();
1186
+ this.emit("spec", this.spec);
1187
+ this.replayCache();
1188
+ return;
1189
+ }
893
1190
  this.total = 0;
894
1191
  this.liveMatches = 0;
895
1192
  this.times = [];
@@ -914,6 +1211,27 @@ class Store {
914
1211
  this.replayCache();
915
1212
  this.backfill();
916
1213
  }
1214
+ // Record how a preset tab is being looked at: its exclude list. A list the spec no longer
1215
+ // carries leaves the entry (the last chip removed), so what is remembered is always the last
1216
+ // thing seen on the tab. The level is not kept here: Logs and Live share lastLogLevel for it.
1217
+ //
1218
+ // Read-modify-write on the stored map, touching only this key: two dashboard windows share
1219
+ // the storage, and a whole-map write from one would erase what the other remembered for its
1220
+ // tabs. Without storage the page's own copy is the map.
1221
+ rememberView(key, spec) {
1222
+ const mem = readStoredViewMemory() ?? this.viewMemory;
1223
+ const entry = { ...(mem[key] ?? {}) };
1224
+ if (Array.isArray(spec.exclude) && spec.exclude.length)
1225
+ entry.exclude = spec.exclude.map(String);
1226
+ else
1227
+ delete entry.exclude;
1228
+ if (Object.keys(entry).length)
1229
+ mem[key] = entry;
1230
+ else
1231
+ delete mem[key];
1232
+ this.viewMemory = mem;
1233
+ writeViewMemory(mem);
1234
+ }
917
1235
  // ---- stream ----
918
1236
  openStream() {
919
1237
  this.closeStream();
@@ -1009,7 +1327,17 @@ class Store {
1009
1327
  }
1010
1328
  // ---- CACHE ring (dedup + bounded by count and age) ----
1011
1329
  frameKey(type, ev) {
1012
- return type + ":" + (ev.id != null ? ev.id : (ev.log_ts || "") + "|" + (ev.pid || "") + "|" + (ev.message || ev.event_type || ev.event_name || ""));
1330
+ // Every kind the stream gate admits carries an id (the device kinds mint theirs per app
1331
+ // process, so the counter restarts with the process; logs get a host-minted one), and a tab
1332
+ // left open on the same device keeps its cache (TTL 1h, capped by count), so on id alone the next process's records
1333
+ // collide with cached keys and drop as duplicates. The timestamp rides along: a restart cannot
1334
+ // reuse both, while a backfilled record and its live twin carry the same device timestamp and
1335
+ // still share one key. A device record with no id (no shipped build sends one) keeps its
1336
+ // timestamp in the key so a whole backfill does not fold into one row; a log line with no id
1337
+ // falls to a content composite.
1338
+ if (ev.id != null || type !== "log")
1339
+ return type + ":" + (ev.id ?? "") + "|" + (ev.timestamp ?? "");
1340
+ return type + ":" + (ev.log_ts || "") + "|" + (ev.pid || "") + "|" + (ev.message || ev.event_type || ev.event_name || "");
1013
1341
  }
1014
1342
  cacheFrame(type, ev) {
1015
1343
  const k = this.frameKey(type, ev);
@@ -1018,9 +1346,44 @@ class Store {
1018
1346
  this.cacheKeys.add(k);
1019
1347
  this.cache.push({ type, ev, ts: ev.timestamp || Date.now() });
1020
1348
  this.observe(ev);
1349
+ this.noteFields(type, ev);
1021
1350
  this.evictCache();
1022
1351
  return true;
1023
1352
  }
1353
+ // True once a row of `source` ("all": of any type) has carried `field` with a non-null value this
1354
+ // session. A null is the device saying the field does not apply to this row, so it is not a
1355
+ // carrier: a term on it hides nothing until a row gives it a value.
1356
+ fieldSeen(source, field) {
1357
+ if (source === "all") {
1358
+ for (const set of this._fieldsSeen.values())
1359
+ if (set.has(field))
1360
+ return true;
1361
+ return false;
1362
+ }
1363
+ return this._fieldsSeen.get(source)?.has(field) ?? false;
1364
+ }
1365
+ // True once any row of `source` has been seen this session. With none there is no verdict to
1366
+ // give on a field.
1367
+ rowsSeen(source) {
1368
+ return source === "all" ? this._fieldsSeen.size > 0 : this._fieldsSeen.has(source);
1369
+ }
1370
+ noteFields(type, ev) {
1371
+ let set = this._fieldsSeen.get(type);
1372
+ let added = false;
1373
+ if (!set) {
1374
+ set = new Set();
1375
+ this._fieldsSeen.set(type, set);
1376
+ added = true;
1377
+ }
1378
+ for (const k in ev) {
1379
+ if (ev[k] == null || set.has(k))
1380
+ continue;
1381
+ set.add(k);
1382
+ added = true;
1383
+ }
1384
+ if (added)
1385
+ this.emit("fields", type);
1386
+ }
1024
1387
  evictCache() {
1025
1388
  const cutoff = Date.now() - CACHE_TTL_MS;
1026
1389
  const drop = () => {
@@ -1057,9 +1420,8 @@ class Store {
1057
1420
  }
1058
1421
  }
1059
1422
  candidates(field) {
1060
- const fixed = { direction: ["OUTGOING", "INCOMING"], level: ["VERBOSE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL"], method: ["GET", "POST", "PUT", "DELETE", "PATCH"] };
1061
- if (fixed[field])
1062
- return fixed[field].slice();
1423
+ if (FIELD_VALUES[field])
1424
+ return FIELD_VALUES[field].slice();
1063
1425
  const seen = this.seen[field];
1064
1426
  return seen ? [...seen].sort() : [];
1065
1427
  }
@@ -1222,6 +1584,67 @@ class Store {
1222
1584
  this.selectedDevice === null);
1223
1585
  }
1224
1586
  matches(ev) {
1587
+ if (!this.passesLevel(ev))
1588
+ return false;
1589
+ if (!this.passesMatch(ev))
1590
+ return false;
1591
+ // Last, so a row `match` already dropped never pays for building the haystack.
1592
+ return !this.excluded(ev);
1593
+ }
1594
+ // The level part of matches() on its own: the lowest priority to show. Only log rows carry one,
1595
+ // so on the "all" timeline network, rtm, clog and trace rows pass untouched, the same carve-out
1596
+ // `package` gets in passesMatch. A row whose priority the order does not know ranks -1 and is
1597
+ // hidden (see levelRank). The feed's empty state charges a hidden row to the floor before
1598
+ // anything else, so it needs this gate apart from the others.
1599
+ passesLevel(ev) {
1600
+ const min = this.spec.minLevel;
1601
+ return !(typeof min === "string" && min && ev._type === "log" && levelRank(ev.level) < levelRank(min));
1602
+ }
1603
+ // The exclude part of matches() on its own. A plain term reads the same haystack as the feed's
1604
+ // filter box (searchText), so a term typed there and a term carried by the spec hide exactly
1605
+ // the same rows; a field:value term tests one field for equality instead (parseExcludeTerm).
1606
+ // The terms are parsed and lowercased once per spec, on its first use (see excludeTerms).
1607
+ excluded(ev) {
1608
+ return this.excludeReason(ev) !== null;
1609
+ }
1610
+ // Which exclude term hid the row: "kind" for a kind:<name> term naming one of the Switchboard
1611
+ // tab's kind chips (they write those, so the empty line can name the chip; a pushed kind:mystery
1612
+ // has no chip and reads as an exclusion), "term" for any other, null when none did. A row both
1613
+ // hide is charged to the kind chip, the control the reader can see. This
1614
+ // is the one call per judged row: matches() reaches it through excluded(), and the feed's
1615
+ // empty-state walk calls it directly for the verdict and the reason at once, so the walk-cost
1616
+ // tests count calls here.
1617
+ //
1618
+ // A field is read as an own property only: a term like constructor:x or __proto__:y names
1619
+ // something every object inherits, and must hide nothing.
1620
+ excludeReason(ev) {
1621
+ const ex = this.excludeTerms();
1622
+ if (!ex.length)
1623
+ return null;
1624
+ let hay = null;
1625
+ let reason = null;
1626
+ for (const t of ex) {
1627
+ if ("field" in t) {
1628
+ const have = Object.hasOwn(ev, t.field) ? ev[t.field] : undefined;
1629
+ if (have == null || String(have).toLowerCase() !== t.value)
1630
+ continue;
1631
+ if (t.field === "kind" && SWITCHBOARD_KINDS.includes(t.value))
1632
+ return "kind";
1633
+ reason = "term";
1634
+ }
1635
+ else if (reason === null) {
1636
+ if (hay === null)
1637
+ hay = searchText(ev);
1638
+ if (hay.includes(t.text))
1639
+ reason = "term";
1640
+ }
1641
+ }
1642
+ return reason;
1643
+ }
1644
+ // The `match` part of matches() on its own: what the view IS about, before the level, the
1645
+ // exclusions and the filter box decide what to show of it. The feed's empty state uses it to
1646
+ // tell "no rows for this view yet" from "rows here, all hidden".
1647
+ passesMatch(ev) {
1225
1648
  const m = this.spec.match;
1226
1649
  if (!m)
1227
1650
  return true;
@@ -1230,9 +1653,35 @@ class Store {
1230
1653
  // network/rtm/clog (they have no package, already come from the app).
1231
1654
  if (k === "package" && ev._type && ev._type !== "log")
1232
1655
  return true;
1656
+ // A switchboard session_id is a number the device mints in order, so a substring match on it
1657
+ // would let "1" pass session 12; when the filter is a whole number and the row's id reads as
1658
+ // one, equality is the test. Gated on the source like the package rule above: another source's
1659
+ // session_id field (or a filter that is not a bare number) keeps the substring rule.
1660
+ if (k === "session_id" && ev._type === "switchboard" && /^\s*\d+\s*$/.test(String(v))) {
1661
+ const have = Number(ev.session_id);
1662
+ if (ev.session_id != null && Number.isFinite(have))
1663
+ return have === Number(v);
1664
+ }
1233
1665
  return String(ev[k] ?? "").toLowerCase().includes(String(v).toLowerCase());
1234
1666
  });
1235
1667
  }
1668
+ // The spec's exclude terms, parsed and lowercased once per list rather than once per row. Keyed
1669
+ // once per spec in applySpec (rekeyExclude), which also covers a list edited in place before the
1670
+ // spec is re-applied; matches() then only compares the array's identity, so the per-row cost is
1671
+ // a pointer check. A caller that assigns store.spec directly (tests do) swaps the array, and the
1672
+ // identity miss re-keys on that first use.
1673
+ _excludeArr = undefined;
1674
+ _excludeParsed = [];
1675
+ rekeyExclude() {
1676
+ const ex = this.spec.exclude;
1677
+ this._excludeArr = ex;
1678
+ this._excludeParsed = Array.isArray(ex) ? ex.map((t) => parseExcludeTerm(String(t))) : [];
1679
+ }
1680
+ excludeTerms() {
1681
+ if (this.spec.exclude !== this._excludeArr)
1682
+ this.rekeyExclude();
1683
+ return this._excludeParsed;
1684
+ }
1236
1685
  breaches(ev) {
1237
1686
  const h = this.spec.highlight;
1238
1687
  if (!h)
@@ -1498,9 +1947,9 @@ class Store {
1498
1947
  //
1499
1948
  // A reply that will not PARSE is a third case, and it must not be worded like the second. Not
1500
1949
  // being able to read the answer says nothing about the device, so it does not get to blame one.
1501
- // That is the repo's stated convention, in CLAUDE.md under the inconclusive-probe section: "A
1502
- // probe that cannot always tell must say so in its return type. Never collapse 'could not tell'
1503
- // into 'no'." So this reports the read failure, and the caller's device-blaming fallback is
1950
+ // A probe that cannot always tell says so in its return type, and "could not tell" never collapses
1951
+ // into "no"; every probe in RadarApp.swift follows the same rule. So this reports the read failure,
1952
+ // and the caller's device-blaming fallback is
1504
1953
  // reserved for a reply that parsed and simply carried no reason of its own.
1505
1954
  async readEnableResult(r, fallback) {
1506
1955
  const body = (await r.json().catch(() => null));
@@ -1537,7 +1986,7 @@ class Store {
1537
1986
  // device list is refreshed so the dropdown is current and the user can pick a valid device.
1538
1987
  async selectDevice(serial) {
1539
1988
  try {
1540
- const r = await fetch("/enable?device_serial=" + encodeURIComponent(serial), { method: "POST", headers: { "X-Radar-Dashboard": "1" } });
1989
+ const r = await fetch("/enable?device_serial=" + encodeURIComponent(serial), { method: "POST", headers: this.authoredHeaders() });
1541
1990
  // Any reply that did not arm the device takes the failure path, not just the 409. A 200 whose
1542
1991
  // body says enabled:false used to fall through here as a success: it cleared deviceError,
1543
1992
  // recorded the serial as switched-to, and resynced a stream against a device holding no
@@ -1840,7 +2289,7 @@ class Store {
1840
2289
  let replySwitched = false;
1841
2290
  let outcome;
1842
2291
  try {
1843
- const r = await fetch(auto ? "/enable?auto=1" : "/enable", { method: "POST", headers: { "X-Radar-Dashboard": "1" } });
2292
+ const r = await fetch(auto ? "/enable?auto=1" : "/enable", { method: "POST", headers: this.authoredHeaders() });
1844
2293
  const { enabled, error, instructs, serial, refusal } = await this.readEnableResult(r, "Reconnect failed. Is a device attached with a debug build of the Slack app running?");
1845
2294
  // The reply names the device this press pinned, and the route pins before it arms, so a
1846
2295
  // failing press can itself move the pin (first sight, or a switch to freshly attached
@@ -1975,6 +2424,10 @@ export function describeConstraints(spec) {
1975
2424
  parts.push("where " + Object.entries(spec.match).map(([k, v]) => k + "=" + v).join(", "));
1976
2425
  if (spec.bodyContains)
1977
2426
  parts.push('body contains "' + spec.bodyContains + '"');
2427
+ if (typeof spec.minLevel === "string" && spec.minLevel)
2428
+ parts.push("level ≥ " + spec.minLevel);
2429
+ if (Array.isArray(spec.exclude) && spec.exclude.length)
2430
+ parts.push("excluding " + spec.exclude.map((t) => '"' + t + '"').join(", "));
1978
2431
  if (spec.highlight && spec.highlight.field)
1979
2432
  parts.push("flag " + spec.highlight.field + " " + (spec.highlight.op || ">") + " " + spec.highlight.value + (spec.highlight.label ? " (" + spec.highlight.label + ")" : ""));
1980
2433
  if (Array.isArray(spec.series) && spec.series.length)
@@ -1987,6 +2440,77 @@ export function describeConstraints(spec) {
1987
2440
  parts.push("rate window " + spec.rateWindowSec + "s");
1988
2441
  return parts.join(" · ");
1989
2442
  }
2443
+ // True when two specs are the same view apart from their exclude lists: every other field is
2444
+ // deep-equal (key order included; the controls build the next spec from a copy of the last, so
2445
+ // the order holds). A blank spec is never the same view as a stream one.
2446
+ export function differsOnlyInExclude(a, b) {
2447
+ if (!a || !b || a.blank || b.blank)
2448
+ return false;
2449
+ const strip = (s) => {
2450
+ const c = { ...s };
2451
+ delete c.exclude;
2452
+ return JSON.stringify(c);
2453
+ };
2454
+ return strip(a) === strip(b);
2455
+ }
2456
+ // A plain term shaped like a field term with a space after the colon (`kind: frame`). It is legal
2457
+ // and is kept as a substring term, but it hides nothing a field term would, so the exclude inputs
2458
+ // say why (gappedFieldHint in filters.ts) while still taking it. `seen` says whether a row of the
2459
+ // tab has carried the field; with one, the hint is only for such a name (kind on Switchboard), and
2460
+ // prose such as `Error: timeout` on Logs is a plain term meant as one, and draws none. Handed in
2461
+ // rather than read off the singleton, so the answer is the caller's store's.
2462
+ export function isGappedFieldTerm(term, seen) {
2463
+ const m = /^([a-z_][a-z0-9_]*):\s+\S/i.exec(term.trim());
2464
+ if (!m)
2465
+ return false;
2466
+ return seen === undefined || seen(m[1].toLowerCase());
2467
+ }
2468
+ // The exclude grammar. `kind:frame` hides rows whose `kind` is exactly "frame"; `frame` alone
2469
+ // hides any row whose summary text contains it (a state change whose cause mentions a frame
2470
+ // goes too). The field is a bare identifier and the value follows the colon with no gap, so
2471
+ // `12:30`, `: x`, `a b:c` and log prose like `Error: timeout` (a term people already save) stay
2472
+ // plain text, and a value opening with `//` is a URL's authority, so `http://x` stays plain too.
2473
+ // A qualified term never falls back to a substring. Both halves are lowercased here, once per spec.
2474
+ export function parseExcludeTerm(term) {
2475
+ const m = /^([a-z_][a-z0-9_]*):(\S.*)$/i.exec(term.trim());
2476
+ if (m) {
2477
+ const value = m[2].trim();
2478
+ if (!value.startsWith("//"))
2479
+ return { field: m[1].toLowerCase(), value: value.toLowerCase() };
2480
+ }
2481
+ return { text: term.toLowerCase() };
2482
+ }
2483
+ // One searchable string per frame for the text filter AND for a spec's `exclude` terms (the
2484
+ // store's matches reads it too, so the two cannot drift onto different haystacks). The row KIND is
2485
+ // deliberately NOT part of this string: a kind token would make "-log" silently exclude clogs
2486
+ // (log ⊂ clog). Kind matching happens by EQUALITY via the filter predicate's second argument
2487
+ // instead (see filterKind in feed.ts).
2488
+ export function searchText(ev) {
2489
+ if ((ev._type || "") === "log")
2490
+ return [ev.level, ev.package, ev.tag, ev.message].filter(Boolean).join(" ").toLowerCase();
2491
+ if ((ev._type || "") === "trace")
2492
+ return [ev.trace_name, ev.span_name].filter(Boolean).join(" ").toLowerCase();
2493
+ if ((ev._type || "") === "switchboard")
2494
+ return [...switchboardFields(ev), ev.session_id].filter((x) => x != null && x !== "").join(" ").toLowerCase();
2495
+ return [ev.direction, ev.method, ev.event_type, ev.event_name, shortUrl(ev.url), ev.channel].filter(Boolean).join(" ").toLowerCase();
2496
+ }
2497
+ // A switchboard record's kind followed by that kind's key fields, in a fixed order, e.g.
2498
+ // ["frame", "incoming", "tts.state", 120], ["state", "connection", "Connecting", "Connected"],
2499
+ // ["phase", "socket", 412], ["player", "rearm", 38, 4096], ["session", "begin"]. This list is the
2500
+ // search haystack; the row summary (feed.ts switchboardSummary) reads the same fields by name, and
2501
+ // a test holds the two together. The record's `id` is deliberately not searchable, as for the other kinds.
2502
+ export function switchboardFields(ev) {
2503
+ const kind = ev.kind || "";
2504
+ const num = (v) => (typeof v === "number" ? v : undefined);
2505
+ switch (kind) {
2506
+ case "session": return [kind, ev.event];
2507
+ case "state": return [kind, ev.state_kind, ev.from, ev.to, ev.cause];
2508
+ case "frame": return [kind, ev.direction, ev.frame_type, num(ev.bytes)];
2509
+ case "phase": return [kind, ev.phase, num(ev.duration_ms)];
2510
+ case "player": return [kind, ev.event, num(ev.gap_ms), num(ev.bytes_queued)];
2511
+ default: return [kind];
2512
+ }
2513
+ }
1990
2514
  export function shortUrl(u) {
1991
2515
  try {
1992
2516
  return new URL(String(u)).pathname.replace("/api/", "");