@slack/radar-mcp 1.11.0 → 1.12.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.
@@ -0,0 +1,200 @@
1
+ // Smart text filter for the feed. Parses the filter-box query ONCE into a predicate that the
2
+ // feed runs over searchText(ev) per row. Compiling here keeps regexes out of the hot path: the
3
+ // predicate runs over up to 100k ring entries on a rebuild and per-frame (~400/s) while
4
+ // tailing, so per-row work must be a few .includes()/.test() calls, never a re-parse.
5
+ //
6
+ // Syntax (space-separated terms AND together):
7
+ // term case-insensitive substring (the old behavior; muscle memory keeps working).
8
+ // A bare term also matches when it EQUALS the row kind passed to test(),
9
+ // see the kind parameter below.
10
+ // -term exclude rows matching term
11
+ // /pattern/ regex term (case-insensitive); -/pattern/ excludes by regex
12
+ // /pat/flags trailing flags are honored for the short flag strings people actually type
13
+ // (1-2 letters from i/m/s/g, no repeats; g is stripped because a stateful
14
+ // lastIndex across .test() calls would make matches flicker). Any other tail
15
+ // (junk, a path segment like users/id, three or more letters) becomes part
16
+ // of the pattern as best-effort regex, so pasted paths like /api/users and
17
+ // flag-typos like /error/x keep matching literally. The ambiguity is inherent
18
+ // (/api/im reads as both regex + flags and regex + path). Every judgment call
19
+ // on an ambiguous /…/tail is reported in `hints` so the reading is visible,
20
+ // never silent.
21
+ // "a b" quoted phrase, matches the space literally; -"a b" excludes the phrase.
22
+ // Quoting is also the escape hatch for a literal leading - or /.
23
+ //
24
+ // An invalid or incomplete regex (e.g. "/foo(" mid-typing) never throws and never filters:
25
+ // that term goes INERT (matches everything) and parse() reports it in `invalid` so the box can
26
+ // show a soft warning state. Degrading to inert, not substring, is deliberate: treating "/fo("
27
+ // as a literal substring would blank the feed while typing, which reads as data loss.
28
+ // Frozen (object and all nested arrays) so the shared match-all result handed out for every
29
+ // empty query cannot be mutated by a consumer.
30
+ const MATCH_ALL = Object.freeze({
31
+ test: () => true,
32
+ invalid: Object.freeze([]),
33
+ hints: Object.freeze([]),
34
+ empty: true,
35
+ });
36
+ // Split the query into raw term tokens: whitespace-separated, but /…/ and "…" spans (with an
37
+ // optional leading -) stay one token even when they contain spaces. An unterminated span runs
38
+ // to the end of the query.
39
+ export function tokenize(query) {
40
+ const tokens = [];
41
+ let i = 0;
42
+ const n = query.length;
43
+ while (i < n) {
44
+ while (i < n && /\s/.test(query[i]))
45
+ i++;
46
+ if (i >= n)
47
+ break;
48
+ const start = i;
49
+ if (query[i] === "-")
50
+ i++;
51
+ const open = query[i];
52
+ if (open === "/" || open === '"') {
53
+ i++;
54
+ while (i < n && query[i] !== open)
55
+ i++;
56
+ if (i < n)
57
+ i++; // consume the closer
58
+ // trailing non-space glue (flags, or the rest of a pasted path) stays part of the token
59
+ while (i < n && !/\s/.test(query[i]))
60
+ i++;
61
+ }
62
+ else {
63
+ while (i < n && !/\s/.test(query[i]))
64
+ i++;
65
+ }
66
+ tokens.push(query.slice(start, i));
67
+ }
68
+ return tokens;
69
+ }
70
+ // A term is committable as a pill when non-empty, not a bare "-", and any opened /…/ or "…"
71
+ // span is CLOSED. Reuses the tokenizer's span logic (same rules: an optional leading -, then
72
+ // the first / or " opens a span that must be closed by the same character). Terms with no span
73
+ // opener are always complete (a bare word, or /foo/tail once the closer is past).
74
+ export function isCompleteTerm(raw) {
75
+ if (!raw)
76
+ return false;
77
+ let i = 0;
78
+ if (raw[i] === "-")
79
+ i++;
80
+ if (i === raw.length)
81
+ return false; // a bare "-" while typing is not committable
82
+ const open = raw[i];
83
+ if (open !== "/" && open !== '"')
84
+ return true; // no span, so complete
85
+ i++;
86
+ while (i < raw.length && raw[i] !== open)
87
+ i++;
88
+ return i < raw.length; // true only when the closer was found
89
+ }
90
+ // A tail reads as regex flags only when it is the short flag string fingers actually type:
91
+ // 1-2 letters from i/m/s/g with no repeats. Longer or letter-repeating tails (img, ims, sms)
92
+ // and anything outside the set (id, dm, us, svg, junk) read as part of a pasted path instead.
93
+ function asFlagTail(tail) {
94
+ if (!/^[gims]{1,2}$/.test(tail))
95
+ return null;
96
+ if (tail.length === 2 && tail[0] === tail[1])
97
+ return null;
98
+ return tail;
99
+ }
100
+ function compileTerm(raw, invalid, hints, kinds) {
101
+ let negate = false;
102
+ let body = raw;
103
+ if (body.startsWith("-")) {
104
+ negate = true;
105
+ body = body.slice(1);
106
+ }
107
+ if (!body)
108
+ return null; // a bare "-" while typing: inert
109
+ if (body[0] === "/") {
110
+ // Three shapes: /pat/ (closed), /pat/flags (short flag tail), or best-effort (everything
111
+ // after the leading slash is ONE pattern: mid-typing, or a pasted path like /api/users).
112
+ // The flags-vs-path ambiguity is inherent (/api/im is both), so whichever way an ambiguous
113
+ // tail is read, the reading lands in `hints` and quoting is the documented escape hatch.
114
+ let src;
115
+ let rawFlags = "";
116
+ if (body.length >= 2 && body.endsWith("/")) {
117
+ src = body.slice(1, -1);
118
+ }
119
+ else {
120
+ const lastSlash = body.lastIndexOf("/");
121
+ const tail = lastSlash > 0 ? body.slice(lastSlash + 1) : "";
122
+ const flags = tail ? asFlagTail(tail) : null;
123
+ if (flags) {
124
+ src = body.slice(1, lastSlash);
125
+ rawFlags = flags;
126
+ hints.push(`${raw} read as regex "${src}" with flags "${flags}". Quote it to match the text literally`);
127
+ }
128
+ else {
129
+ src = body.slice(1);
130
+ if (lastSlash > 0) {
131
+ hints.push(`${raw} read as one regex "${src}". Quote it to match the text literally`);
132
+ }
133
+ }
134
+ }
135
+ if (!src)
136
+ return null; // "/" or "//" while typing: inert
137
+ let flags = rawFlags.replace(/g/g, "");
138
+ if (!flags.includes("i"))
139
+ flags += "i";
140
+ try {
141
+ const re = new RegExp(src, flags);
142
+ return { negate, test: (t) => re.test(t) };
143
+ }
144
+ catch {
145
+ invalid.push(raw);
146
+ return null; // invalid regex: inert, reported
147
+ }
148
+ }
149
+ if (body[0] === '"') {
150
+ const closed = body.length >= 2 && body[body.length - 1] === '"';
151
+ const phrase = (closed ? body.slice(1, -1) : body.slice(1)).toLowerCase();
152
+ if (!phrase)
153
+ return null;
154
+ return { negate, test: (t) => t.includes(phrase) };
155
+ }
156
+ const needle = body.toLowerCase();
157
+ if (negate && kinds.has(needle)) {
158
+ // A negated KIND NAME excludes by row type ONLY when kind matching is active (the Live
159
+ // view passes kind). Substring must not participate: "-log" would otherwise also hide
160
+ // any clog whose text contains "log" (logout_success, app_login), which is exactly the
161
+ // silent data loss kind matching exists to prevent. On single-source tabs (kind
162
+ // undefined) it falls back to plain substring exclusion, same as any other term.
163
+ return { negate, test: (t, kind) => (kind !== undefined ? kind === needle : t.includes(needle)) };
164
+ }
165
+ return { negate, test: (t, kind) => t.includes(needle) || kind === needle };
166
+ }
167
+ /**
168
+ * Parse a filter-box query into a compiled predicate. Call on filter CHANGE only (the result
169
+ * is stable for a given query); run `parsed.test(searchText(ev), kind?)` per row.
170
+ * `kindNames` is the vocabulary of row-type names ("log", "clog", …) that get kind semantics;
171
+ * the caller owns it (registry's STREAM_KINDS) so this module stays pure and dependency-free.
172
+ */
173
+ export function parseFilter(query, kindNames) {
174
+ const q = (query || "").trim();
175
+ if (!q)
176
+ return MATCH_ALL;
177
+ const kinds = new Set(kindNames || []);
178
+ const invalid = [];
179
+ const hints = [];
180
+ const terms = [];
181
+ for (const raw of tokenize(q)) {
182
+ const t = compileTerm(raw, invalid, hints, kinds);
183
+ if (t)
184
+ terms.push(t);
185
+ }
186
+ if (!terms.length)
187
+ return { test: () => true, invalid, hints, empty: true };
188
+ return {
189
+ test: (text, kind) => {
190
+ for (const t of terms) {
191
+ if (t.test(text, kind) === t.negate)
192
+ return false;
193
+ }
194
+ return true;
195
+ },
196
+ invalid,
197
+ hints,
198
+ empty: false,
199
+ };
200
+ }
@@ -0,0 +1,399 @@
1
+ // Prefs browser (source:"prefs") -- read-only on-device SharedPreferences browser: file list ->
2
+ // entries, with a profile picker on dual-profile devices. Mirrors db.ts exactly: file list on
3
+ // the left, entries in the main pane, dual-profile picker, privacy banner. Server contract:
4
+ // /prefs?user= -> { user, available_users: string[], files: {name,size}[] } | { error, files:[], available_users:[] }
5
+ // /prefsread?file=&user=&keys= -> { file, user, entries: {key,type,value}[], device_read_truncated?, total_entries, returned_entries } | { error }
6
+ // /prefssearch?query=&user= -> { query, user, available_users, results, truncated?, skipped?: string[] }
7
+ //
8
+ // IMPORTANT (plan requirement): this module must NOT import the streaming store. The Prefs tab is
9
+ // point-in-time, not a live feed; pulling the store would start the SSE engine + timers on a
10
+ // tab that has no use for them. It carries its own keyboard nav since there is no Feed here.
11
+ import { html } from "./html.js";
12
+ import { useState, useEffect, useCallback, useRef } from "preact/hooks";
13
+ import { useLatestRef, useGlobalKeydown } from "./hooks.js";
14
+ import { highlightJson } from "./inspector.js";
15
+ function profileLabel(u) {
16
+ return u === "" || u == null ? "device" : u === "0" ? "personal (user 0)" : "secondary (user " + u + ")";
17
+ }
18
+ // Badge for feature-flag prefs files
19
+ function isFfFile(name) {
20
+ return name.startsWith("debug_features_") || name.startsWith("easy_features_") || name.startsWith("feature_flags_");
21
+ }
22
+ // `(size/1024)|0` truncates every file under 1024 bytes to a flat, indistinguishable "0 KB" --
23
+ // on a real device a third-plus of the files are that small (locale_prefs, security prefs,
24
+ // small per-team overrides), so the list read as broken/unsorted rather than correctly sorted
25
+ // with tiny files at the bottom. Show exact bytes below 1KB, one decimal of KB below 10KB
26
+ // (rounds small-but-real files like "1.8 KB" instead of collapsing to "1 KB"), whole KB above.
27
+ function formatSize(bytes) {
28
+ if (bytes < 1024)
29
+ return bytes + " B";
30
+ if (bytes < 10240)
31
+ return (bytes / 1024).toFixed(1) + " KB";
32
+ return Math.round(bytes / 1024) + " KB";
33
+ }
34
+ // Below this, a file is functionally empty (a handful of scalar entries at most) -- muted in
35
+ // the list so attention goes to the files worth opening, without hiding them entirely.
36
+ const TINY_FILE_BYTES = 200;
37
+ export function PrefsBrowser({ spec }) {
38
+ const [user, setUser] = useState(null);
39
+ const [files, setFiles] = useState(null); // null = loading
40
+ const [selectedFile, setSelectedFile] = useState(null);
41
+ const [entries, setEntries] = useState(null); // null = loading
42
+ const [searchQuery, setSearchQuery] = useState("");
43
+ const [searchResults, setSearchResults] = useState(null);
44
+ const [searching, setSearching] = useState(false);
45
+ const [meta, setMeta] = useState("");
46
+ // Keyboard nav covers the FILE LIST only (j/k + Enter to open). The entries pane is
47
+ // mouse-driven: it had a keyboard highlight once, but a green outline landing on an
48
+ // arbitrary row read as a rendering glitch, so entries keyboard nav was removed.
49
+ const [fileIdx, setFileIdx] = useState(0);
50
+ // Which row (by flat index across all visible PrefsGrid instances) is expanded to show its
51
+ // full value. Owned here so ONE index can address a row inside whichever of the (possibly
52
+ // several, one per matching search file) PrefsGrid instances renders it.
53
+ const [expandedIdx, setExpandedIdx] = useState(null);
54
+ // Bumped on every pickFile/search call so a slower, now-stale fetch cannot land after a newer
55
+ // one already resolved or after the user clicked away -- e.g. clicking a file while a search
56
+ // is still in flight must not let the search response overwrite the file's entries once it
57
+ // finally arrives (the pane/searching state would otherwise say "not searching" while a search
58
+ // result still shows up a moment later).
59
+ const requestIdRef = useRef(0);
60
+ const userQS = useCallback((u) => (u != null ? "&user=" + encodeURIComponent(u) : ""), []);
61
+ const loadFiles = useCallback(async (u) => {
62
+ setFiles(null);
63
+ try {
64
+ const r = await (await fetch("/prefs?" + (u != null ? "user=" + encodeURIComponent(u) : ""))).json();
65
+ setFiles(r);
66
+ if (!r.error)
67
+ setUser(r.user ?? null);
68
+ }
69
+ catch (e) {
70
+ setFiles({ error: "network error loading preferences files" });
71
+ }
72
+ }, []);
73
+ // initial load
74
+ useEffect(() => {
75
+ loadFiles(null);
76
+ }, []);
77
+ // keep the keyboard highlight in range when the file list changes
78
+ useEffect(() => {
79
+ const count = (files && files.files) ? files.files.length : 0;
80
+ setFileIdx((i) => Math.max(0, Math.min(count - 1, i)));
81
+ }, [files]);
82
+ const pickFile = useCallback(async (name) => {
83
+ // Picking a file always wins over an in-flight search: bump the request token so that
84
+ // search's eventual response (if any) is discarded on arrival, and drop the "searching"
85
+ // spinner immediately rather than leaving it spinning for a search the user just abandoned.
86
+ const myRequestId = ++requestIdRef.current;
87
+ setSelectedFile(name);
88
+ setSearchQuery("");
89
+ setSearchResults(null);
90
+ setSearching(false);
91
+ setEntries(null);
92
+ try {
93
+ const r = await (await fetch("/prefsread?file=" + encodeURIComponent(name) + userQS(user))).json();
94
+ if (requestIdRef.current !== myRequestId)
95
+ return; // superseded by a newer click
96
+ setEntries(r);
97
+ if (!r.error) {
98
+ const note = r.device_read_truncated ? " (device 256KB cap)" : "";
99
+ setMeta(name + " — " + (r.returned_entries ?? 0) + " of " + (r.total_entries ?? 0) + " entries" + note + " · " + profileLabel(user));
100
+ }
101
+ }
102
+ catch (e) {
103
+ if (requestIdRef.current !== myRequestId)
104
+ return;
105
+ setEntries({ error: "network error loading preferences" });
106
+ }
107
+ }, [user, userQS]);
108
+ const search = useCallback(async (q) => {
109
+ const myRequestId = ++requestIdRef.current;
110
+ if (!q) {
111
+ setSearchQuery("");
112
+ setSearchResults(null);
113
+ setSearching(false);
114
+ return;
115
+ }
116
+ setSearchQuery(q);
117
+ setSearching(true);
118
+ try {
119
+ const r = await (await fetch("/prefssearch?query=" + encodeURIComponent(q) + userQS(user))).json();
120
+ // A file click (or a newer search) superseded this request while it was in flight --
121
+ // discard the result instead of overwriting whatever the user has since selected.
122
+ if (requestIdRef.current !== myRequestId)
123
+ return;
124
+ setSearchResults(r);
125
+ setSearching(false);
126
+ if (!r.error) {
127
+ const note = r.skipped && r.skipped.length ? " (" + r.skipped.length + " files could not be read)" : "";
128
+ setMeta("search: " + q + " — " + (r.results?.length ?? 0) + " files" + note + " · " + profileLabel(user));
129
+ }
130
+ }
131
+ catch (e) {
132
+ if (requestIdRef.current !== myRequestId)
133
+ return;
134
+ setSearchResults({ error: "network error searching preferences" });
135
+ setSearching(false);
136
+ }
137
+ }, [user, userQS]);
138
+ const sideRef = useRef(null);
139
+ useEffect(() => {
140
+ const host = sideRef.current;
141
+ const el = host && host.querySelector(".kbd");
142
+ if (el && el.scrollIntoView)
143
+ el.scrollIntoView({ block: "nearest" });
144
+ }, [fileIdx]);
145
+ // Keyboard navigation, file list only: j/k move, Enter opens, Escape closes a click-expanded
146
+ // value. There is no "pane" concept anymore -- the file list is the only keyboard-focusable
147
+ // list, and expanding/collapsing a value is a click-only action.
148
+ const fileNames = (files && files.files) || [];
149
+ const expandedIdxRef = useLatestRef(expandedIdx);
150
+ const st = useLatestRef({ fileNames, fileIdx, pickFile, expandedIdxRef });
151
+ useGlobalKeydown((e) => {
152
+ // never hijack search or profile dropdown
153
+ const t = e.target;
154
+ if (t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA" || t.tagName === "SELECT" || t.isContentEditable))
155
+ return;
156
+ if (e.metaKey || e.ctrlKey || e.altKey)
157
+ return;
158
+ const s = st.current;
159
+ switch (e.key) {
160
+ case "ArrowDown":
161
+ case "j":
162
+ if (!s.fileNames.length)
163
+ return;
164
+ setExpandedIdx(null); // moving the highlight closes whatever was expanded
165
+ setFileIdx((i) => Math.min(s.fileNames.length - 1, i + 1));
166
+ break;
167
+ case "ArrowUp":
168
+ case "k":
169
+ if (!s.fileNames.length)
170
+ return;
171
+ setExpandedIdx(null);
172
+ setFileIdx((i) => Math.max(0, i - 1));
173
+ break;
174
+ case "Enter": {
175
+ const file = s.fileNames[s.fileIdx];
176
+ if (file)
177
+ s.pickFile(file.name);
178
+ break;
179
+ }
180
+ case "Escape":
181
+ if (s.expandedIdxRef.current !== null)
182
+ setExpandedIdx(null);
183
+ else
184
+ return;
185
+ break;
186
+ default:
187
+ return;
188
+ }
189
+ e.preventDefault();
190
+ });
191
+ const RENDER_LIMIT = 10000;
192
+ // Sort files by size descending (biggest/most-interesting first)
193
+ const sortedFiles = files && files.files ? [...files.files].sort((a, b) => b.size - a.size) : [];
194
+ return html `
195
+ <div class="prefsview">
196
+ <div class="prefsside" ref=${sideRef}>
197
+ <div class="prefssec">files</div>
198
+ ${files == null
199
+ ? html `<div class="msg">loading…</div>`
200
+ : files.error
201
+ ? html `<div class="msg err">${files.error}</div>`
202
+ : !files.files || !files.files.length
203
+ ? html `<div class="msg">no preference files (device unreachable, or debug build not installed)</div>`
204
+ : html `
205
+ ${(files.available_users || []).length > 1
206
+ ? html `<div class="prefsprofile">
207
+ <span class="prefsprofcap">profile</span>
208
+ <select
209
+ onChange=${(e) => {
210
+ const v = e.currentTarget.value;
211
+ requestIdRef.current++; // discard any in-flight search/read from the old profile
212
+ setUser(v);
213
+ setSelectedFile(null);
214
+ setEntries(null);
215
+ setSearchResults(null);
216
+ setSearchQuery("");
217
+ setSearching(false);
218
+ setMeta("");
219
+ loadFiles(v);
220
+ }}
221
+ >
222
+ ${files.available_users.map((u) => html `<option value=${u} selected=${u === files.user}>${profileLabel(u)}</option>`)}
223
+ </select>
224
+ </div>`
225
+ : html `<div class="prefsprofile">profile: <b>${profileLabel(files.user)}</b></div>`}
226
+ ${sortedFiles.map((f, i) => html `<div
227
+ class=${"prefsitem" + (f.name === selectedFile ? " sel" : "") + (i === fileIdx ? " kbd" : "") + (f.size < TINY_FILE_BYTES ? " tiny" : "")}
228
+ onClick=${() => {
229
+ setFileIdx(i);
230
+ pickFile(f.name);
231
+ }}
232
+ >
233
+ <span class="prefsitemname" title=${f.name}>${f.name}</span>${isFfFile(f.name) ? html `<span class="ffbadge">[FF]</span>` : null}<span class="size">${formatSize(f.size)}</span>
234
+ </div>`)}
235
+ `}
236
+ </div>
237
+ <div class="prefsmain">
238
+ <div class="prefsprivacy">
239
+ Preference values can include user, team, and org identifiers. Review before sharing.
240
+ </div>
241
+ <div class="prefssearchbar">
242
+ <div class="prefssearchlabel">Search ACROSS ALL FILES</div>
243
+ <div class="prefssearch">
244
+ <input
245
+ value=${searchQuery}
246
+ placeholder="e.g. slackbot, count, feature name…"
247
+ autocomplete="off"
248
+ onInput=${(e) => {
249
+ const v = e.currentTarget.value;
250
+ setSearchQuery(v);
251
+ }}
252
+ onKeyDown=${(e) => {
253
+ if (e.key === "Enter")
254
+ search(searchQuery);
255
+ }}
256
+ />
257
+ <button disabled=${searching} onClick=${() => search(searchQuery)}>${searching ? html `<span class="spinner"></span> Searching…` : "Search"}</button>
258
+ ${selectedFile && !searchQuery ? html `<button class="prefsrefresh" onClick=${() => pickFile(selectedFile)}>↻ refresh</button>` : null}
259
+ </div>
260
+ </div>
261
+ <div class="prefsmeta">${searching ? "searching…" : meta}</div>
262
+ <div class="prefsout">
263
+ ${searching
264
+ ? html `<div class="msg">searching all files…</div>`
265
+ : searchResults
266
+ ? searchResults.error
267
+ ? html `<div class="msg err">${searchResults.error}</div>`
268
+ : !searchResults.results || !searchResults.results.length
269
+ ? // "no matches" must never stand alone when files were skipped -- skipped:[]
270
+ // means "searched everything, found nothing" (a real answer); a non-empty
271
+ // skipped array means some files were never actually searched (a run-as
272
+ // denial, mid-write, or unreadable file), which reads as a false negative
273
+ // if the UI shows the same "no matches" text either way. `results` only
274
+ // lists files WITH a match, so there is no total-files-searched count to
275
+ // quote here -- name what is known (skipped count) without inventing one.
276
+ html `
277
+ ${searchResults.skipped && searchResults.skipped.length
278
+ ? html `<div class="truncwarn err">${searchResults.skipped.length} file${searchResults.skipped.length === 1 ? "" : "s"} could not be read. "No matches" only reflects the files that were searched.</div>`
279
+ : null}
280
+ <div class="msg">no matches</div>
281
+ `
282
+ : html `
283
+ ${searchResults.skipped && searchResults.skipped.length
284
+ ? html `<div class="truncwarn">${searchResults.skipped.length} files could not be read.</div>`
285
+ : null}
286
+ ${(() => {
287
+ let rowOffset = 0;
288
+ return searchResults.results.slice(0, RENDER_LIMIT).map((group) => {
289
+ const result = html `<div class="searchgroup">
290
+ <div class="searchfile">${group.file}</div>
291
+ <${PrefsGrid}
292
+ rows=${group.matches}
293
+ rowOffset=${rowOffset}
294
+ expandedIdx=${expandedIdx}
295
+ onToggleExpanded=${(idx) => setExpandedIdx(idx === expandedIdx ? null : idx)}
296
+ />
297
+ </div>`;
298
+ rowOffset += group.matches.length;
299
+ return result;
300
+ });
301
+ })()}
302
+ ${searchResults.results.length > RENDER_LIMIT
303
+ ? html `<div class="msg">(showing first ${RENDER_LIMIT} of ${searchResults.results.length} files)</div>`
304
+ : null}
305
+ `
306
+ : selectedFile == null
307
+ ? html `<div class="msg">pick a preferences file, or search above</div>`
308
+ : entries == null
309
+ ? html `<div class="msg">loading…</div>`
310
+ : entries.error
311
+ ? html `<div class="msg err">${entries.error}</div>`
312
+ : html `
313
+ ${entries.device_read_truncated ? html `<div class="truncwarn">This read stopped partway through the file on the device (256KB cap).</div>` : null}
314
+ ${!entries.entries || !entries.entries.length
315
+ ? html `<div class="msg">0 entries</div>`
316
+ : html `<${PrefsGrid}
317
+ rows=${entries.entries}
318
+ rowOffset=${0}
319
+ expandedIdx=${expandedIdx}
320
+ onToggleExpanded=${(idx) => setExpandedIdx(idx === expandedIdx ? null : idx)}
321
+ />`}
322
+ `}
323
+ </div>
324
+ </div>
325
+ </div>
326
+ `;
327
+ }
328
+ function copyText(e, value) {
329
+ navigator.clipboard?.writeText(value);
330
+ const btn = e.currentTarget;
331
+ const original = btn.textContent;
332
+ btn.textContent = "copied ✓";
333
+ setTimeout(() => {
334
+ btn.textContent = original;
335
+ }, 900);
336
+ }
337
+ // Parse a value string as JSON when possible, so a navigation_history/experiment blob renders
338
+ // pretty-printed (via inspector.ts's highlightJson) instead of a flat unreadable line. Falls
339
+ // back to the raw string for plain values (booleans, ints, short strings).
340
+ function tryParseJson(v) {
341
+ if (!v || (v[0] !== "{" && v[0] !== "["))
342
+ return null;
343
+ try {
344
+ return JSON.parse(v);
345
+ }
346
+ catch {
347
+ return null;
348
+ }
349
+ }
350
+ // Click a truncated value cell to expand it in place: the CSS ellipsis clips long values (a
351
+ // navigation_history or experiment_data blob easily runs to hundreds of chars, past the column
352
+ // width, with no way to read or select the rest). Expanding shows the full value, pretty-printed
353
+ // when it parses as JSON, plus a copy button -- same spirit as inspector.ts's detail view, scoped
354
+ // to one table row instead of a whole event.
355
+ function PrefsGrid({ rows, rowOffset = 0, expandedIdx = null, onToggleExpanded, }) {
356
+ return html `
357
+ <table>
358
+ <thead>
359
+ <tr>
360
+ <th>key</th>
361
+ <th>type</th>
362
+ <th>value</th>
363
+ </tr>
364
+ </thead>
365
+ <tbody>
366
+ ${rows.map((row, localIdx) => {
367
+ const globalIdx = rowOffset + localIdx;
368
+ const valueStr = String(row.value ?? "");
369
+ const isOpen = expandedIdx === globalIdx;
370
+ const parsed = isOpen ? tryParseJson(valueStr) : null;
371
+ return html `<tr>
372
+ <td title=${String(row.key ?? "")}>${String(row.key ?? "")}</td>
373
+ <td title=${String(row.type ?? "")}>${String(row.type ?? "")}</td>
374
+ <td
375
+ title="click to view full value"
376
+ class=${"val" + (isOpen ? " open" : "")}
377
+ onClick=${() => onToggleExpanded?.(globalIdx)}
378
+ >
379
+ ${valueStr}
380
+ </td>
381
+ </tr>
382
+ ${isOpen
383
+ ? html `<tr class="valexpand">
384
+ <td colspan="3">
385
+ <div class="valexpandbar">
386
+ <button onClick=${(e) => copyText(e, valueStr)}>Copy</button>
387
+ <button onClick=${() => onToggleExpanded?.(globalIdx)}>Close</button>
388
+ </div>
389
+ ${parsed !== null
390
+ ? html `<pre class="valpretty" dangerouslySetInnerHTML=${{ __html: highlightJson(parsed) }}></pre>`
391
+ : html `<pre class="valpretty">${valueStr}</pre>`}
392
+ </td>
393
+ </tr>`
394
+ : null}`;
395
+ })}
396
+ </tbody>
397
+ </table>
398
+ `;
399
+ }
@@ -32,7 +32,7 @@ export const FIELD_VALUES = {
32
32
  method: ["GET", "POST", "PUT", "DELETE", "PATCH"],
33
33
  };
34
34
  // SOURCE registry: one row per source. `kind` routes the view (streaming feed vs the
35
- // point-in-time DB browser) without a hardcoded source check.
35
+ // point-in-time state browser) without a hardcoded source check.
36
36
  export const SOURCES = {
37
37
  network: { label: "Network", kind: "stream", hasDetailEndpoint: true, eagerCapture: true, ringSize: 400, detailNoun: "the full request/response body" },
38
38
  rtm: { label: "RTM", kind: "stream", hasDetailEndpoint: true, eagerCapture: true, ringSize: 2000, detailNoun: "the full payload" },
@@ -40,7 +40,8 @@ export const SOURCES = {
40
40
  trace: { label: "Traces", kind: "stream", hasDetailEndpoint: true, ringSize: 2000, detailNoun: "the span timing and tag detail" },
41
41
  log: { label: "Logs", kind: "stream", hasDetailEndpoint: false },
42
42
  all: { label: "Live", kind: "stream" },
43
- db: { label: "Database", kind: "db" },
43
+ db: { label: "Database", kind: "state" },
44
+ prefs: { label: "Preferences", kind: "state" },
44
45
  };
45
46
  // The set of streaming source kinds the store admits off the SSE stream (derived from SOURCES,
46
47
  // excluding the non-stream db + the unified "all" alias).
@@ -65,8 +66,8 @@ export function hasDetailEndpoint(kind) {
65
66
  // see widgets.ts). A new widget = one key here + one component.
66
67
  export const WIDGETS = ["counter", "rate", "sparkline", "graph"];
67
68
  // Source order for the modebar / global tab-switch (matches the MODES preset order).
68
- export const SOURCE_ORDER = ["all", "network", "rtm", "clog", "trace", "log", "db"];
69
- // The source options the Filters panel offers: every streaming source (db is its own container,
70
- // not a feed filter). Derived from SOURCES so adding a streaming source surfaces it in Filters
71
- // with no edit there. Ordered by SOURCE_ORDER (the modebar order) for a stable, familiar list.
69
+ export const SOURCE_ORDER = ["all", "network", "rtm", "clog", "trace", "log", "db", "prefs"];
70
+ // The source options the Filters panel offers: every streaming source (state sources like db/prefs
71
+ // are their own containers, not feed filters). Derived from SOURCES so adding a streaming source
72
+ // surfaces it in Filters with no edit there. Ordered by SOURCE_ORDER (the modebar order) for a stable, familiar list.
72
73
  export const FILTER_SOURCES = SOURCE_ORDER.filter((s) => SOURCES[s]?.kind === "stream");