@slack/radar-mcp 1.17.1 → 1.18.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.
@@ -1,38 +1,106 @@
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.
1
+ // Feature Flags browser (source:"flags") -- a live view of the running Slack app's feature flags
2
+ // AND multi-variant experiments. Loads a point-in-time snapshot, then subscribes to the device's
3
+ // on-device observer so rows update in place as overrides/server values change. Like the DB
4
+ // browser it must NOT import the streaming store (that would start the store's own SSE engine +
5
+ // timers on this tab); it opens its OWN short-lived EventSource on /stream and closes it on
6
+ // unmount.
6
7
  //
7
8
  // Server contract (server.ts proxies to the device feature-flag RadarPlugin):
8
- // GET /flags -> { feature_flags: FlagRow[], total } | { error, feature_flags: [] }
9
+ // GET /flags -> { feature_flags: FlagRow[], total_captured } | { error, feature_flags: [] }
9
10
  //
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.
11
+ // The device unifies toggles and experiments on one route via a sealed value type, so a FlagRow
12
+ // (device list = summary, kept light) is one of two shapes distinguished by `type`:
13
+ // key flag/experiment name, e.g. "android_some_flag"
14
+ // scope which arm the value belongs to (authenticated/unauthenticated)
15
+ // org_id which signed-in org resolved the value; absent on unauthenticated rows. Two
16
+ // workspaces in different orgs both resolve as "authenticated" with their own
17
+ // value, so (scope,org_id,type,key) is what makes a row unique.
18
+ // timestamp when the device recorded this row, so one row is distinguishable from an older
19
+ // one. Named to match every other source's wire shape.
20
+ // type "toggle" | "experiment"
21
+ // enabled toggles only: the EFFECTIVE boolean the app uses right now (override if set,
22
+ // else the server value).
23
+ // group_name experiments only: the EFFECTIVE group/variant string (e.g. "treatment_a";
24
+ // "" / "control" is the baseline arm).
15
25
  // is_overridden true when a local debug override is active
16
26
  //
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.
27
+ // Live updates: the device observers push `feature_flag` frames on /api/stream (proxied to
28
+ // /stream) for BOTH kinds whenever an effective value changes: {type:"feature_flag", event:
29
+ // <summary>}. We upsert those into the row set by composite key and briefly flash the changed row.
20
30
  //
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.)
31
+ // Columns: flag | scope | org | type | value | origin. `value` = valuePill of the effective value
32
+ // (ON/OFF for toggles, a variant group pill for experiments). `origin` = Override (local) when
33
+ // is_overridden, else Server.
24
34
  import { html } from "./html.js";
25
35
  import { useState, useEffect, useCallback, useRef } from "preact/hooks";
36
+ // A row is unique per (scope, org_id, type, key), not by key alone: the device lists each key once
37
+ // per scope AND once per signed-in org, and a toggle and an experiment could share a name. Leaving
38
+ // org out collapsed two workspaces onto one row, so whichever wrote last won. `scope` is a
39
+ // two-value enum, an org id is letters/digits/underscore, and both `type` and `key` come from enum
40
+ // names, so none can contain the `::` separator and the join is collision-free. Used both to store
41
+ // rows and to key the flash map.
42
+ function rowKey(f) {
43
+ return `${f.scope ?? ""}::${f.org_id ?? ""}::${f.type ?? ""}::${f.key}`;
44
+ }
45
+ // An empty org id means the same thing as no org id, and letting both through would key them as two
46
+ // different rows: the collapse this change removes, reintroduced by a serialization detail.
47
+ function normalizeRow(f) {
48
+ if (f.org_id)
49
+ return f;
50
+ // Delete rather than set undefined: a patch spreads the frame over the stored row, and an explicit
51
+ // undefined would erase an org the row already had.
52
+ const { org_id: _dropped, ...rest } = f;
53
+ return rest;
54
+ }
55
+ // The row a frame belongs to when the frame itself carries no org. A build that does not report
56
+ // org_id cannot be keyed per org, so patch the one row that matches on everything else rather than
57
+ // inserting an orgless duplicate beside the real ones. With two or more org rows the frame is
58
+ // unattributable -- it reflects one store write in one org, so patching all of them would fabricate
59
+ // a value for an org that never reported one, and inserting an orgless row fabricates a row the
60
+ // device does not have. Null tells the caller to re-fetch the snapshot, which carries the org ids.
61
+ function keyForFrame(rows, ev) {
62
+ const exact = rowKey(ev);
63
+ if (ev.org_id || rows[exact])
64
+ return exact;
65
+ const suffix = `::${ev.type ?? ""}::${ev.key}`;
66
+ const prefix = `${ev.scope ?? ""}::`;
67
+ const siblings = Object.keys(rows).filter((k) => k.startsWith(prefix) && k.endsWith(suffix));
68
+ if (siblings.length === 1)
69
+ return siblings[0];
70
+ return siblings.length === 0 ? exact : null;
71
+ }
72
+ // Why an org cell is empty. An unauthenticated row has no org by definition; an authenticated row
73
+ // with no org means this device build does not report one, which is a different thing to a reader.
74
+ function orgTitle(f) {
75
+ if (f.org_id)
76
+ return f.timestamp ? `${f.org_id} · recorded ${new Date(f.timestamp).toLocaleTimeString()}` : f.org_id;
77
+ return f.scope === "unauthenticated"
78
+ ? "no org: the unauthenticated store has none"
79
+ : "this device build does not report org_id";
80
+ }
81
+ // The effective value to render: experiments use `group_name` (a string), toggles use `enabled`
82
+ // (a boolean). Falls back to whichever field is present so an older toggle-only build still works.
83
+ function flagValue(f) {
84
+ if (f.type === "experiment" || f.group_name !== undefined)
85
+ return f.group_name;
86
+ return f.enabled;
87
+ }
88
+ // A dimmed value needs to say WHY it is faint, or faint reads as stale/disabled -- the opposite of
89
+ // what it means here. Says only what dim means: plenty of undimmed values are single-row groups,
90
+ // so undimmed does not imply a disagreement.
91
+ const DIM_TITLE = "every row of this flag in this scope shows this same value";
26
92
  // 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.
93
+ // text pill ("" / "control" read as the off/baseline arm). `dim` mutes a value that every row of
94
+ // the flag agrees on, so a disagreement is the only full-weight value in a multi-row group.
28
95
  function valuePill(v, dim) {
96
+ // The dash shares the dim STYLING but not its meaning, so it carries its own explanation.
29
97
  if (v === undefined || v === null)
30
- return html `<span class="flagval dim">—</span>`;
98
+ return html `<span class="flagval dim" title="no value reported">—</span>`;
31
99
  if (typeof v === "boolean") {
32
- return html `<span class=${"flagval " + (v ? "on" : "off") + (dim ? " dim" : "")}>${v ? "ON" : "OFF"}</span>`;
100
+ return html `<span class=${"flagval " + (v ? "on" : "off") + (dim ? " dim" : "")} title=${dim ? DIM_TITLE : null}>${v ? "ON" : "OFF"}</span>`;
33
101
  }
34
102
  const off = v === "" || v.toLowerCase() === "control";
35
- return html `<span class=${"flagval variant " + (off ? "off" : "on") + (dim ? " dim" : "")}>${v || "—"}</span>`;
103
+ return html `<span class=${"flagval variant " + (off ? "off" : "on") + (dim ? " dim" : "")} title=${dim ? DIM_TITLE : null}>${v || "—"}</span>`;
36
104
  }
37
105
  // Why a flag has its effective value. No SERVER/LOCAL state field anymore, so origin is derived
38
106
  // purely from whether a local override is active.
@@ -41,15 +109,46 @@ function origin(f) {
41
109
  ? { label: "Override (local)", cls: "or-override" }
42
110
  : { label: "Server", cls: "or-server" };
43
111
  }
112
+ // The group a row's value is compared within for agreement dimming: same flag, same scope, same
113
+ // kind, across orgs.
114
+ function dimGroup(f) {
115
+ return `${f.scope ?? ""}::${f.type ?? ""}::${f.key}`;
116
+ }
117
+ // The kind of flag: an experiment (multi-variant group) or a boolean toggle. Mirrors flagValue():
118
+ // an explicit "experiment" type, OR an absent `type` with a `group_name` present (older build), is
119
+ // read as an experiment; anything else is a toggle.
120
+ function typeBadge(f) {
121
+ return f.type === "experiment" || f.group_name !== undefined
122
+ ? { label: "experiment", cls: "ft-experiment" }
123
+ : { label: "toggle", cls: "ft-toggle" };
124
+ }
44
125
  const FLASH_MS = 1200;
45
126
  export function FlagsBrowser() {
46
127
  // rows: the current flag set keyed by name (upserted by both the snapshot and live events).
47
128
  const [rows, setRows] = useState(null); // null = loading
48
129
  const [err, setErr] = useState(null);
49
130
  const [filter, setFilter] = useState("");
131
+ // Which minimization scope to show. Flags carry a `scope` ("authenticated"/"unauthenticated");
132
+ // default to authenticated (the common case). "all" shows both.
133
+ const [scope, setScope] = useState("authenticated");
50
134
  // keys that changed recently (drives the row flash); value is a token cleared on a timer.
51
135
  const [flashed, setFlashed] = useState({});
52
136
  const flashTimers = useRef({});
137
+ // Mirror of `rows` kept in sync at every write, so the stream handler can key a frame BEFORE
138
+ // calling setRows instead of reaching into the updater (whose timing is a hook implementation
139
+ // detail) and reading a variable it reassigned there.
140
+ const rowsRef = useRef({});
141
+ // A soft fetch in flight when the tab unmounts still resolves; without this guard it would call
142
+ // setRows on an unmounted component.
143
+ const mounted = useRef(true);
144
+ // Every authoritative write (a frame patch or an applied snapshot) bumps this. A SOFT snapshot
145
+ // that resolves after a later write is stale against the screen and is dropped rather than
146
+ // applied, so a background fetch can never revert a live frame it raced.
147
+ const writeEpoch = useRef(0);
148
+ // Last device state off the stream's _status frames. The SSE proxy self-heals a device drop
149
+ // without the browser's EventSource ever closing, so an app reinstall never fires onerror; the
150
+ // waiting -> connected transition on _status is the only signal the device came back.
151
+ const deviceState = useRef("");
53
152
  const flash = useCallback((key) => {
54
153
  setFlashed((f) => ({ ...f, [key]: (f[key] || 0) + 1 }));
55
154
  const timers = flashTimers.current;
@@ -64,24 +163,54 @@ export function FlagsBrowser() {
64
163
  delete timers[key];
65
164
  }, FLASH_MS);
66
165
  }, []);
67
- const load = useCallback(async () => {
68
- setRows(null);
69
- setErr(null);
166
+ // `soft` marks a refetch the user did not ask for (ambiguous frame, device back, poll). It keeps
167
+ // the current table on screen instead of blanking to "loading…" mid-read, and a transient
168
+ // failure keeps the stale-but-real rows rather than replacing them with an error. Returns
169
+ // whether a snapshot was actually applied, so a caller can re-arm on failure.
170
+ const load = useCallback(async (soft = false) => {
171
+ if (!soft) {
172
+ setRows(null);
173
+ setErr(null);
174
+ }
175
+ const epochAtStart = writeEpoch.current;
70
176
  try {
71
177
  const r = await (await fetch("/flags")).json();
178
+ if (!mounted.current)
179
+ return false;
72
180
  if (r.error) {
73
- setErr(r.error);
74
- setRows({});
75
- return;
181
+ if (!soft) {
182
+ setErr(r.error);
183
+ rowsRef.current = {};
184
+ setRows({});
185
+ }
186
+ return false;
187
+ }
188
+ if (soft && writeEpoch.current !== epochAtStart) {
189
+ // A frame or another snapshot landed while this fetch was in flight: this body predates
190
+ // what is on screen and applying it would revert the newer write. The poll and the next
191
+ // event reconcile whatever this snapshot alone knew.
192
+ return false;
76
193
  }
77
194
  const byKey = {};
78
- for (const fl of r.feature_flags || [])
79
- byKey[fl.key] = fl;
195
+ for (const raw of r.feature_flags || []) {
196
+ const fl = normalizeRow(raw);
197
+ byKey[rowKey(fl)] = fl;
198
+ }
199
+ writeEpoch.current++;
200
+ rowsRef.current = byKey;
201
+ setErr(null);
80
202
  setRows(byKey);
203
+ return true;
81
204
  }
82
205
  catch {
83
- setErr("network error loading feature flags");
84
- setRows({});
206
+ if (!mounted.current)
207
+ return false;
208
+ if (!soft) {
209
+ setErr("network error loading feature flags");
210
+ rowsRef.current = {};
211
+ setRows({});
212
+ }
213
+ return false;
85
214
  }
86
215
  }, []);
87
216
  // initial snapshot
@@ -99,28 +228,144 @@ export function FlagsBrowser() {
99
228
  catch {
100
229
  return;
101
230
  }
231
+ if (f.type === "_status") {
232
+ const state = f.event?.state;
233
+ // The device came back (reinstall, sleep, re-arm): rows it dropped or re-orged while away
234
+ // never produce frames, so re-pull the snapshot. The first "connected" of the session is
235
+ // not a comeback and does not refetch.
236
+ if (state === "connected" && deviceState.current && deviceState.current !== "connected") {
237
+ load(true);
238
+ }
239
+ if (state)
240
+ deviceState.current = state;
241
+ return;
242
+ }
243
+ if (f.type === "feature_flag_evict") {
244
+ // The device dropped an org's rows on sign-out (wire revision 4); mirror it. Rows that
245
+ // never produce another frame would otherwise read as live state forever.
246
+ const org = f.event?.org_id;
247
+ if (!org)
248
+ return;
249
+ const kept = {};
250
+ for (const [key, row] of Object.entries(rowsRef.current)) {
251
+ if (row.org_id !== org)
252
+ kept[key] = row;
253
+ }
254
+ writeEpoch.current++;
255
+ rowsRef.current = kept;
256
+ setRows(kept);
257
+ return;
258
+ }
102
259
  if (f.type !== "feature_flag" || !f.event || !f.event.key)
103
260
  return;
104
- const ev = f.event;
105
- setRows((prev) => ({ ...(prev || {}), [ev.key]: { ...(prev && prev[ev.key]), ...ev } }));
106
- flash(ev.key);
261
+ const ev = normalizeRow(f.event);
262
+ const k = keyForFrame(rowsRef.current, ev);
263
+ if (k === null) {
264
+ // Unattributable: an orgless frame over several org rows. Frames and snapshot rows are
265
+ // the same device serialization, so org_id is in both or neither on any single build;
266
+ // reaching here takes a mid-session reinstall across two different builds, and the
267
+ // _status comeback refetch re-pulls the snapshot on exactly that path. Drop the frame.
268
+ return;
269
+ }
270
+ // A plain value set, not an updater: rowsRef is the read source, so state and mirror move
271
+ // together and nothing depends on when a hook runs its updater.
272
+ writeEpoch.current++;
273
+ const next = { ...rowsRef.current, [k]: { ...rowsRef.current[k], ...ev } };
274
+ rowsRef.current = next;
275
+ setRows(next);
276
+ flash(k);
277
+ };
278
+ // The tab works without live updates, but rows written before an outage go stale silently, so
279
+ // re-pull the snapshot once the stream recovers (reconnecting is the browser's job). Soft: a
280
+ // recovery the user never asked for must not blank the table or trade real rows for an error.
281
+ let down = false;
282
+ es.onerror = () => {
283
+ down = true;
284
+ };
285
+ es.onopen = () => {
286
+ if (down) {
287
+ down = false;
288
+ load(true);
289
+ }
107
290
  };
108
- // The tab works without live updates; a stream error just means no live patching.
109
- es.onerror = () => { };
110
291
  return () => es.close();
111
- }, [flash]);
112
- // clear any pending flash timers on unmount
292
+ }, [flash, load]);
293
+ // clear pending flash timers on unmount, and stop in-flight soft fetches from landing setRows
113
294
  useEffect(() => () => {
295
+ mounted.current = false;
114
296
  for (const t of Object.values(flashTimers.current))
115
297
  clearTimeout(t);
116
298
  }, []);
117
- const all = rows ? Object.values(rows).sort((a, b) => a.key.localeCompare(b.key)) : [];
299
+ // Sort down to every key component, so the rows of one key keep the same order between refreshes
300
+ // and a reader comparing them by eye is not comparing a moving target.
301
+ const everything = rows
302
+ ? Object.values(rows).sort((a, b) => a.key.localeCompare(b.key) ||
303
+ (a.scope ?? "").localeCompare(b.scope ?? "") ||
304
+ (a.type ?? "").localeCompare(b.type ?? "") ||
305
+ (a.org_id ?? "").localeCompare(b.org_id ?? ""))
306
+ : [];
307
+ // Tab labels count distinct FLAGS, not rows: a key repeats once per org, so a row count next to
308
+ // a by-name filter reads as the device double-reporting. The meta line carries the row count.
309
+ // A flag is (type, key) here exactly as in the MCP tools' total_flags, and a row with no scope
310
+ // counts as authenticated, matching the row filter below.
311
+ const flagId = (x) => `${x.type ?? ""}::${x.key}`;
312
+ const authCount = new Set(everything.filter((x) => (x.scope || "authenticated") === "authenticated").map(flagId)).size;
313
+ const unauthCount = new Set(everything.filter((x) => x.scope === "unauthenticated").map(flagId)).size;
314
+ const all = scope === "all" ? everything : everything.filter((x) => (x.scope || "authenticated") === scope);
118
315
  const f = filter.trim().toLowerCase();
119
316
  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";
317
+ // Named, not counted, and over the rows actually on screen: filtering to one key is the reason to
318
+ // open this tab, so that is exactly when a reader needs to know which orgs they are looking at. A
319
+ // reader who knows two workspaces are signed in can also see that only one of them reported.
320
+ const orgsInView = [...new Set(shown.filter((x) => x.org_id).map((x) => x.org_id))].sort();
321
+ // Two names at most in the bar; the meta span's title carries the full list. Org ids are long
322
+ // and .flagsmeta does not wrap.
323
+ const orgNames = orgsInView.length > 2
324
+ ? `${orgsInView.slice(0, 2).join(", ")} +${orgsInView.length - 2} more`
325
+ : orgsInView.join(", ");
326
+ const orgSuffix = orgsInView.length ? ` · ${orgNames}` : "";
327
+ // An authenticated row with no org is one fact about the device, said once here rather than once
328
+ // per row; the cell shows a dash either way and its tooltip tells an old build apart from the
329
+ // unauthenticated scope. "older build" is a claim about the BUILD, so it derives from everything
330
+ // the tab knows, never from the filtered view -- filtering down to one orgless flag must not
331
+ // diagnose a build that demonstrably reports orgs.
332
+ const orglessAuth = shown.some((x) => !x.org_id && (x.scope || "authenticated") === "authenticated");
333
+ const anyOrgAnywhere = everything.some((x) => x.org_id);
334
+ const buildNote = !orglessAuth ? "" : anyOrgAnywhere ? " · no org data on some rows" : " · no org data (older build)";
335
+ const rowNoun = all.length === 1 ? " row" : " rows";
336
+ const meta = rows == null
337
+ ? ""
338
+ : (f ? shown.length + " / " + all.length + " shown" : all.length + rowNoun) + orgSuffix + buildNote;
339
+ // Keys whose rows within one scope and type resolve to more than one value. Everything else in a
340
+ // multi-row group agrees, and agreement is dimmed so a real disagreement is the only full-weight
341
+ // value. Type is part of the group, or a toggle and an experiment sharing a name would read as a
342
+ // permanent disagreement (a boolean never equals a variant string). One pass builds both the
343
+ // value set and the row count per group.
344
+ const valuesByKey = new Map();
345
+ const rowsByKey = new Map();
346
+ for (const x of shown) {
347
+ const k = dimGroup(x);
348
+ const seen = valuesByKey.get(k) ?? new Set();
349
+ seen.add(flagValue(x));
350
+ valuesByKey.set(k, seen);
351
+ rowsByKey.set(k, (rowsByKey.get(k) ?? 0) + 1);
352
+ }
353
+ const dimmedGroups = new Set([...valuesByKey.entries()]
354
+ .filter(([k, v]) => v.size === 1 && (rowsByKey.get(k) ?? 0) > 1)
355
+ .map(([k]) => k));
121
356
  return html `
122
357
  <div class="flagsview">
123
358
  <div class="flagsbar">
359
+ <span class="scopetabs">
360
+ ${["authenticated", "unauthenticated", "all"].map((s) => {
361
+ const label = s === "authenticated" ? `authenticated (${authCount})` : s === "unauthenticated" ? `unauthenticated (${unauthCount})` : "all";
362
+ return html `<button
363
+ class=${"scopetab" + (scope === s ? " sel" : "")}
364
+ title=${s === "all" ? null : "distinct flags in this scope; the meta line counts rows"}
365
+ onClick=${() => setScope(s)}
366
+ >${label}</button>`;
367
+ })}
368
+ </span>
124
369
  <span class="ffilterwrap">
125
370
  <input
126
371
  class="ffilter"
@@ -135,7 +380,7 @@ export function FlagsBrowser() {
135
380
  />
136
381
  ${filter ? html `<span class="ffilterclear" title="clear filter" onClick=${() => setFilter("")}>✕</span>` : null}
137
382
  </span>
138
- <span class="flagsmeta">${meta}</span>
383
+ <span class="flagsmeta" title=${orgsInView.length ? orgsInView.join(", ") : null}>${meta}</span>
139
384
  <button class="flagsrefresh" title="re-fetch the snapshot" onClick=${() => load()}>↻ refresh</button>
140
385
  </div>
141
386
  <div class="dbout flagsout">
@@ -143,21 +388,30 @@ export function FlagsBrowser() {
143
388
  ? html `<div class="msg">loading…</div>`
144
389
  : err
145
390
  ? html `<div class="msg err">${err}</div>`
146
- : !all.length
391
+ : !everything.length
147
392
  ? 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} />`}
393
+ : !all.length
394
+ ? html `<div class="msg">no ${scope} flags</div>`
395
+ : !shown.length
396
+ ? html `<div class="msg">no flags match “${filter}”</div>`
397
+ : html `<${Table}
398
+ rows=${shown}
399
+ flashed=${flashed}
400
+ dimmed=${dimmedGroups}
401
+ />`}
151
402
  </div>
152
403
  </div>
153
404
  `;
154
405
  }
155
- function Table({ rows, flashed }) {
406
+ function Table({ rows, flashed, dimmed, }) {
156
407
  return html `
157
408
  <table>
158
409
  <thead>
159
410
  <tr>
160
411
  <th>flag</th>
412
+ <th class="scope">scope</th>
413
+ <th class="org">org</th>
414
+ <th class="ftype">type</th>
161
415
  <th class="val">value</th>
162
416
  <th class="origin">origin</th>
163
417
  </tr>
@@ -165,11 +419,15 @@ function Table({ rows, flashed }) {
165
419
  <tbody>
166
420
  ${rows.map((x) => {
167
421
  const o = origin(x);
422
+ const t = typeBadge(x);
168
423
  const ov = x.is_overridden === true;
169
- const cls = (ov ? "overridden" : "") + (flashed[x.key] ? " flash" : "");
424
+ const cls = (ov ? "overridden" : "") + (flashed[rowKey(x)] ? " flash" : "");
170
425
  return html `<tr class=${cls}>
171
426
  <td class="key" title=${x.key}>${x.key}</td>
172
- <td class="val">${valuePill(x.enabled)}</td>
427
+ <td class="scope">${x.scope || "—"}</td>
428
+ <td class="org" title=${orgTitle(x)}>${x.org_id || "—"}</td>
429
+ <td class="ftype"><span class=${"ftbadge " + t.cls}>${t.label}</span></td>
430
+ <td class="val">${valuePill(flagValue(x), dimmed.has(dimGroup(x)))}</td>
173
431
  <td class="origin"><span class=${"orbadge " + o.cls}>${o.label}</span></td>
174
432
  </tr>`;
175
433
  })}
@@ -13,6 +13,14 @@ const STREAM_FPS = 20;
13
13
  function streamSrc() {
14
14
  return "/screen/stream?fps=" + STREAM_FPS + "&t=" + Date.now();
15
15
  }
16
+ function snapshotSrc() {
17
+ return "/screen/shot?inline=1&t=" + Date.now();
18
+ }
19
+ // The only control that clears a stuck device-side screenrecord ON DEMAND, hence a visible label.
20
+ // The Android title names the recording kill because "reset the mirror" does not imply it; other
21
+ // platforms' redetect only re-probes, so their title must not claim it.
22
+ const REDETECT_TITLE_ANDROID = "Re-detect the display and reset the mirror. Also stops Radar's screen recording on the device.";
23
+ const REDETECT_TITLE = "Re-detect the display and reset the mirror.";
16
24
  export function ScreenOverlay({ open, onClose }) {
17
25
  const [caps, setCaps] = useState(null);
18
26
  const [consent, setConsent] = useState(false);
@@ -134,6 +142,7 @@ export function ScreenOverlay({ open, onClose }) {
134
142
  }, [announceFailure, announceSave]);
135
143
  const stopAndSave = useCallback(async () => {
136
144
  setRecording(false);
145
+ setHint("stopping recording…");
137
146
  await requestSave("/screen/record/stop", "recording", "nothing to save (recording was too short or never started)");
138
147
  }, [requestSave]);
139
148
  // Stop + save a running recording when the panel closes. Without this, closing the panel
@@ -182,6 +191,46 @@ export function ScreenOverlay({ open, onClose }) {
182
191
  const id = setTimeout(() => setPlainHint("live. ▣ Screen again to close."), 3500);
183
192
  return () => clearTimeout(id);
184
193
  }
194
+ if (caps && caps.snapshotCast && imgRef.current) {
195
+ let failures = 0;
196
+ let inflight = false;
197
+ let currentUrl = null;
198
+ const img = imgRef.current;
199
+ const refresh = async () => {
200
+ if (inflight || !img)
201
+ return;
202
+ inflight = true;
203
+ try {
204
+ const r = await fetch(snapshotSrc());
205
+ if (!r.ok)
206
+ throw new Error();
207
+ const blob = await r.blob();
208
+ const url = URL.createObjectURL(blob);
209
+ if (currentUrl)
210
+ URL.revokeObjectURL(currentUrl);
211
+ currentUrl = url;
212
+ img.src = url;
213
+ failures = 0;
214
+ img.classList.remove("stale");
215
+ }
216
+ catch {
217
+ failures++;
218
+ if (failures >= 3)
219
+ img.classList.add("stale");
220
+ }
221
+ finally {
222
+ inflight = false;
223
+ }
224
+ };
225
+ refresh();
226
+ const id = setInterval(refresh, 1000);
227
+ setPlainHint("simulator mirror (refreshes every second). ▣ Screen again to close.");
228
+ return () => {
229
+ clearInterval(id);
230
+ if (currentUrl)
231
+ URL.revokeObjectURL(currentUrl);
232
+ };
233
+ }
185
234
  }, [open, consent, caps, setPlainHint]);
186
235
  const accept = useCallback(async () => {
187
236
  try {
@@ -211,13 +260,24 @@ export function ScreenOverlay({ open, onClose }) {
211
260
  }
212
261
  }, [consent, saving, requestSave, setPlainHint]);
213
262
  const rec = useCallback(async () => {
214
- if (!consent || !(caps && caps.liveCast)) {
263
+ if (!consent || !(caps && (caps.recording ?? caps.liveCast))) {
215
264
  setPlainHint("recording needs ffmpeg + consent");
216
265
  return;
217
266
  }
218
267
  if (!recording) {
219
- setRecording(true);
220
- await fetch("/screen/record/start", { method: "POST", headers: { "X-Radar-Dashboard": "1" } }).catch(() => { });
268
+ try {
269
+ const response = await fetch("/screen/record/start", { method: "POST", headers: { "X-Radar-Dashboard": "1" } });
270
+ const result = await response.json().catch(() => ({}));
271
+ if (!response.ok || !result.ok) {
272
+ setHint(result.error || "recording failed to start");
273
+ return;
274
+ }
275
+ setRecording(true);
276
+ setHint("recording…");
277
+ }
278
+ catch {
279
+ setHint("recording failed to start");
280
+ }
221
281
  }
222
282
  else {
223
283
  await stopAndSave();
@@ -234,9 +294,14 @@ export function ScreenOverlay({ open, onClose }) {
234
294
  const r = await (await fetch("/screen/redetect", { headers: { "X-Radar-Dashboard": "1" } }))
235
295
  .json()
236
296
  .catch(() => ({}));
237
- if (consent && caps && caps.liveCast && imgRef.current)
238
- imgRef.current.src = streamSrc();
239
- setPlainHint("display: " + (r.display || "default"));
297
+ if (r.error) {
298
+ setPlainHint(r.error);
299
+ }
300
+ else {
301
+ if (consent && caps && caps.liveCast && imgRef.current)
302
+ imgRef.current.src = streamSrc();
303
+ setPlainHint("display: " + (r.display || "default"));
304
+ }
240
305
  }, [consent, caps, setPlainHint]);
241
306
  if (!open)
242
307
  return null;
@@ -244,7 +309,7 @@ export function ScreenOverlay({ open, onClose }) {
244
309
  if (!consent) {
245
310
  body = html `
246
311
  <div class="scconsent">
247
- This mirrors the <b>live device screen</b>. It shows whatever is on the phone right now,
312
+ This mirrors the <b>live device screen</b>. It shows whatever is on the device right now,
248
313
  including open DMs, message content, and notifications. Review what is on screen before
249
314
  sharing it. Frames are not requested until you accept, and the mirror stays on until you
250
315
  restart the dashboard. If you <b>record</b>, the clip is saved to a file on this computer
@@ -253,8 +318,8 @@ export function ScreenOverlay({ open, onClose }) {
253
318
  </div>
254
319
  `;
255
320
  }
256
- else if (caps && caps.liveCast) {
257
- body = html `<img id="screenimg" ref=${imgRef} alt="device screen" onError=${() => setPlainHint("stream dropped (device disconnected?). ⟳ to retry.")} />`;
321
+ else if (caps && (caps.liveCast || caps.snapshotCast)) {
322
+ body = html `<img id="screenimg" ref=${imgRef} alt="device screen" onError=${() => setPlainHint("stream dropped (device disconnected?). reset to retry.")} />`;
258
323
  }
259
324
  else {
260
325
  const cmd = caps && caps.installHint;
@@ -274,8 +339,8 @@ export function ScreenOverlay({ open, onClose }) {
274
339
  <div class="schead">
275
340
  <span class="sctitle">Device screen</span>
276
341
  <button class="scbtn" onClick=${shot} disabled=${saving} title="Full-resolution screenshot">📷</button>
277
- <button class=${"scbtn" + (recording ? " rec" : "")} onClick=${rec} disabled=${saving} title="Record to mp4">${recording ? "■ stop" : "● rec"}</button>
278
- <button class="scbtn" onClick=${redetect} title="Re-detect the active display">⟳</button>
342
+ <button class=${"scbtn" + (recording ? " rec" : "")} disabled=${saving || (!!caps && !(caps.recording ?? caps.liveCast))} onClick=${rec} title="Record to mp4">${recording ? "■ stop" : "● rec"}</button>
343
+ <button class="scbtn" onClick=${redetect} title=${caps?.platform === "android" ? REDETECT_TITLE_ANDROID : REDETECT_TITLE}>⟳ reset</button>
279
344
  <button class="scbtn" onClick=${onClose} title="Close">✕</button>
280
345
  </div>
281
346
  <div
@@ -33,7 +33,7 @@ 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
+ { 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" } },
37
37
  ];
38
38
  // Dashboard mode key -> the ping `sources` name that must be present for the tab to work. Only
39
39
  // sources the device ships as plugins are gateable; the rest (network/db/prefs/...) always show,
@@ -1,7 +1,7 @@
1
1
  import http from "http";
2
+ import { type DashboardScreenController } from "../shared/dashboard-screen.js";
2
3
  import type { ProcessState } from "../shared/transport.js";
3
4
  import { type LogFrame } from "./log-session.js";
4
- import { stopRecording, getLive } from "../shared/screen.js";
5
5
  declare const WEB_PORT: number;
6
6
  /**
7
7
  * Decide whether to drop a log frame under backpressure. LIVE frames are dropped
@@ -89,8 +89,7 @@ export declare function getPresenceState(): {
89
89
  /** Reset presence between tests (module state is a process singleton). */
90
90
  export declare function resetPresenceForTest(): void;
91
91
  interface ShutdownDeps {
92
- getLive?: typeof getLive;
93
- stopRecording?: typeof stopRecording;
92
+ screen?: Pick<DashboardScreenController, "isRecording" | "stopRecording">;
94
93
  exit?: (code: number) => void;
95
94
  log?: (msg: string) => void;
96
95
  }