@slack/radar-mcp 1.12.0 → 1.13.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.
package/dist/shared/db.js CHANGED
@@ -246,12 +246,56 @@ export function listDatabases(user) {
246
246
  .filter((n) => !/-(wal|shm|journal)$/.test(n));
247
247
  return { user: u, availableUsers: available, names };
248
248
  }
249
+ /**
250
+ * Reject a pulled DB buffer that is not a whole, complete SQLite file, before it is written
251
+ * to disk and cached. Three independent checks:
252
+ *
253
+ * 1. The magic header (first 16 bytes) AND a minimum length of 512 bytes, the smallest legal
254
+ * whole SQLite file (the smallest legal page size). Catches a missing/unreadable DB,
255
+ * whose `cat` emits an error string instead of file bytes, and also guards the page-size
256
+ * read below: without this floor, a buffer that happens to be exactly 16-17 bytes (magic
257
+ * present, nothing after) would throw an unhandled RangeError from `readUInt16BE`
258
+ * instead of this function's own clear error.
259
+ * 2. Page-size legality: the format only allows a power of two from 512 to 32768 at header
260
+ * offset 16-17 (big-endian), or the special-cased value 1 meaning 65536. `adb exec-out`
261
+ * streaming a live, multi-MB DB can truncate mid-page (an adb transport hiccup, or the
262
+ * app writing to the file while it is being read) and still pass check 1, since the
263
+ * header is the FIRST bytes of the stream and truncation happens later. If the cut lands
264
+ * inside the page-size field itself, the field can read as 0 or some other illegal value
265
+ * -- that is itself proof of truncation, not a value to skip validating.
266
+ * 3. Whole-file-size check: a complete SQLite file is always an exact multiple of its own
267
+ * (now known-legal) page size. A byte count that does not divide evenly is proof the
268
+ * stream was cut short somewhere past the header.
269
+ *
270
+ * Exported so this is testable without a device (mirrors assertReadOnlyQuery / isExplainQuery
271
+ * below, which exist for the same reason): pullDatabase's actual adb call cannot run in CI.
272
+ */
273
+ const MIN_SQLITE_FILE_SIZE = 512;
274
+ export function assertCompleteSqliteFile(name, bytes) {
275
+ if (!bytes ||
276
+ bytes.length < MIN_SQLITE_FILE_SIZE ||
277
+ !bytes.subarray(0, SQLITE_MAGIC.length).equals(SQLITE_MAGIC)) {
278
+ throw new Error(`"${name}" did not come back as a valid SQLite file (${bytes ? bytes.length : 0} bytes). It may not exist on the device, the org may not be loaded on this profile, or the database may be encrypted.`);
279
+ }
280
+ const declaredPageSize = bytes.readUInt16BE(16);
281
+ const pageSize = declaredPageSize === 1 ? 65536 : declaredPageSize;
282
+ const isLegalPageSize = pageSize === 65536 || (pageSize >= 512 && pageSize <= 32768 && (pageSize & (pageSize - 1)) === 0);
283
+ if (!isLegalPageSize) {
284
+ throw new Error(`"${name}" came back with an invalid page-size field (${declaredPageSize}). The device pull was likely cut off mid-stream and landed inside the header; retry.`);
285
+ }
286
+ if (bytes.length % pageSize !== 0) {
287
+ throw new Error(`"${name}" came back truncated (${bytes.length} bytes is not a whole multiple of its ${pageSize}-byte page size). The device pull was likely cut off mid-stream; retry.`);
288
+ }
289
+ }
249
290
  /**
250
291
  * Stream a database off the device to a local 0600 copy (scoped to the target user) and
251
292
  * return its path. `run-as ... cp` into shared storage fails silently (sandbox), so the
252
- * working path is `exec-out cat` piped to a host file. Validates the SQLite magic header
253
- * so a missing DB (whose `cat` emits an error string, not file bytes) fails with a clear
254
- * message instead of being written as a junk file that later trips an opaque parse error.
293
+ * working path is `exec-out cat` piped to a host file. Validates via
294
+ * `assertCompleteSqliteFile` (magic header, page-size legality, whole-file-size) so a
295
+ * missing or truncated pull fails with a clear message instead of being written as a junk
296
+ * file that later trips an opaque parse error. Retries the pull once on a transient
297
+ * truncation before giving up: `adb exec-out` hiccups are usually a one-shot glitch, and a
298
+ * silent retry means a dashboard user never sees the error for the common case.
255
299
  *
256
300
  * WAL: Slack's on-device DBs are WAL-mode and the live app holds write connections open,
257
301
  * so recently-committed rows live in the `-wal` sidecar, NOT yet in the main file. Pulling
@@ -274,22 +318,33 @@ export async function pullDatabase(name, user, force = false) {
274
318
  // force=true to re-stream when the user wants the current device state.
275
319
  if (!force && fs.existsSync(local))
276
320
  return local;
321
+ // A truncated pull is retried ONCE, silently, before giving up: an adb transport hiccup on
322
+ // a multi-MB stream is usually a one-shot glitch that a plain re-pull clears, and the
323
+ // common case should never surface an error to the user at all. Only the truncation checks
324
+ // (assertCompleteSqliteFile) are retried, not an adb-level failure (missing DB, run-as
325
+ // rejection) -- that failure mode is not transient and retrying it just doubles the wait
326
+ // before the same clear error.
277
327
  let bytes;
278
- try {
279
- // Async exec-out so a multi-MB pull does not block the event loop (which would hang
280
- // every other tab, the stream, and /health for the duration of the pull).
281
- bytes = await runAdbAsync([
282
- "exec-out",
283
- `run-as ${DB_PKG} ${userFlag(u)} cat databases/${name}`,
284
- ]);
285
- }
286
- catch {
287
- throw new Error(`"${name}" is not readable on the device (not present for this profile, or run-as failed). List databases to see what is there.`);
288
- }
289
- if (!bytes ||
290
- bytes.length < SQLITE_MAGIC.length ||
291
- !bytes.subarray(0, SQLITE_MAGIC.length).equals(SQLITE_MAGIC)) {
292
- throw new Error(`"${name}" did not come back as a valid SQLite file (${bytes ? bytes.length : 0} bytes). It may not exist on the device, the org may not be loaded on this profile, or the database may be encrypted.`);
328
+ for (let attempt = 0; attempt < 2; attempt++) {
329
+ try {
330
+ // Async exec-out so a multi-MB pull does not block the event loop (which would hang
331
+ // every other tab, the stream, and /health for the duration of the pull).
332
+ bytes = await runAdbAsync([
333
+ "exec-out",
334
+ `run-as ${DB_PKG} ${userFlag(u)} cat databases/${name}`,
335
+ ]);
336
+ }
337
+ catch {
338
+ throw new Error(`"${name}" is not readable on the device (not present for this profile, or run-as failed). List databases to see what is there.`);
339
+ }
340
+ try {
341
+ assertCompleteSqliteFile(name, bytes);
342
+ break;
343
+ }
344
+ catch (e) {
345
+ if (attempt === 1)
346
+ throw e;
347
+ }
293
348
  }
294
349
  fs.writeFileSync(local, bytes, { mode: 0o600 });
295
350
  // Pull the WAL sidecars alongside the main file so the normal (non-immutable) open below
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Rewrite the device's raw "Not Found" into an actionable message. The route 404s as valid
3
+ * JSON ({"error":"Not Found"}) on builds that predate the feature-flag Radar plugin, which is
4
+ * correct but useless to a caller with no way to know this route is plugin-gated.
5
+ */
6
+ export declare function friendlyFeatureFlagError(error: unknown): string;
@@ -0,0 +1,17 @@
1
+ // Shared feature-flag response handling for the two callers that read the device's
2
+ // /api/feature_flags route: the MCP tools (flags-tools.ts) and the web dashboard's Flags tab
3
+ // (web/server.ts). Both need the same "Not Found" rewrite for builds that predate the
4
+ // feature-flag Radar plugin, so it lives here once instead of drifting between two copies.
5
+ /**
6
+ * Rewrite the device's raw "Not Found" into an actionable message. The route 404s as valid
7
+ * JSON ({"error":"Not Found"}) on builds that predate the feature-flag Radar plugin, which is
8
+ * correct but useless to a caller with no way to know this route is plugin-gated.
9
+ */
10
+ export function friendlyFeatureFlagError(error) {
11
+ if (typeof error !== "string")
12
+ return "Unknown device error.";
13
+ if (error === "Not Found") {
14
+ return "This debug build does not serve feature flags yet (update to a build with the feature-flag Radar plugin).";
15
+ }
16
+ return error;
17
+ }
@@ -336,6 +336,27 @@
336
336
  .searchgroup { margin-bottom:16px; }
337
337
  .searchfile { color:var(--muted-2); font-size:11px; font-weight:600; padding:6px 10px; background:var(--surface); border-radius:6px; margin-bottom:8px; }
338
338
  .msg { color:var(--muted); font-size:12px; padding:10px; } .msg.err { color:var(--error); }
339
+ /* feature flags (source:"flags") -- reuses .dbout for the table */
340
+ .flagsview { display:flex; flex-direction:column; gap:10px; max-width:1180px; margin-top:8px; height:72vh; }
341
+ .flagsbar { display:flex; gap:10px; align-items:center; }
342
+ /* the filter input fills the row like the feed's, and shares the feedbar input styling */
343
+ .flagsbar .ffilterwrap { flex:1; min-width:140px; }
344
+ .flagsbar input { flex:1; background:var(--surface-2); border:1px solid var(--border-2); border-radius:8px; color:var(--text); padding:7px 10px; font:inherit; font-size:12.5px; } .flagsbar input:focus { outline:none; border-color:var(--accent); }
345
+ .flagsmeta { color:var(--muted); font-size:11.5px; white-space:nowrap; }
346
+ .flagsrefresh { margin-left:auto; background:var(--surface); border:1px solid var(--border-2); color:var(--muted-2); border-radius:8px; padding:5px 12px; font:inherit; font-size:11.5px; cursor:pointer; } .flagsrefresh:hover { border-color:var(--accent); color:var(--text); }
347
+ .flagsview .dbout th.val, .flagsview .dbout td.val { width:90px; }
348
+ .flagsview .dbout th.origin, .flagsview .dbout td.origin { width:160px; }
349
+ .flagsview .dbout td.key { font-family:ui-monospace,Menlo,Consolas,monospace; color:var(--text); }
350
+ .flagval { font-variant-numeric:tabular-nums; font-weight:600; }
351
+ .flagval.on { color:var(--accent); } .flagval.off { color:var(--muted); } .flagval.dim { opacity:.55; font-weight:400; }
352
+ .flagval.variant { font-variant-numeric:normal; font-family:ui-monospace,Menlo,Consolas,monospace; font-size:11.5px; }
353
+ .flagsview .dbout tr.overridden td { background:var(--hover); }
354
+ /* live observer patch: briefly highlight a row whose value just changed */
355
+ .flagsview .dbout tr.flash td { animation:flagflash 1.2s ease-out; }
356
+ @keyframes flagflash { from { background:var(--accent-bg); } to { background:transparent; } }
357
+ .orbadge { display:inline-block; padding:1px 7px; border-radius:4px; font-size:10.5px; font-weight:600; white-space:nowrap; border:1px solid var(--border-2); }
358
+ .orbadge.or-server { color:var(--accent); border-color:var(--accent); }
359
+ .orbadge.or-override { color:#ffb454; border-color:#ffb454; }
339
360
  /* screen overlay */
340
361
  #screenpanel { position:fixed; top:0; right:0; bottom:0; width:340px; background:var(--surface-2); border-left:1px solid var(--border); z-index:40; display:flex; flex-direction:column; padding:12px; box-shadow:-4px 0 16px var(--shadow); overflow:auto; }
341
362
  #screenpanel .schead { display:flex; align-items:center; gap:8px; margin-bottom:10px; }
@@ -8,13 +8,14 @@ import { html } from "./html.js";
8
8
  import { render } from "preact";
9
9
  import { useState, useEffect, useCallback } from "preact/hooks";
10
10
  import { useStoreValue } from "./hooks.js";
11
- import { store, MODES, describeConstraints } from "./store.js";
11
+ import { store, MODES, modeServed, describeConstraints } from "./store.js";
12
12
  import { SOURCES } from "./registry.js";
13
13
  import { Feed } from "./feed.js";
14
14
  import { Cards } from "./widgets.js";
15
15
  import { Inspector } from "./inspector.js";
16
16
  import { Filters } from "./filters.js";
17
17
  import { DbBrowser } from "./db.js";
18
+ import { FlagsBrowser } from "./flags.js";
18
19
  import { PrefsBrowser } from "./prefs.js";
19
20
  import { ScreenOverlay } from "./screen.js";
20
21
  function readTheme() {
@@ -89,11 +90,20 @@ function Header({ screenOpen, onScreenToggle }) {
89
90
  function ModeBar() {
90
91
  const [, force] = useState(0);
91
92
  useEffect(() => store.on("spec", () => force((n) => n + 1)), []);
93
+ const deviceSources = useStoreValue(store, "sources", () => store.deviceSources);
92
94
  const activeKey = store.activeModeKey();
93
95
  const pick = (specToPush) => store.setSpec(specToPush);
96
+ const serves = (m) => modeServed(m.key, deviceSources);
97
+ // A device switch can hide the active tab (leaner build). Reset to the first tab so the
98
+ // user is never stranded on an invisible mode rendering a dead feed.
99
+ useEffect(() => {
100
+ if (activeKey && activeKey !== "__custom__" && !modeServed(activeKey, deviceSources)) {
101
+ store.setSpec(MODES[0].spec);
102
+ }
103
+ }, [deviceSources, activeKey]);
94
104
  // Group modes by source kind for visual separation
95
- const streamModes = MODES.filter((m) => SOURCES[m.spec.source]?.kind === "stream");
96
- const stateModes = MODES.filter((m) => SOURCES[m.spec.source]?.kind === "state");
105
+ const streamModes = MODES.filter((m) => serves(m) && SOURCES[m.spec.source]?.kind === "stream");
106
+ const stateModes = MODES.filter((m) => serves(m) && SOURCES[m.spec.source]?.kind === "state");
97
107
  return html `
98
108
  <div class="modebar">
99
109
  ${streamModes.map((m) => html `<button class=${"modebtn" + (activeKey === m.key ? " active" : "")} onClick=${() => pick(m.spec)}>${m.label}</button>`)}
@@ -201,7 +211,8 @@ function App() {
201
211
  if (e.key !== "ArrowRight" && e.key !== "ArrowLeft" && e.key !== "h" && e.key !== "l")
202
212
  return;
203
213
  const dir = e.key === "ArrowRight" || e.key === "l" ? 1 : -1;
204
- const keys = MODES.map((m) => m.key);
214
+ // Same filter as the modebar, so the arrows cannot land on a hidden tab.
215
+ const keys = MODES.filter((m) => modeServed(m.key, store.deviceSources)).map((m) => m.key);
205
216
  if (store.lastCustomSpec)
206
217
  keys.push("__custom__");
207
218
  let cur = keys.indexOf(store.activeModeKey() || "");
@@ -235,6 +246,17 @@ function App() {
235
246
  <${DbBrowser} spec=${spec} key=${"db-" + dbResync} />
236
247
  `;
237
248
  }
249
+ else if (spec.source === "flags") {
250
+ // Feature Flags: a self-contained, point-in-time container like the DB browser (no store /
251
+ // SSE engine). key=flags so it remounts cleanly when switching to the tab.
252
+ view = html `
253
+ <div class="sub">
254
+ <span class="summary">${spec.summary || "Feature flags"}</span>
255
+ <span class="tech">source=flags (live snapshot from the running app)</span>
256
+ </div>
257
+ <${FlagsBrowser} key="flags" />
258
+ `;
259
+ }
238
260
  else if (spec.source === "prefs") {
239
261
  // The Prefs browser is a self-contained, point-in-time container: it does NOT import the store
240
262
  // (no SSE engine / timers on a tab that has no live feed). key folds in dbResync (PR #94
@@ -5,7 +5,7 @@
5
5
  // and the RENDER side (windowed rows + keyboard model).
6
6
  import { html } from "./html.js";
7
7
  import { useState, useEffect, useRef, useCallback, useMemo } from "preact/hooks";
8
- import { store, shortUrl, shortPkg, MODES, fmtNum } from "./store.js";
8
+ import { store, shortUrl, shortPkg, MODES, modeServed, fmtNum } from "./store.js";
9
9
  import { STREAM_KINDS } from "./registry.js";
10
10
  import { parseFilter, tokenize, isCompleteTerm } from "./filter.js";
11
11
  const ROW_H = 24;
@@ -103,7 +103,8 @@ function sortOptionsFor(source) {
103
103
  // The spec of the tab `dir` steps away from the active one (clamped). Used by the filter box's
104
104
  // empty-arrow tab-switch (the global handler ignores keys typed in an input).
105
105
  function neighborTabSpec(dir) {
106
- const keys = MODES.map((m) => m.key);
106
+ // Same filter as the modebar, so the arrows cannot land on a hidden tab.
107
+ const keys = MODES.filter((m) => modeServed(m.key, store.deviceSources)).map((m) => m.key);
107
108
  if (store.lastCustomSpec)
108
109
  keys.push("__custom__");
109
110
  let cur = keys.indexOf(store.activeModeKey() || "");
@@ -553,6 +554,12 @@ export function Feed({ spec, onInspect, selectedId }) {
553
554
  // switching (←/→/h/l) is handled GLOBALLY in app.ts so it also works on DB/Screen.
554
555
  useEffect(() => {
555
556
  const onKey = (e) => {
557
+ // If the user has an active text selection (e.g. highlighted text in the detail panel),
558
+ // let the browser's native copy run instead of hijacking Cmd/Ctrl-C to copy feed rows.
559
+ if ((e.metaKey || e.ctrlKey) && e.key === "c") {
560
+ if ((window.getSelection()?.toString() ?? "") !== "")
561
+ return; // native copy proceeds
562
+ }
556
563
  const t = e.target;
557
564
  if (t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA" || t.tagName === "SELECT" || t.isContentEditable)) {
558
565
  if ((e.metaKey || e.ctrlKey) && e.key === "c" && sel.size) {
@@ -0,0 +1,179 @@
1
+ // Feature Flags browser (source:"flags") -- a live view of the running Slack app's feature
2
+ // flags. Loads a point-in-time snapshot, then subscribes to the device's on-device observer so
3
+ // rows update in place as overrides/server values change. Like the DB browser it must NOT import
4
+ // the streaming store (that would start the store's own SSE engine + timers on this tab); it
5
+ // opens its OWN short-lived EventSource on /stream and closes it on unmount.
6
+ //
7
+ // Server contract (server.ts proxies to the device feature-flag RadarPlugin):
8
+ // GET /flags -> { feature_flags: FlagRow[], total } | { error, feature_flags: [] }
9
+ //
10
+ // Each FlagRow (device list = summary, kept light):
11
+ // key flag name, e.g. "android_some_flag"
12
+ // enabled the EFFECTIVE value the app uses right now (local override if set, else the
13
+ // server value). Boolean today; a string (variant group name) is rendered too,
14
+ // defensively, in case the device plugin regains multi-variant support.
15
+ // is_overridden true when a local debug override is active
16
+ //
17
+ // Live updates: the device observer pushes `feature_flag` frames on /api/stream (proxied to
18
+ // /stream) whenever a flag's effective value changes: {type:"feature_flag", event:{key, enabled,
19
+ // is_overridden}}. We upsert those into the row set by key and briefly flash the changed row.
20
+ //
21
+ // Columns: flag | value | origin. `value` = enabled (ON/OFF, or a variant group pill). `origin`
22
+ // = Override (local) when is_overridden, else Server. (The device no longer sends a separate
23
+ // server value or scope in the list, so those columns are gone.)
24
+ import { html } from "./html.js";
25
+ import { useState, useEffect, useCallback, useRef } from "preact/hooks";
26
+ // Render a flag value. Booleans (toggles) show ON/OFF; a variant group-name string shows as a
27
+ // text pill ("" / "control" read as the off/baseline arm). `dim` mutes a secondary column.
28
+ function valuePill(v, dim) {
29
+ if (v === undefined || v === null)
30
+ return html `<span class="flagval dim">—</span>`;
31
+ if (typeof v === "boolean") {
32
+ return html `<span class=${"flagval " + (v ? "on" : "off") + (dim ? " dim" : "")}>${v ? "ON" : "OFF"}</span>`;
33
+ }
34
+ const off = v === "" || v.toLowerCase() === "control";
35
+ return html `<span class=${"flagval variant " + (off ? "off" : "on") + (dim ? " dim" : "")}>${v || "—"}</span>`;
36
+ }
37
+ // Why a flag has its effective value. No SERVER/LOCAL state field anymore, so origin is derived
38
+ // purely from whether a local override is active.
39
+ function origin(f) {
40
+ return f.is_overridden === true
41
+ ? { label: "Override (local)", cls: "or-override" }
42
+ : { label: "Server", cls: "or-server" };
43
+ }
44
+ const FLASH_MS = 1200;
45
+ export function FlagsBrowser() {
46
+ // rows: the current flag set keyed by name (upserted by both the snapshot and live events).
47
+ const [rows, setRows] = useState(null); // null = loading
48
+ const [err, setErr] = useState(null);
49
+ const [filter, setFilter] = useState("");
50
+ // keys that changed recently (drives the row flash); value is a token cleared on a timer.
51
+ const [flashed, setFlashed] = useState({});
52
+ const flashTimers = useRef({});
53
+ const flash = useCallback((key) => {
54
+ setFlashed((f) => ({ ...f, [key]: (f[key] || 0) + 1 }));
55
+ const timers = flashTimers.current;
56
+ if (timers[key])
57
+ clearTimeout(timers[key]);
58
+ timers[key] = setTimeout(() => {
59
+ setFlashed((f) => {
60
+ const next = { ...f };
61
+ delete next[key];
62
+ return next;
63
+ });
64
+ delete timers[key];
65
+ }, FLASH_MS);
66
+ }, []);
67
+ const load = useCallback(async () => {
68
+ setRows(null);
69
+ setErr(null);
70
+ try {
71
+ const r = await (await fetch("/flags")).json();
72
+ if (r.error) {
73
+ setErr(r.error);
74
+ setRows({});
75
+ return;
76
+ }
77
+ const byKey = {};
78
+ for (const fl of r.feature_flags || [])
79
+ byKey[fl.key] = fl;
80
+ setRows(byKey);
81
+ }
82
+ catch {
83
+ setErr("network error loading feature flags");
84
+ setRows({});
85
+ }
86
+ }, []);
87
+ // initial snapshot
88
+ useEffect(() => {
89
+ load();
90
+ }, []);
91
+ // Live observer: our OWN EventSource (not the store's). Patch rows on `feature_flag` frames.
92
+ useEffect(() => {
93
+ const es = new EventSource("/stream");
94
+ es.onmessage = (m) => {
95
+ let f;
96
+ try {
97
+ f = JSON.parse(m.data);
98
+ }
99
+ catch {
100
+ return;
101
+ }
102
+ if (f.type !== "feature_flag" || !f.event || !f.event.key)
103
+ return;
104
+ const ev = f.event;
105
+ setRows((prev) => ({ ...(prev || {}), [ev.key]: { ...(prev && prev[ev.key]), ...ev } }));
106
+ flash(ev.key);
107
+ };
108
+ // The tab works without live updates; a stream error just means no live patching.
109
+ es.onerror = () => { };
110
+ return () => es.close();
111
+ }, [flash]);
112
+ // clear any pending flash timers on unmount
113
+ useEffect(() => () => {
114
+ for (const t of Object.values(flashTimers.current))
115
+ clearTimeout(t);
116
+ }, []);
117
+ const all = rows ? Object.values(rows).sort((a, b) => a.key.localeCompare(b.key)) : [];
118
+ const f = filter.trim().toLowerCase();
119
+ const shown = f ? all.filter((x) => (x.key || "").toLowerCase().includes(f)) : all;
120
+ const meta = rows == null ? "" : f ? shown.length + " / " + all.length + " shown" : all.length + " flags";
121
+ return html `
122
+ <div class="flagsview">
123
+ <div class="flagsbar">
124
+ <span class="ffilterwrap">
125
+ <input
126
+ class="ffilter"
127
+ value=${filter}
128
+ placeholder="filter flags by name…"
129
+ autocomplete="off"
130
+ onInput=${(e) => setFilter(e.currentTarget.value)}
131
+ onKeyDown=${(e) => {
132
+ if (e.key === "Escape")
133
+ setFilter("");
134
+ }}
135
+ />
136
+ ${filter ? html `<span class="ffilterclear" title="clear filter" onClick=${() => setFilter("")}>✕</span>` : null}
137
+ </span>
138
+ <span class="flagsmeta">${meta}</span>
139
+ <button class="flagsrefresh" title="re-fetch the snapshot" onClick=${() => load()}>↻ refresh</button>
140
+ </div>
141
+ <div class="dbout flagsout">
142
+ ${rows == null
143
+ ? html `<div class="msg">loading…</div>`
144
+ : err
145
+ ? html `<div class="msg err">${err}</div>`
146
+ : !all.length
147
+ ? html `<div class="msg">no feature flags (device unreachable, or this build predates the feature-flag plugin)</div>`
148
+ : !shown.length
149
+ ? html `<div class="msg">no flags match “${filter}”</div>`
150
+ : html `<${Table} rows=${shown} flashed=${flashed} />`}
151
+ </div>
152
+ </div>
153
+ `;
154
+ }
155
+ function Table({ rows, flashed }) {
156
+ return html `
157
+ <table>
158
+ <thead>
159
+ <tr>
160
+ <th>flag</th>
161
+ <th class="val">value</th>
162
+ <th class="origin">origin</th>
163
+ </tr>
164
+ </thead>
165
+ <tbody>
166
+ ${rows.map((x) => {
167
+ const o = origin(x);
168
+ const ov = x.is_overridden === true;
169
+ const cls = (ov ? "overridden" : "") + (flashed[x.key] ? " flash" : "");
170
+ return html `<tr class=${cls}>
171
+ <td class="key" title=${x.key}>${x.key}</td>
172
+ <td class="val">${valuePill(x.enabled)}</td>
173
+ <td class="origin"><span class=${"orbadge " + o.cls}>${o.label}</span></td>
174
+ </tr>`;
175
+ })}
176
+ </tbody>
177
+ </table>
178
+ `;
179
+ }
@@ -42,6 +42,8 @@ export const SOURCES = {
42
42
  all: { label: "Live", kind: "stream" },
43
43
  db: { label: "Database", kind: "state" },
44
44
  prefs: { label: "Preferences", kind: "state" },
45
+ // Feature flags: a point-in-time snapshot like db/prefs (own container, no SSE feed).
46
+ flags: { label: "Feature Flags", kind: "state" },
45
47
  };
46
48
  // The set of streaming source kinds the store admits off the SSE stream (derived from SOURCES,
47
49
  // excluding the non-stream db + the unified "all" alias).
@@ -58,6 +60,13 @@ export const DETAILABLE_KINDS = Object.entries(SOURCES)
58
60
  export const EAGER_CAPTURE_KINDS = Object.entries(SOURCES)
59
61
  .filter(([, v]) => v.hasDetailEndpoint && v.eagerCapture)
60
62
  .map(([k]) => k);
63
+ // A "state" source is a point-in-time browser (db, prefs, flags), NOT a live stream. The store
64
+ // fully quiets its SSE engine + tick for these (they run their own fetch/stream), so this is the
65
+ // single check the store branches on — derived from the registry so a new state source cannot
66
+ // drift out of sync with the store's quieting logic.
67
+ export function isStateSource(source) {
68
+ return !!source && SOURCES[source]?.kind === "state";
69
+ }
61
70
  export function hasDetailEndpoint(kind) {
62
71
  return !!SOURCES[kind]?.hasDetailEndpoint;
63
72
  }
@@ -66,7 +75,7 @@ export function hasDetailEndpoint(kind) {
66
75
  // see widgets.ts). A new widget = one key here + one component.
67
76
  export const WIDGETS = ["counter", "rate", "sparkline", "graph"];
68
77
  // Source order for the modebar / global tab-switch (matches the MODES preset order).
69
- export const SOURCE_ORDER = ["all", "network", "rtm", "clog", "trace", "log", "db", "prefs"];
78
+ export const SOURCE_ORDER = ["all", "network", "rtm", "clog", "trace", "log", "db", "prefs", "flags"];
70
79
  // The source options the Filters panel offers: every streaming source (state sources like db/prefs
71
80
  // are their own containers, not feed filters). Derived from SOURCES so adding a streaming source
72
81
  // surfaces it in Filters with no edit there. Ordered by SOURCE_ORDER (the modebar order) for a stable, familiar list.
@@ -1,4 +1,4 @@
1
- import { STREAM_KINDS, EAGER_CAPTURE_KINDS } from "./registry.js";
1
+ import { STREAM_KINDS, EAGER_CAPTURE_KINDS, isStateSource } 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
@@ -33,7 +33,24 @@ export const MODES = [
33
33
  { 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" } } },
34
34
  { key: "db", label: "Database", spec: { title: "Device DB", summary: "Browse the on-device SQLite databases (read-only snapshot).", source: "db" } },
35
35
  { key: "prefs", label: "Preferences", spec: { title: "Device Preferences", summary: "Browse the on-device SharedPreferences (including feature-flag overrides), read-only.", source: "prefs" } },
36
+ { key: "flags", label: "Feature Flags", spec: { title: "Feature Flags", summary: "Every feature flag the Slack app knows about, with its current effective value and whether it is locally overridden. Live-updates as flags change on the device. Filter by name.", source: "flags" } },
36
37
  ];
38
+ // Dashboard mode key -> the ping `sources` name that must be present for the tab to work. Only
39
+ // sources the device ships as plugins are gateable; the rest (network/rtm/clog/db/prefs/...)
40
+ // always show, and each joins this map when its device-side migration lands. Lives here next to
41
+ // MODES (the thing it keys off) so the two cannot drift apart in separate files.
42
+ export const MODE_SOURCE = {
43
+ trace: "traces",
44
+ flags: "feature_flags",
45
+ };
46
+ // True when the device serves this mode's source. Old builds declare nothing
47
+ // (sources null) and keep every tab.
48
+ export function modeServed(key, sources) {
49
+ if (!sources)
50
+ return true;
51
+ const required = MODE_SOURCE[key];
52
+ return !required || sources.includes(required);
53
+ }
37
54
  // A preset is identified by what it DOES, not how it is labelled. canonicalSpecKey reduces a
38
55
  // spec to its behavioral identity so a spec that is semantically a preset still matches it
39
56
  // despite cosmetic drift:
@@ -91,6 +108,9 @@ class Store {
91
108
  // within 2s and the message vanished before the user read it. This field is owned by
92
109
  // selectDevice, survives the health poll, and clears only on a successful pick.
93
110
  deviceError = null;
111
+ // Capture-source names the device declares on ping (seam builds). null = old build with no
112
+ // discovery, in which case every tab shows (today's behavior). Emitted as "sources" on change.
113
+ deviceSources = null;
94
114
  cache = [];
95
115
  cacheKeys = new Set();
96
116
  seen = {};
@@ -221,6 +241,7 @@ class Store {
221
241
  this.selectedDevice = null;
222
242
  this.devicesError = false;
223
243
  this.deviceError = null;
244
+ this.deviceSources = null;
224
245
  this.cache = [];
225
246
  this.cacheKeys = new Set();
226
247
  this.seen = {};
@@ -252,7 +273,7 @@ class Store {
252
273
  // spec.series entry, or null when the spec has no graph. Shared by applySpec (fresh spec) and
253
274
  // clearDeviceCaches (device switch) so the two paths cannot drift.
254
275
  buildGraph() {
255
- if (this.spec.blank || this.spec.source === "db" || this.spec.source === "prefs" || !Array.isArray(this.spec.viz) || !this.spec.viz.includes("graph") || !Array.isArray(this.spec.series)) {
276
+ if (this.spec.blank || isStateSource(this.spec.source) || !Array.isArray(this.spec.viz) || !this.spec.viz.includes("graph") || !Array.isArray(this.spec.series)) {
256
277
  return null;
257
278
  }
258
279
  return { N: GRAPH_N, series: this.spec.series.map((s) => ({ def: s, buckets: new Array(GRAPH_N).fill(0), counts: new Array(GRAPH_N).fill(0) })) };
@@ -276,6 +297,11 @@ class Store {
276
297
  this.times = [];
277
298
  this.perSec = new Array(PERSEC_N).fill(0);
278
299
  this.graph = this.buildGraph();
300
+ // The old device's declared sources do not describe the new one; null until its next poll.
301
+ this.updateSources(null);
302
+ // Best-effort latency win: age the fresh-frame stamp so the next pollHealth really fetches.
303
+ // Backfill frames can re-freshen it within ms; pollProfile's 5s read is the backstop.
304
+ this._lastEventTs = 0;
279
305
  }
280
306
  // ---- start everything ----
281
307
  start() {
@@ -382,9 +408,10 @@ class Store {
382
408
  this._capQueue.length = 0;
383
409
  this.graph = this.buildGraph();
384
410
  this.emit("spec", this.spec);
385
- // DB/Prefs browser + blank: fully quiet the streaming engine so it does not compete with
386
- // point-in-time operations. Close the SSE stream AND stop the per-second tick. The 100k cache is left intact.
387
- if (this.spec.blank || this.spec.source === "db" || this.spec.source === "prefs") {
411
+ // State browsers (db/prefs/flags) + blank: fully quiet the streaming engine so it does not
412
+ // compete with point-in-time operations (each state tab runs its own fetch/stream). Close the
413
+ // SSE stream AND stop the per-second tick. The 100k cache is left intact.
414
+ if (this.spec.blank || isStateSource(this.spec.source)) {
388
415
  this.closeStream();
389
416
  if (this._tick) {
390
417
  clearInterval(this._tick);
@@ -723,6 +750,19 @@ class Store {
723
750
  this.emit("db-resync", this.dbSerialVersion);
724
751
  }
725
752
  // ---- health + profile ----
753
+ // Track the device's declared capture sources (seam builds). Emits "sources" only on a real
754
+ // change so the modebar does not re-render every 2s poll.
755
+ updateSources(raw) {
756
+ const names = raw
757
+ ? raw.map((s) => (typeof s?.name === "string" ? s.name : "")).filter(Boolean)
758
+ : null;
759
+ const key = names ? names.slice().sort().join(",") : null;
760
+ const prev = this.deviceSources ? this.deviceSources.slice().sort().join(",") : null;
761
+ if (key === prev)
762
+ return;
763
+ this.deviceSources = names;
764
+ this.emit("sources", names);
765
+ }
726
766
  async pollHealth() {
727
767
  if (Date.now() - this._lastEventTs < 6000) {
728
768
  this._healthMisses = 0;
@@ -739,6 +779,9 @@ class Store {
739
779
  // activity. Between the two, both busy and quiet observer tabs converge within 5s.
740
780
  this.checkSerialEdge(h.device_serial ?? null);
741
781
  if (h.device) {
782
+ // Only a healthy reply updates the source list: a device:false blip must not flip
783
+ // tabs off and back on recovery. The last list stands until the serial edge clears it.
784
+ this.updateSources(Array.isArray(h.sources) ? h.sources : null);
742
785
  this._healthMisses = 0;
743
786
  this.recovered();
744
787
  this.setConn("connected", "");
@@ -773,6 +816,11 @@ class Store {
773
816
  fetch("/health").then((r) => r.json()).catch(() => null),
774
817
  ]);
775
818
  const uid = healthR && healthR.boundUserId;
819
+ // pollHealth's fresh-frame fast path can skip its /health fetch indefinitely on a chatty
820
+ // stream; this 5s poll already fetched /health, so read the sources off it too.
821
+ if (healthR && healthR.device) {
822
+ this.updateSources(Array.isArray(healthR.sources) ? healthR.sources : null);
823
+ }
776
824
  this.profiles = (profilesR && profilesR.profiles) || [];
777
825
  if (uid == null) {
778
826
  this.profileLabel = this._lastBoundLabel ? "last seen " + this._lastBoundLabel + " — reconnecting…" : "waiting for device…";
@@ -865,7 +913,7 @@ class Store {
865
913
  resyncStream() {
866
914
  this._dropped = false;
867
915
  const src = this.spec.source;
868
- if (this.spec.blank || !src || src === "db" || src === "prefs")
916
+ if (this.spec.blank || !src || isStateSource(src))
869
917
  return;
870
918
  this.openStream();
871
919
  this.backfill();