@slack/radar-mcp 1.12.0 → 1.14.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
+ }
package/dist/web/bin.js CHANGED
@@ -3,7 +3,7 @@ import { execSync } from "child_process";
3
3
  import { realpathSync } from "fs";
4
4
  import http from "http";
5
5
  import { fileURLToPath } from "url";
6
- import { cleanupOnBind, createServer, seedInitialSpec, WEB_PORT } from "./server.js";
6
+ import { cleanupOnBind, createServer, seedInitialSpec, shutdownDashboard, startAutoCloseSweep, WEB_PORT, } from "./server.js";
7
7
  import { RADAR_VERSION } from "../shared/constants.js";
8
8
  /**
9
9
  * One loopback GET against the dashboard's own port, used by the adopt path. Resolves with the
@@ -144,6 +144,10 @@ export function startWebServer() {
144
144
  // so adopting it leaves its view and open DB-browser tab intact.
145
145
  seedInitialSpec();
146
146
  cleanupOnBind();
147
+ // Arm the auto-close sweep only now that THIS process owns the port. Doing it post-bind (not
148
+ // in createServer) keeps importing the module — or a second launcher that loses the bind —
149
+ // from arming a timer that could process.exit. The interval is unref'd inside.
150
+ startAutoCloseSweep(server);
147
151
  const url = `http://localhost:${WEB_PORT}`;
148
152
  console.log(`Slack Radar Web running at ${url}`);
149
153
  // Auto-open the browser for the HUMAN launcher (`slack-radar web` / `slack-radar-web`),
@@ -155,11 +159,17 @@ export function startWebServer() {
155
159
  return;
156
160
  openBrowser(url);
157
161
  });
158
- const shutdown = () => {
159
- console.log("\nShutting down…");
160
- server.close(() => process.exit(0));
161
- setTimeout(() => process.exit(0), 2000);
162
- };
162
+ // The /shutdown route and the auto-close sweep both funnel through shutdownDashboard, so the
163
+ // server.close + timeout-fallback exit -- and the finalize-a-live-recording safety step --
164
+ // cannot drift between THOSE two paths. Ctrl-C / SIGTERM do NOT reach this handler: screen.ts's
165
+ // registerScreenCleanup() (called earlier, inside createServer()) registers its own SIGINT/
166
+ // SIGTERM listeners that call process.exit() synchronously, and Node runs signal listeners in
167
+ // registration order -- so screen.ts's handler always wins the race and this one below never
168
+ // runs. That handler's own signalCleanup() does its own (fire-and-forget, non-recording-safe)
169
+ // teardown. Pre-existing gap, not introduced here; fixing it means touching screen.ts, which is
170
+ // out of scope for this change. Registering below anyway costs nothing and is the load-bearing
171
+ // path IF screen.ts's signal handling ever stops calling process.exit() synchronously.
172
+ const shutdown = () => void shutdownDashboard(server);
163
173
  process.on("SIGINT", shutdown);
164
174
  process.on("SIGTERM", shutdown);
165
175
  }
@@ -60,6 +60,7 @@
60
60
  h1 .version { margin-left:auto; font-size:11px; font-weight:400; color:var(--muted-2); letter-spacing:0; }
61
61
  .themebtn, .screenbtn { background:var(--surface); border:1px solid var(--border-2); color:var(--muted-2); border-radius:8px; padding:5px 12px; font:inherit; font-size:12.5px; cursor:pointer; }
62
62
  .themebtn:hover, .screenbtn:hover { border-color:var(--accent); color:var(--text); } .screenbtn.on { background:var(--accent-bg); border-color:var(--accent); color:var(--accent-text); }
63
+ .killbtn.armed { border-color:var(--error); color:var(--error); } .killbtn.armed:hover { border-color:var(--error-2); color:var(--error-2); }
63
64
  .modebar { display:flex; gap:6px; margin:0 0 6px; flex-wrap:wrap; flex:0 0 auto; align-items:center; }
64
65
  .modebtn { background:var(--surface); border:1px solid var(--border-2); color:var(--muted-2); border-radius:8px; padding:6px 14px; font:inherit; font-size:12.5px; cursor:pointer; }
65
66
  .modebtn:hover { border-color:var(--accent); color:var(--text); }
@@ -336,6 +337,27 @@
336
337
  .searchgroup { margin-bottom:16px; }
337
338
  .searchfile { color:var(--muted-2); font-size:11px; font-weight:600; padding:6px 10px; background:var(--surface); border-radius:6px; margin-bottom:8px; }
338
339
  .msg { color:var(--muted); font-size:12px; padding:10px; } .msg.err { color:var(--error); }
340
+ /* feature flags (source:"flags") -- reuses .dbout for the table */
341
+ .flagsview { display:flex; flex-direction:column; gap:10px; max-width:1180px; margin-top:8px; height:72vh; }
342
+ .flagsbar { display:flex; gap:10px; align-items:center; }
343
+ /* the filter input fills the row like the feed's, and shares the feedbar input styling */
344
+ .flagsbar .ffilterwrap { flex:1; min-width:140px; }
345
+ .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); }
346
+ .flagsmeta { color:var(--muted); font-size:11.5px; white-space:nowrap; }
347
+ .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); }
348
+ .flagsview .dbout th.val, .flagsview .dbout td.val { width:90px; }
349
+ .flagsview .dbout th.origin, .flagsview .dbout td.origin { width:160px; }
350
+ .flagsview .dbout td.key { font-family:ui-monospace,Menlo,Consolas,monospace; color:var(--text); }
351
+ .flagval { font-variant-numeric:tabular-nums; font-weight:600; }
352
+ .flagval.on { color:var(--accent); } .flagval.off { color:var(--muted); } .flagval.dim { opacity:.55; font-weight:400; }
353
+ .flagval.variant { font-variant-numeric:normal; font-family:ui-monospace,Menlo,Consolas,monospace; font-size:11.5px; }
354
+ .flagsview .dbout tr.overridden td { background:var(--hover); }
355
+ /* live observer patch: briefly highlight a row whose value just changed */
356
+ .flagsview .dbout tr.flash td { animation:flagflash 1.2s ease-out; }
357
+ @keyframes flagflash { from { background:var(--accent-bg); } to { background:transparent; } }
358
+ .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); }
359
+ .orbadge.or-server { color:var(--accent); border-color:var(--accent); }
360
+ .orbadge.or-override { color:#ffb454; border-color:#ffb454; }
339
361
  /* screen overlay */
340
362
  #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
363
  #screenpanel .schead { display:flex; align-items:center; gap:8px; margin-bottom:10px; }
@@ -6,15 +6,16 @@
6
6
  // router sibling toggled by ▣ Screen: a fixed right-docked panel that floats over any view.
7
7
  import { html } from "./html.js";
8
8
  import { render } from "preact";
9
- import { useState, useEffect, useCallback } from "preact/hooks";
9
+ import { useState, useEffect, useCallback, useRef } 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() {
@@ -54,13 +55,42 @@ function Header({ screenOpen, onScreenToggle }) {
54
55
  const conn = useStoreValue(store, "conn", () => store.conn);
55
56
  const profile = useStoreValue(store, "profile", () => store.profileLabel);
56
57
  const version = useStoreValue(store, "version", () => store.serverVersion);
58
+ const stopped = useStoreValue(store, "stopped", () => store.stopped);
57
59
  const [busy, setBusy] = useState(false);
60
+ const [killing, setKilling] = useState(false);
61
+ // Arm/confirm for the destructive kill button: the FIRST click only arms a "sure?" state
62
+ // (auto-disarms after a few seconds so a stray click never leaves a live trap); the SECOND
63
+ // click, while armed, actually fires. Kills the whole process with no undo (drops the session
64
+ // logcat ring and the pulled-DB cache), so a same-styled-as-Theme single click is not safe --
65
+ // this is the confirmation without adding a dialog/modal that would change the header layout.
66
+ const [killArmed, setKillArmed] = useState(false);
67
+ const killArmTimer = useRef(null);
68
+ useEffect(() => () => { if (killArmTimer.current)
69
+ clearTimeout(killArmTimer.current); }, []);
58
70
  const [theme, setTheme] = useState(readTheme);
59
71
  const reconnect = useCallback(async () => {
60
72
  setBusy(true);
61
73
  await store.reconnect();
62
74
  setBusy(false);
63
75
  }, []);
76
+ const kill = useCallback(async () => {
77
+ if (!killArmed) {
78
+ setKillArmed(true);
79
+ if (killArmTimer.current)
80
+ clearTimeout(killArmTimer.current);
81
+ killArmTimer.current = setTimeout(() => setKillArmed(false), 4000);
82
+ return;
83
+ }
84
+ if (killArmTimer.current)
85
+ clearTimeout(killArmTimer.current);
86
+ setKillArmed(false);
87
+ setKilling(true);
88
+ const ok = await store.kill();
89
+ // On success the store flips `stopped` and the terminal state renders below; on failure the
90
+ // server is still up, so drop the busy flag and let the user try again.
91
+ if (!ok)
92
+ setKilling(false);
93
+ }, [killArmed]);
64
94
  const toggleTheme = useCallback(() => {
65
95
  const next = readTheme() === "light" ? "dark" : "light";
66
96
  document.documentElement.classList.toggle("light", next === "light");
@@ -72,6 +102,14 @@ function Header({ screenOpen, onScreenToggle }) {
72
102
  }
73
103
  setTheme(next);
74
104
  }, []);
105
+ // The server is gone. Render a terminal state in place of the live header rather than leaving
106
+ // stale controls that would all fail against a dead port. Every hook above runs on EVERY
107
+ // render regardless of `stopped` -- an early return before a hook call would skip it once
108
+ // stopped flips true, changing the hook count between renders (Preact/React both require the
109
+ // same hooks, same order, every render).
110
+ if (stopped) {
111
+ return html `<h1>SLACK RADAR DASHBOARD <span class="conn waiting">● dashboard stopped</span></h1>`;
112
+ }
75
113
  const connected = conn.state === "connected";
76
114
  return html `
77
115
  <h1>
@@ -82,6 +120,7 @@ function Header({ screenOpen, onScreenToggle }) {
82
120
  ${!connected ? html `<button class="reconnect" disabled=${busy} onClick=${reconnect}>${busy ? "⟳ enabling…" : "⟳ Reconnect Radar"}</button>` : null}
83
121
  <button class="themebtn" onClick=${toggleTheme} title="Toggle light / dark theme">${theme === "light" ? "🌙 Dark" : "☀ Light"}</button>
84
122
  <button class=${"screenbtn" + (screenOpen ? " on" : "")} onClick=${onScreenToggle} title="Mirror the live device screen">▣ Screen</button>
123
+ <button class=${"themebtn killbtn" + (killArmed ? " armed" : "")} disabled=${killing} onClick=${kill} title=${killArmed ? "Click again to confirm" : "Stop the dashboard server"}>${killing ? "⏻ stopping…" : killArmed ? "⏻ Confirm stop?" : "⏻ Stop dashboard"}</button>
85
124
  ${version ? html `<span class="version" title="Version of the dashboard process. It can differ from your Claude Code MCP session if a dashboard from an earlier launch still holds the port; restart the dashboard to match.">v${version}</span>` : null}
86
125
  </h1>
87
126
  `;
@@ -89,11 +128,20 @@ function Header({ screenOpen, onScreenToggle }) {
89
128
  function ModeBar() {
90
129
  const [, force] = useState(0);
91
130
  useEffect(() => store.on("spec", () => force((n) => n + 1)), []);
131
+ const deviceSources = useStoreValue(store, "sources", () => store.deviceSources);
92
132
  const activeKey = store.activeModeKey();
93
133
  const pick = (specToPush) => store.setSpec(specToPush);
134
+ const serves = (m) => modeServed(m.key, deviceSources);
135
+ // A device switch can hide the active tab (leaner build). Reset to the first tab so the
136
+ // user is never stranded on an invisible mode rendering a dead feed.
137
+ useEffect(() => {
138
+ if (activeKey && activeKey !== "__custom__" && !modeServed(activeKey, deviceSources)) {
139
+ store.setSpec(MODES[0].spec);
140
+ }
141
+ }, [deviceSources, activeKey]);
94
142
  // 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");
143
+ const streamModes = MODES.filter((m) => serves(m) && SOURCES[m.spec.source]?.kind === "stream");
144
+ const stateModes = MODES.filter((m) => serves(m) && SOURCES[m.spec.source]?.kind === "state");
97
145
  return html `
98
146
  <div class="modebar">
99
147
  ${streamModes.map((m) => html `<button class=${"modebtn" + (activeKey === m.key ? " active" : "")} onClick=${() => pick(m.spec)}>${m.label}</button>`)}
@@ -201,7 +249,8 @@ function App() {
201
249
  if (e.key !== "ArrowRight" && e.key !== "ArrowLeft" && e.key !== "h" && e.key !== "l")
202
250
  return;
203
251
  const dir = e.key === "ArrowRight" || e.key === "l" ? 1 : -1;
204
- const keys = MODES.map((m) => m.key);
252
+ // Same filter as the modebar, so the arrows cannot land on a hidden tab.
253
+ const keys = MODES.filter((m) => modeServed(m.key, store.deviceSources)).map((m) => m.key);
205
254
  if (store.lastCustomSpec)
206
255
  keys.push("__custom__");
207
256
  let cur = keys.indexOf(store.activeModeKey() || "");
@@ -235,6 +284,17 @@ function App() {
235
284
  <${DbBrowser} spec=${spec} key=${"db-" + dbResync} />
236
285
  `;
237
286
  }
287
+ else if (spec.source === "flags") {
288
+ // Feature Flags: a self-contained, point-in-time container like the DB browser (no store /
289
+ // SSE engine). key=flags so it remounts cleanly when switching to the tab.
290
+ view = html `
291
+ <div class="sub">
292
+ <span class="summary">${spec.summary || "Feature flags"}</span>
293
+ <span class="tech">source=flags (live snapshot from the running app)</span>
294
+ </div>
295
+ <${FlagsBrowser} key="flags" />
296
+ `;
297
+ }
238
298
  else if (spec.source === "prefs") {
239
299
  // The Prefs browser is a self-contained, point-in-time container: it does NOT import the store
240
300
  // (no SSE engine / timers on a tab that has no live feed). key folds in dbResync (PR #94
@@ -59,7 +59,10 @@ export function DbBrowser({ spec }) {
59
59
  setOut({ msg: "pick a table or write a query" });
60
60
  setTables(null);
61
61
  try {
62
- const r = await (await fetch("/dbtables?db=" + encodeURIComponent(name) + userQS(user) + (refresh ? "&refresh=1" : ""))).json();
62
+ const r = await (
63
+ // Authored: /dbtables pulls a plaintext copy of the device database to local disk, so
64
+ // the server refuses it without proof this is our own client.
65
+ await fetch("/dbtables?db=" + encodeURIComponent(name) + userQS(user) + (refresh ? "&refresh=1" : ""), { headers: { "X-Radar-Dashboard": "1" } })).json();
63
66
  setTables(r);
64
67
  if (!r.error)
65
68
  setMeta(name + " — " + (((r.sizeBytes ?? 0) / 1024) | 0) + " KB snapshot, " + (r.tables ?? []).length + " tables · " + profileLabel(user));
@@ -75,7 +78,10 @@ export function DbBrowser({ spec }) {
75
78
  return;
76
79
  setOut({ msg: "running…" });
77
80
  try {
78
- const r = await (await fetch("/dbquery?db=" + encodeURIComponent(db) + "&sql=" + encodeURIComponent(theSql) + userQS(user))).json();
81
+ const r = await (
82
+ // Authored for the same reason as /dbtables: queryDatabase pulls the device database to
83
+ // local disk when no copy exists yet.
84
+ await fetch("/dbquery?db=" + encodeURIComponent(db) + "&sql=" + encodeURIComponent(theSql) + userQS(user), { headers: { "X-Radar-Dashboard": "1" } })).json();
79
85
  if (r.error)
80
86
  setOut({ error: r.error });
81
87
  else if (!r.rows || !r.rows.length) {
@@ -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.