@slack/radar-mcp 1.18.1 → 1.20.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.
@@ -9,7 +9,7 @@
9
9
  // point-in-time, not a live feed; pulling the store would start the SSE engine + timers on a
10
10
  // tab that has no use for them. It carries its own keyboard nav since there is no Feed here.
11
11
  import { html } from "./html.js";
12
- import { useState, useEffect, useCallback, useRef } from "preact/hooks";
12
+ import { useState, useEffect, useCallback, useMemo, useRef } from "preact/hooks";
13
13
  import { useLatestRef, useGlobalKeydown } from "./hooks.js";
14
14
  // --- query history ---
15
15
  // The queries you ran by hand in this tab, newest-first, per database AND per profile (the same
@@ -144,6 +144,88 @@ function copyText(text, e) {
144
144
  btn.textContent = "copied ✓";
145
145
  setTimeout(() => (btn.textContent = prev), 1200);
146
146
  }
147
+ // The words SQLite refuses as a bare table name in a FROM clause. Deliberately NOT its full
148
+ // keyword list: most SQLite keywords are still legal identifiers, and measuring the difference
149
+ // matters here because every unnecessary quote brings back the swallowing described below. Each
150
+ // of the 147 documented keywords was created as a table and selected from bare; these 58 failed
151
+ // and the other 89 (`key`, `row`, `end`, `filter`, `view`, `match` and the rest) parsed fine.
152
+ // If a later SQLite reserves another word, that name gets a syntax error the moment it is
153
+ // clicked, which is visible and immediate rather than a wrong answer.
154
+ const SQLITE_RESERVED = new Set(("ADD ALL ALTER AND AS AUTOINCREMENT BETWEEN CASE CHECK COLLATE COMMIT CONSTRAINT CREATE " +
155
+ "DEFAULT DEFERRABLE DELETE DISTINCT DROP ELSE ESCAPE EXCEPT EXISTS FOREIGN FROM GROUP " +
156
+ "HAVING IN INDEX INSERT INTERSECT INTO IS ISNULL JOIN LIMIT NOT NOTHING NOTNULL NULL ON " +
157
+ "OR ORDER PRIMARY REFERENCES RETURNING SELECT SET TABLE THEN TO TRANSACTION UNION UNIQUE " +
158
+ "UPDATE USING VALUES WHEN WHERE").split(" "));
159
+ // A bare table name: the identifier shape SQLite accepts without quotes. Any byte at or above 0x80
160
+ // counts as a name character, so a non-ASCII table name needs no quotes either. `$` counts too, but
161
+ // only after the first character: measured, `a$b` and `a$` select bare while `$b` is a syntax error.
162
+ const BARE_NAME = /^[A-Za-z_\u0080-\uFFFF][A-Za-z0-9_$\u0080-\uFFFF]*$/;
163
+ // How a table name is written into the generated SELECT. A plain word goes in bare, because
164
+ // quotes around it swallow whatever is typed beside them: `SELECT * FROM "items" LIMIT 100`
165
+ // edited into `... FROM "items WHERE id='1'" LIMIT 100` asks for a table named
166
+ // `items WHERE id='1'`, and sqlite answers "no such table", which reads as though the table
167
+ // vanished rather than as a clause in the wrong place. A name that cannot stand bare keeps its
168
+ // quotes, with any embedded quote doubled, which is SQL's own escape. Quotes are the fallback
169
+ // because a quoted identifier is always legal, and the set above is kept tight so the fallback
170
+ // stays rare.
171
+ export function tableRef(name) {
172
+ return BARE_NAME.test(name) && !SQLITE_RESERVED.has(name.toUpperCase())
173
+ ? name
174
+ : '"' + name.replace(/"/g, '""') + '"';
175
+ }
176
+ // A cell with nothing in it. SQLite columns are dynamically typed, so one column holds numbers,
177
+ // text and NULL at once. `undefined` is here for a caller passing rows that do not all carry the
178
+ // same columns; /dbquery cannot produce that, because sqlite3 -json emits every key on every row.
179
+ //
180
+ // Whitespace-only text counts as blank, for two reasons. The grid renders cells into `<td>`, where
181
+ // HTML collapses whitespace, so such a cell IS an empty cell to the reader the sort is for. And it
182
+ // keeps whitespace away from `numericValue`, where `Number("")` is 0, which would rank a
183
+ // blank-looking cell as zero ahead of every real number ascending.
184
+ function isBlank(v) {
185
+ return v === null || v === undefined || (typeof v === "string" && v.trim() === "");
186
+ }
187
+ // One collator for the whole module. Building one per comparison costs 222ms to sort a 10000-row
188
+ // text column against 15ms for a cached one, measured, and a sort runs on the UI thread.
189
+ const COLLATOR = new Intl.Collator(undefined, { numeric: true });
190
+ // A cell's numeric value, when it has one. Not just typeof number: SQLite columns are dynamically
191
+ // typed and a column of numbers stored as TEXT is ordinary, so `"1.09"` has to rank as 1.09. Text
192
+ // collation gets those wrong even with numeric:true, because it reads digit runs rather than values:
193
+ // measured, it puts `1.09` after `1.5` and `-3` before `-5`. A value only counts as numeric when the
194
+ // WHOLE string is a finite number, so `item9` still takes the text path and stays ahead of `item10`.
195
+ function numericValue(v) {
196
+ if (typeof v === "number")
197
+ return Number.isFinite(v) ? v : null;
198
+ if (typeof v !== "string")
199
+ return null;
200
+ const n = Number(v.trim());
201
+ return Number.isFinite(n) ? n : null;
202
+ }
203
+ // A copy of `rows` ordered by `col`.
204
+ //
205
+ // Three bands, in this order: values that are numbers, then everything else, then blanks. The
206
+ // direction reorders values WITHIN a band and never reshuffles the bands, so blanks stay at the
207
+ // bottom and numbers stay ahead of text whichever way the column points. Blanks sink because "no
208
+ // value" is not a value to rank, and because a descending sort whose first screen is empty cells
209
+ // hides the rows the sort was for. Text compares with numeric collation, which keeps `item9` ahead of
210
+ // `item10`. Array.prototype.sort is stable, so rows that tie keep the order the query returned them
211
+ // in, which is what the third click goes back to.
212
+ export function sortRows(rows, col, dir) {
213
+ return rows.slice().sort((x, y) => {
214
+ const xv = x[col];
215
+ const yv = y[col];
216
+ const xb = isBlank(xv);
217
+ const yb = isBlank(yv);
218
+ if (xb || yb)
219
+ return xb && yb ? 0 : xb ? 1 : -1;
220
+ const xn = numericValue(xv);
221
+ const yn = numericValue(yv);
222
+ if (xn !== null && yn !== null)
223
+ return dir * (xn < yn ? -1 : xn > yn ? 1 : 0);
224
+ if ((xn === null) !== (yn === null))
225
+ return xn !== null ? -1 : 1;
226
+ return dir * COLLATOR.compare(String(xv), String(yv));
227
+ });
228
+ }
147
229
  export function DbBrowser({ spec }) {
148
230
  const [user, setUser] = useState(null);
149
231
  const [dbs, setDbs] = useState(null); // null = loading
@@ -152,9 +234,13 @@ export function DbBrowser({ spec }) {
152
234
  const [sql, setSql] = useState("");
153
235
  const [out, setOut] = useState({ msg: "pick a database, then a table" });
154
236
  const [meta, setMeta] = useState("");
155
- // The result row whose full detail is open in the dock. Cleared whenever a new query runs,
156
- // since a stale row index would point into the old result set.
237
+ // The result row whose full detail is open in the dock. Held as the row itself rather than its
238
+ // position, because sorting moves the position while the open row stays the same row. Cleared
239
+ // whenever a new query runs, since a row from the old result set has nothing to point at.
157
240
  const [selectedRow, setSelectedRow] = useState(null);
241
+ // How the grid is ordered. Cleared when a new result ARRIVES rather than when a query is sent, so
242
+ // an earlier answer landing late cannot inherit an ordering chosen for a different result.
243
+ const [sort, setSort] = useState(null);
158
244
  // What the right-hand dock is showing, if anything. Row detail and query history share one
159
245
  // dock (tabbed) so the results grid never has to give up width to two panels at once.
160
246
  const [dock, setDock] = useState(() => (readDockPref() ? "history" : null));
@@ -251,6 +337,7 @@ export function DbBrowser({ spec }) {
251
337
  setOut({ error: r.error });
252
338
  return; // a rejected query is not worth remembering
253
339
  }
340
+ setSort(null); // see the state declaration for why this is here and not before the request
254
341
  // Recorded on any answer the server accepted, 0 rows included -- an empty result is a
255
342
  // legitimate query you may well want to run again.
256
343
  if (record)
@@ -271,8 +358,39 @@ export function DbBrowser({ spec }) {
271
358
  setOut({ error: "network error running query" });
272
359
  }
273
360
  }, [db, sql, user, userQS]);
361
+ // Clicking a column header walks it: ascending, then descending, then back to the order the query
362
+ // returned. Clicking a different header starts that column ascending. Nothing here touches the
363
+ // query or the device: it is grid state over the rows already on screen, which is why it is instant
364
+ // and why the grid says what it covered.
365
+ const cycleSort = useCallback((col) => {
366
+ setSort((s) => (!s || s.col !== col ? { col, dir: 1 } : s.dir === 1 ? { col, dir: -1 } : null));
367
+ }, []);
368
+ // The rows as the grid shows them. Memoized on the rows and the sort so scrolling, opening a row,
369
+ // or typing in the SQL box does not re-sort a big result on every render.
370
+ const shown = useMemo(() => (out.rows && out.rows.length && sort ? sortRows(out.rows, sort.col, sort.dir) : out.rows), [out.rows, sort]);
371
+ // Column set comes from the rows AS THEY ARRIVED, never from the sorted copy, so which row landed
372
+ // first cannot change which columns the grid has. /dbquery cannot actually send rows with
373
+ // different keys, since sqlite3 -json emits every key on every row, but Grid takes the rows it is
374
+ // given and this makes the header set independent of their order either way.
375
+ const cols = useMemo(() => (out.rows && out.rows.length ? Object.keys(out.rows[0]) : []), [out.rows]);
376
+ // The scope, said in rendered text beside the row count rather than in a tooltip, because a sorted
377
+ // column normally implies the whole result and this one covers the rows on screen. Said every time
378
+ // a sort is in effect rather than only when something looks unusual.
379
+ //
380
+ // It states coverage and stops there. Naming what was left out would be a claim about the query,
381
+ // and nothing here can tell whether anything WAS left out: `LIMIT 100` that hands back 14 rows
382
+ // truncated nothing, so "not the whole result" is false exactly as often as it is useful. The
383
+ // reason a reader needs, that `LIMIT` with no ORDER BY returns a storage-order prefix and so the
384
+ // top row after sorting by time can be the newest of an OLD hundred, is in the header tooltip,
385
+ // where it is advice about the next click rather than an assertion about this result.
386
+ //
387
+ // Only rendered when there are rows, so it cannot sit beside a stale count while a query is in
388
+ // flight or after one has failed.
389
+ const sortScope = sort && out.rows && out.rows.length
390
+ ? html `<span class="dbsortnote"> · sorted these ${out.rows.length} rows</span>`
391
+ : null;
274
392
  const pickTable = useCallback((t) => {
275
- const q = 'SELECT * FROM "' + t + '" LIMIT 100';
393
+ const q = "SELECT * FROM " + tableRef(t) + " LIMIT 100";
276
394
  setSql(q);
277
395
  run(q, false); // generated, not typed: keep it out of the history
278
396
  }, [run]);
@@ -325,6 +443,17 @@ export function DbBrowser({ spec }) {
325
443
  if (el && el.scrollIntoView)
326
444
  el.scrollIntoView({ block: "nearest" });
327
445
  }, [pane, dbIdx, tblIdx, histIdx]);
446
+ // The results pane scrolls and its header is sticky, so a sort is one click away however deep you
447
+ // are. Reordering under a scrolled viewport leaves you in the middle of the new order looking at an
448
+ // arbitrary slice, with the rows the sort was for off-screen above. Go back to the top, which is
449
+ // where the answer now is. Keyed on the rows as well as the sort, because a new result is the other
450
+ // way the content under the viewport changes completely, and it should not matter which of the two
451
+ // put different rows there.
452
+ const outRef = useRef(null);
453
+ useEffect(() => {
454
+ if (outRef.current)
455
+ outRef.current.scrollTop = 0;
456
+ }, [sort, out.rows]);
328
457
  // Keyboard navigation. The latest lists/indices/handlers live in a ref so the single window
329
458
  // listener (attached once by useGlobalKeydown) never goes stale. Mirrors the PoC's
330
459
  // stale-closure-ref pattern, now via the shared Foundation hooks.
@@ -496,23 +625,28 @@ export function DbBrowser({ spec }) {
496
625
  </button>`
497
626
  : null}
498
627
  </div>
499
- <div class="dbmeta">${meta}</div>
628
+ <div class="dbmeta">${meta}${sortScope}</div>
500
629
  <div class=${"dbsplit" + (dock ? " open" : "")}>
501
- <div class="dbout">
630
+ <div class="dbout" ref=${outRef}>
502
631
  ${out.msg
503
632
  ? html `<div class="msg">${out.msg}</div>`
504
633
  : out.error
505
634
  ? html `<div class="msg err">${out.error}</div>`
506
- : !out.rows || !out.rows.length
635
+ : !shown || !shown.length
507
636
  ? html `<div class="msg">0 rows</div>`
508
637
  : html `<${Grid}
509
- rows=${out.rows}
510
- selectedIndex=${dock === "row" && selectedRow ? selectedRow.index : -1}
511
- onSelect=${(row, index) => {
638
+ rows=${shown}
639
+ cols=${cols}
640
+ sort=${sort}
641
+ onSort=${cycleSort}
642
+ selectedRow=${dock === "row" ? selectedRow : null}
643
+ onSelect=${(row) => {
512
644
  // Clicking the open row again closes it; the dock then falls back to
513
- // history if that is where you had it.
514
- const same = dock === "row" && selectedRow && selectedRow.index === index;
515
- setSelectedRow(same ? null : { row, index });
645
+ // history if that is where you had it. Compared by row, not by position,
646
+ // so a sort between the two clicks cannot make them look like different
647
+ // rows (or make two different rows look like the same one).
648
+ const same = dock === "row" && selectedRow === row;
649
+ setSelectedRow(same ? null : row);
516
650
  setDock(same ? (readDockPref() ? "history" : null) : "row");
517
651
  }}
518
652
  />`}
@@ -534,7 +668,7 @@ export function DbBrowser({ spec }) {
534
668
  <span class="x" title="close" onClick=${closeDock}>✕</span>
535
669
  </div>
536
670
  ${dock === "row" && selectedRow
537
- ? html `<${RowInspector} row=${selectedRow.row} />`
671
+ ? html `<${RowInspector} row=${selectedRow} />`
538
672
  : html `<${HistoryPanel}
539
673
  entries=${history}
540
674
  focusIdx=${pane === "hist" ? histIdx : -1}
@@ -552,17 +686,42 @@ export function DbBrowser({ spec }) {
552
686
  </div>
553
687
  `;
554
688
  }
555
- function Grid({ rows, selectedIndex, onSelect, }) {
556
- const cols = Object.keys(rows[0]);
689
+ function Grid({ rows, cols, selectedRow, onSelect, sort, onSort, }) {
690
+ // What the next click does, and what it will cover, at the control rather than only on the meta
691
+ // line. The remedy is here too: nothing else tells a reader that the wider question is theirs to
692
+ // ask, and it is knowable without inspecting anything.
693
+ //
694
+ // No aria-describedby pointing at the scope note. It was tried and measured worse: a description
695
+ // SUPERSEDES the title in the accessible name computation, so the action copy disappeared from the
696
+ // accessibility tree exactly where it stops being guessable, and pointing every header at one
697
+ // result-wide note described eleven unsorted columns as sorted. The note is rendered text either
698
+ // way, so a reader meets it; it is just not wired to the control.
699
+ const hint = (dir) => dir === null
700
+ ? "sort ascending, these rows only. Add ORDER BY to the query to sort everything"
701
+ : dir === 1
702
+ ? "sort descending, these rows only. Add ORDER BY to the query to sort everything"
703
+ : "clear the sort";
557
704
  return html `
558
705
  <table>
559
706
  <thead>
560
707
  <tr>
561
- ${cols.map((c) => html `<th>${c}</th>`)}
708
+ ${cols.map((c) => {
709
+ // One read of the sort per header, which every other attribute derives from: null means
710
+ // this column is not the sorted one.
711
+ const dir = sort !== null && sort.col === c ? sort.dir : null;
712
+ return html `<th
713
+ class=${"dbsortable" + (dir === null ? "" : " sorted")}
714
+ title=${hint(dir)}
715
+ aria-sort=${dir === null ? "none" : dir === 1 ? "ascending" : "descending"}
716
+ onClick=${() => onSort(c)}
717
+ >
718
+ ${c}<span class="dbsortdir" aria-hidden="true">${dir === null ? "↕" : dir === 1 ? "▲" : "▼"}</span>
719
+ </th>`;
720
+ })}
562
721
  </tr>
563
722
  </thead>
564
723
  <tbody>
565
- ${rows.map((row, i) => html `<tr class=${i === selectedIndex ? "rowsel" : ""} onClick=${() => onSelect(row, i)}>
724
+ ${rows.map((row) => html `<tr class=${row === selectedRow ? "rowsel" : ""} onClick=${() => onSelect(row)}>
566
725
  ${cols.map((c) => html `<td title=${String(row[c] ?? "")}>${String(row[c] ?? "")}</td>`)}
567
726
  </tr>`)}
568
727
  </tbody>
@@ -5,9 +5,9 @@
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, modeServed, fmtNum } from "./store.js";
9
- import { STREAM_KINDS } from "./registry.js";
10
- import { parseFilter, tokenize, isCompleteTerm } from "./filter.js";
8
+ import { store, shortUrl, shortPkg, MODES, modeServed, fmtNum, specForTab } from "./store.js";
9
+ import { STREAM_KINDS, LOG_LEVEL_ORDER, levelRank } from "./registry.js";
10
+ import { parseFilter, tokenize, isCompleteTerm, isQuote } from "./filter.js";
11
11
  const ROW_H = 24;
12
12
  const OVERSCAN = 10;
13
13
  // Feed UI prefs PERSIST across tab switches (the Feed unmounts/remounts per source). The text
@@ -59,7 +59,7 @@ function pillClasses(raw, invalidSet, sourceIsAll) {
59
59
  classes.push("fpill-neg");
60
60
  if (body.startsWith("/"))
61
61
  classes.push("fpill-re");
62
- else if (body.startsWith('"'))
62
+ else if (isQuote(body[0]))
63
63
  classes.push("fpill-quote");
64
64
  else if (sourceIsAll && KIND_TOKENS.has(body.toLowerCase()))
65
65
  classes.push("fpill-kind", "fpill-kind-" + body.toLowerCase());
@@ -67,11 +67,16 @@ function pillClasses(raw, invalidSet, sourceIsAll) {
67
67
  }
68
68
  // The label shown on a pill. Negation renders as a leading "−" glyph outside the body so the
69
69
  // body reads the same as it does in the filter string. Regex pills keep their slashes (that is
70
- // how they were typed); quoted phrases keep their quotes.
70
+ // how they were typed). A quoted phrase drops its straight quotes from the body and gets curly
71
+ // marks rendered OUTSIDE the ellipsizing body instead: a long pasted line used to truncate its
72
+ // closing quote away and read as an unbalanced `"Fetched 0 AI app profiles for tea…`. The raw
73
+ // term (quotes included) still rides the title and pops back for editing unchanged.
71
74
  function pillLabel(raw) {
72
- if (raw.startsWith("-"))
73
- return { neg: true, body: raw.slice(1) };
74
- return { neg: false, body: raw };
75
+ const neg = raw.startsWith("-");
76
+ const body = neg ? raw.slice(1) : raw;
77
+ if (body.length >= 2 && isQuote(body[0]) && isQuote(body[body.length - 1]))
78
+ return { neg, body: body.slice(1, -1), quoted: true };
79
+ return { neg, body, quoted: false };
75
80
  }
76
81
  // Platform-aware jump-pill labels. macOS has no Home/End, so show the chord that works there.
77
82
  const IS_MAC = typeof navigator !== "undefined" && /Mac|iP(hone|ad|od)/.test(navigator.platform || navigator.userAgent || "");
@@ -89,7 +94,7 @@ function sortOptionsFor(source) {
89
94
  opts.push({ key: "status", label: "status code (high→low)", get: (e) => Number(e.status_code), dir: "desc" });
90
95
  }
91
96
  if (source === "log")
92
- opts.push({ key: "severity", label: "severity (errors first)", get: (e) => ({ FATAL: 5, ERROR: 4, WARN: 3, INFO: 2, DEBUG: 1, VERBOSE: 0 }[(e.level || "").toUpperCase()] ?? -1), dir: "desc" });
97
+ opts.push({ key: "severity", label: "severity (errors first)", get: (e) => levelRank(e.level), dir: "desc" });
93
98
  if (source === "rtm")
94
99
  opts.push({ key: "evtype", label: "event type (A→Z)", get: (e) => e.event_type || "", dir: "asc" });
95
100
  if (source === "clog")
@@ -187,6 +192,22 @@ export function Feed({ spec, onInspect, selectedId }) {
187
192
  const [filter, setFilterState] = useState(() => FEED_PREFS.filter);
188
193
  const [sort, setSortState] = useState(() => FEED_PREFS.sortBySource[source || ""] || "newest");
189
194
  const [paused, setPaused] = useState(false);
195
+ const [helpOpen, setHelpOpen] = useState(false);
196
+ // The legend closes on a press anywhere outside it, the way the combobox lists do, so it never
197
+ // has to be hunted down again once read. Presses inside it are left alone so its examples can
198
+ // be selected and copied.
199
+ useEffect(() => {
200
+ if (!helpOpen || typeof document === "undefined" || !document.addEventListener)
201
+ return;
202
+ const onDown = (e) => {
203
+ const t = e.target;
204
+ if (t && typeof t.closest === "function" && t.closest(".fhelp, .fhelppop"))
205
+ return;
206
+ setHelpOpen(false);
207
+ };
208
+ document.addEventListener("mousedown", onDown);
209
+ return () => document.removeEventListener("mousedown", onDown);
210
+ }, [helpOpen]);
190
211
  const setFilter = useCallback((v) => {
191
212
  FEED_PREFS.filter = v;
192
213
  setFilterState(v);
@@ -321,10 +342,12 @@ export function Feed({ spec, onInspect, selectedId }) {
321
342
  });
322
343
  return off;
323
344
  }, [recompute, matchParsed, sort, sortOpts]);
324
- // Rebuild when the SERVER-SIDE filter (match/bodyContains) changes -- that changes what
325
- // store.matches() admits, so the whole snapshot must refresh. Keyed so it only fires on a
326
- // real filter change, not every spec poll.
327
- const matchKey = JSON.stringify(spec.match || {}) + "|" + (spec.bodyContains || "");
345
+ // Rebuild when the SERVER-SIDE filter (match/bodyContains/minLevel) changes -- that changes
346
+ // what store.matches() admits, so the whole snapshot must refresh. Keyed so it only fires on a
347
+ // real filter change, not every spec poll. minLevel is part of the key because the level
348
+ // selector's first live test left 289 rows of INFO and DEBUG on screen under "level ≥ ERROR":
349
+ // new frames were filtered, the rows already rendered were not.
350
+ const matchKey = JSON.stringify(spec.match || {}) + "|" + (spec.bodyContains || "") + "|" + (spec.minLevel || "");
328
351
  useEffect(() => {
329
352
  forceSnap();
330
353
  }, [matchKey]);
@@ -671,6 +694,19 @@ export function Feed({ spec, onInspect, selectedId }) {
671
694
  delete next.match;
672
695
  store.setSpec(next, { local: true });
673
696
  }, [spec]);
697
+ // The level selector writes the spec, the way the app selector does, so the choice survives a
698
+ // reload, shows as a chip, and an agent-authored spec can set the same field. VERBOSE is the
699
+ // floor of the order, so it is stored as no field at all rather than as a value that filters
700
+ // nothing.
701
+ const curLevel = (typeof spec.minLevel === "string" && spec.minLevel) || LOG_LEVEL_ORDER[0];
702
+ const changeLevel = useCallback((v) => {
703
+ const next = JSON.parse(JSON.stringify(spec));
704
+ if (v === LOG_LEVEL_ORDER[0])
705
+ delete next.minLevel;
706
+ else
707
+ next.minLevel = v;
708
+ store.setSpec(next, { local: true });
709
+ }, [spec]);
674
710
  // build only the visible slice
675
711
  const slice = [];
676
712
  for (let i = first; i < last; i++) {
@@ -715,6 +751,20 @@ export function Feed({ spec, onInspect, selectedId }) {
715
751
  // state: it changes nothing visually until the next commit. Cleared when the draft is
716
752
  // erased (erasing the popped text means "remove that term", so a new term goes to the tail).
717
753
  const editSlotRef = useRef(null);
754
+ // Stable identity on purpose: an inline arrow would be a new ref every render, and Preact detaches
755
+ // and reattaches a changed ref, replaying the three setAttribute calls per frame while tailing.
756
+ // Set as ATTRIBUTES, not props: spellcheck and (in WebKit) autocorrect are boolean IDL
757
+ // properties, and Preact assigns a prop that exists on the element as a property, so
758
+ // spellcheck="false" would coerce to true. The text substitution these turn off is what rewrote
759
+ // a typed quote into a curly one in the dock app's web view.
760
+ const attachFilterInput = useCallback((el) => {
761
+ filterRef.current = el;
762
+ if (el) {
763
+ el.setAttribute("spellcheck", "false");
764
+ el.setAttribute("autocorrect", "off");
765
+ el.setAttribute("autocapitalize", "off");
766
+ }
767
+ }, []);
718
768
  const commitDraft = (rawDraft) => {
719
769
  // Only commit a complete non-empty term; a bare "-" or an open /… / "… span stays as draft.
720
770
  if (!isCompleteTerm(rawDraft))
@@ -759,14 +809,16 @@ export function Feed({ spec, onInspect, selectedId }) {
759
809
  // Click anywhere in the wrap that is NOT a pill focuses the draft input (matches
760
810
  // browser input behavior: the whole wrap reads as one field).
761
811
  const target = e.target;
762
- if (target && typeof target.closest === "function" && target.closest(".fpill"))
812
+ // The legend and its button are left alone too: focusing the input on the click that ends
813
+ // a drag-select would drop the selection somebody just made in the legend.
814
+ if (target && typeof target.closest === "function" && target.closest(".fpill, .fhelp, .fhelppop"))
763
815
  return;
764
816
  const inp = filterRef.current;
765
817
  if (inp && typeof inp.focus === "function")
766
818
  inp.focus();
767
819
  }}>
768
820
  ${pills.map((raw, idx) => {
769
- const { neg, body } = pillLabel(raw);
821
+ const { neg, body, quoted } = pillLabel(raw);
770
822
  const cls = pillClasses(raw, invalidSet, sourceIsAll);
771
823
  // The title always carries the raw term: long pills ellipsize at max-width, and
772
824
  // hover is the only way to audit a truncated term without mutating the query.
@@ -802,7 +854,7 @@ export function Feed({ spec, onInspect, selectedId }) {
802
854
  e.preventDefault();
803
855
  popPillForEdit(idx);
804
856
  }}>
805
- ${neg ? html `<span class="fpill-sign">−</span>` : null}<span class="fpill-body">${body}</span><span class="fpill-x"
857
+ ${neg ? html `<span class="fpill-sign">−</span>` : null}${quoted ? html `<span class="fpill-q">“</span>` : null}<span class="fpill-body">${body}</span>${quoted ? html `<span class="fpill-q">”</span>` : null}<span class="fpill-x"
806
858
  title="remove this term"
807
859
  onMouseDown=${(e) => {
808
860
  e.preventDefault();
@@ -812,15 +864,45 @@ export function Feed({ spec, onInspect, selectedId }) {
812
864
  </span>
813
865
  `;
814
866
  })}
815
- <input class=${"ffilter" + (draftInvalid ? " finvalid" : "")} ref=${filterRef}
816
- placeholder=${pills.length ? "" : "filter rows… -exclude /regex/ \"phrase\""} autocomplete="off" value=${draft}
867
+ <input class=${"ffilter" + (draftInvalid ? " finvalid" : "")}
868
+ placeholder=${pills.length ? "\"phrase\" -exclude /regex/" : "filter rows… \"phrase\" -exclude /regex/"} autocomplete="off" value=${draft}
869
+ aria-label="filter rows"
817
870
  title=${draftInvalid
818
871
  ? "invalid regex ignored: " + draft
819
872
  : draftHint
820
873
  ? draftHint
821
- : 'space-separated terms AND together · -term excludes · /pattern/ is regex with optional short flags (i/m/s/g, 1-2 letters, so /api/im reads as flags) · unterminated /…/ or flag typos like /error/x become literal regex · "quote" to match any /…/ literally · on Live, a kind name (log, clog, trace, rtm, network) matches by type or substring, and its -kind form excludes by type only (quote it, -"log", to exclude by text instead)'}
874
+ : 'space-separated terms AND together · -term excludes · /pattern/ is regex with optional short flags (i/m/s/g, 1-2 letters, so /api/im reads as flags) · unterminated /…/ or flag typos like /error/x become literal regex · "quote" to match any /…/ literally, curly quotes count too · pasting text with spaces into an empty box quotes it as one phrase · on Live, a kind name (log, clog, trace, rtm, network) matches by type or substring, and its -kind form excludes by type only (quote it, -"log", to exclude by text instead)'}
875
+ ref=${attachFilterInput}
822
876
  onFocus=${() => { if (sel.size)
823
877
  clearSel(); }}
878
+ onPaste=${(e) => {
879
+ // A pasted line with spaces is one thing the user is looking for, not a list of
880
+ // terms: without this, the next space chopped a pasted log message into a pill per
881
+ // word, and common words like "0" or "app" matched half the feed. So a multi-word
882
+ // paste that REPLACES the draft (empty, or fully selected) commits as one quoted
883
+ // phrase. Pastes that fall through and land as typed: a single word; anything that
884
+ // spans lines (a single-line input cannot hold or round-trip the newline, and no row
885
+ // text has one); text carrying its own double quote, straight or curly (it would end
886
+ // the span early); and anything that STARTS in the box's own syntax (a quote, a
887
+ // regex, or an exclude). Only the first token is judged: log lines routinely carry
888
+ // "-1" or "/data/..." mid-line, and judging every token turned those back into a
889
+ // pill per word, which is the exact failure this handler exists to stop. A copied
890
+ // filter expression that starts with a bare word is quoted; the pill pops back for
891
+ // editing.
892
+ const el = e.currentTarget;
893
+ const text = (e.clipboardData?.getData("text") ?? "").trim();
894
+ const replacing = el.value === "" || (el.selectionStart === 0 && el.selectionEnd === el.value.length);
895
+ const tokens = text.split(/\s+/);
896
+ // A leading quote is already covered by the any-quote check below (one alphabet,
897
+ // QUOTE_CHARS, via isQuote); a leading regex or exclude is what this reads.
898
+ const syntax = /^\//.test(tokens[0]) || /^-\S/.test(tokens[0]);
899
+ if (!replacing || tokens.length < 2 || /[\r\n]/.test(text) || [...text].some(isQuote) || syntax)
900
+ return;
901
+ // Same shape as the space path: only a commit that happened consumes the keystroke,
902
+ // so a refused commit can never eat the clipboard.
903
+ if (commitDraft('"' + text + '"'))
904
+ e.preventDefault();
905
+ }}
824
906
  onKeyDown=${(e) => {
825
907
  const el = e.currentTarget;
826
908
  if (e.key === " ") {
@@ -851,14 +933,16 @@ export function Feed({ spec, onInspect, selectedId }) {
851
933
  setPillsAndDraft(pills.slice(0, -1), last);
852
934
  }
853
935
  else if (e.key === "Escape") {
936
+ setHelpOpen(false);
854
937
  el.blur();
855
938
  }
856
939
  else if ((e.key === "ArrowLeft" || e.key === "ArrowRight") && el.value === "") {
857
940
  e.preventDefault();
858
941
  el.blur();
859
942
  const ns = neighborTabSpec(e.key === "ArrowRight" ? 1 : -1);
943
+ // Presets carry the level floor the way a tab click does; the Custom spec is pushed as is.
860
944
  if (ns)
861
- store.setSpec(ns);
945
+ store.setSpec(ns === store.lastCustomSpec ? ns : specForTab(ns, store.spec, store.lastLogLevel));
862
946
  }
863
947
  }}
864
948
  onInput=${(e) => {
@@ -870,7 +954,32 @@ export function Feed({ spec, onInspect, selectedId }) {
870
954
  setPillsAndDraft(pills, v);
871
955
  }} />
872
956
  ${filter ? html `<span class="ffilterclear" title="clear all" onClick=${() => setFilter("")}>✕</span>` : null}
957
+ <span class=${"fhelp" + (helpOpen ? " open" : "")} title="filter syntax help" role="button" tabindex="0"
958
+ aria-label="filter syntax help" aria-expanded=${helpOpen} aria-controls=${helpOpen ? "fhelppop" : undefined}
959
+ onMouseDown=${(e) => e.preventDefault()}
960
+ onClick=${() => setHelpOpen((o) => !o)}
961
+ onKeyDown=${(e) => {
962
+ // A span does not synthesize a click from Enter or Space the way a button does, so the
963
+ // keys are handled here; assistive tech sends a real click, handled above.
964
+ if (e.key === "Enter" || e.key === " ") {
965
+ e.preventDefault();
966
+ setHelpOpen((o) => !o);
967
+ }
968
+ else if (e.key === "Escape")
969
+ setHelpOpen(false);
970
+ }}>?</span>
971
+ ${helpOpen ? html `<div class="fhelppop" id="fhelppop" role="note">
972
+ <code>error</code><span>rows containing it (case does not matter)</span>
973
+ <code>error timeout</code><span>rows containing both, in any order</span>
974
+ <code>"not found"</code><span>rows containing that phrase</span>
975
+ <code>-heartbeat</code><span>hide rows containing it</span>
976
+ <code>"-1"</code><span>a literal - or / goes in quotes</span>
977
+ <code>/^Fetch/</code><span>a regular expression</span>
978
+ ${source === "all" ? html `<code>-log</code><span>hide every row of a kind (log, clog, trace, rtm, network)</span>` : null}
979
+ ${isLogish ? html `<span class="fhelpnote">Typing <code>WARN</code> matches rows that contain it. For WARN and above, use the <b>level ≥</b> selector on this bar.</span>` : null}
980
+ </div>` : null}
873
981
  </span>
982
+ ${isLogish ? html `<label class="fsortlbl" title=${source === "all" ? "show log lines at this level or above. Rows of other kinds are not affected." : "show log lines at this level or above"}>level ≥ <select class="flevel" value=${curLevel} onChange=${(e) => changeLevel(e.currentTarget.value)}>${LOG_LEVEL_ORDER.map((l) => html `<option value=${l}>${l === LOG_LEVEL_ORDER[0] ? l + " (all)" : l}</option>`)}</select></label>` : null}
874
983
  ${isLogish ? html `<label class="fsortlbl">app <select onChange=${(e) => changePkg(e.currentTarget.value)}><option value="__all__" selected=${curPkg === "__all__"}>all apps</option>${pkgOptions.map((p) => html `<option value=${p} selected=${p === curPkg}>${shortPkg(p)}</option>`)}</select></label>` : null}
875
984
  <label class="fsortlbl">sort <select value=${sort} onChange=${(e) => setSort(e.currentTarget.value)}>${sortOpts.map((o) => html `<option value=${o.key}>${o.label}</option>`)}</select></label>
876
985
  <button class=${"fbtn" + (paused ? " paused" : "")} title="pause / resume the live feed" onClick=${() => setPaused((p) => !p)}>${paused ? "▶ resume" : "⏸ pause"}</button>
@@ -19,7 +19,10 @@
19
19
  // on an ambiguous /…/tail is reported in `hints` so the reading is visible,
20
20
  // never silent.
21
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 /.
22
+ // Quoting is also the escape hatch for a literal leading - or /. Curly quotes
23
+ // (“ ”) count as quotes too: macOS smart-quote substitution rewrites a typed "
24
+ // inside the dock app's WKWebView, and a phrase that then split into tokens was
25
+ // reported as "quoting does not work".
23
26
  //
24
27
  // An invalid or incomplete regex (e.g. "/foo(" mid-typing) never throws and never filters:
25
28
  // that term goes INERT (matches everything) and parse() reports it in `invalid` so the box can
@@ -33,6 +36,10 @@ const MATCH_ALL = Object.freeze({
33
36
  hints: Object.freeze([]),
34
37
  empty: true,
35
38
  });
39
+ // Every character that opens or closes a quoted span. Straight and curly are interchangeable
40
+ // on both ends, so a span typed as “a b" (one side rewritten by the OS) still closes.
41
+ export const QUOTE_CHARS = new Set(['"', "\u201c", "\u201d"]);
42
+ export const isQuote = (c) => c !== undefined && QUOTE_CHARS.has(c);
36
43
  // Split the query into raw term tokens: whitespace-separated, but /…/ and "…" spans (with an
37
44
  // optional leading -) stay one token even when they contain spaces. An unterminated span runs
38
45
  // to the end of the query.
@@ -49,9 +56,10 @@ export function tokenize(query) {
49
56
  if (query[i] === "-")
50
57
  i++;
51
58
  const open = query[i];
52
- if (open === "/" || open === '"') {
59
+ if (open === "/" || isQuote(open)) {
53
60
  i++;
54
- while (i < n && query[i] !== open)
61
+ const closes = (c) => (open === "/" ? c === "/" : isQuote(c));
62
+ while (i < n && !closes(query[i]))
55
63
  i++;
56
64
  if (i < n)
57
65
  i++; // consume the closer
@@ -68,9 +76,10 @@ export function tokenize(query) {
68
76
  return tokens;
69
77
  }
70
78
  // 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).
79
+ // span is CLOSED around at least one character. Reuses the tokenizer's span logic (same rules:
80
+ // an optional leading -, then the first / or quote opens a span that a closer of its own kind
81
+ // ends). Terms with no span opener are always complete (a bare word, or /foo/tail once the
82
+ // closer is past).
74
83
  export function isCompleteTerm(raw) {
75
84
  if (!raw)
76
85
  return false;
@@ -80,12 +89,16 @@ export function isCompleteTerm(raw) {
80
89
  if (i === raw.length)
81
90
  return false; // a bare "-" while typing is not committable
82
91
  const open = raw[i];
83
- if (open !== "/" && open !== '"')
92
+ if (open !== "/" && !isQuote(open))
84
93
  return true; // no span, so complete
85
94
  i++;
86
- while (i < raw.length && raw[i] !== open)
95
+ const closes = (c) => (open === "/" ? c === "/" : isQuote(c));
96
+ const contentStart = i;
97
+ while (i < raw.length && !closes(raw[i]))
87
98
  i++;
88
- return i < raw.length; // true only when the closer was found
99
+ // true only when the closer was found AND the span holds something: "" or “” would commit as a
100
+ // pill that filters nothing and never turns amber, so it stays in the draft instead.
101
+ return i < raw.length && i > contentStart;
89
102
  }
90
103
  // A tail reads as regex flags only when it is the short flag string fingers actually type:
91
104
  // 1-2 letters from i/m/s/g with no repeats. Longer or letter-repeating tails (img, ims, sms)
@@ -146,8 +159,8 @@ function compileTerm(raw, invalid, hints, kinds) {
146
159
  return null; // invalid regex: inert, reported
147
160
  }
148
161
  }
149
- if (body[0] === '"') {
150
- const closed = body.length >= 2 && body[body.length - 1] === '"';
162
+ if (isQuote(body[0])) {
163
+ const closed = body.length >= 2 && isQuote(body[body.length - 1]);
151
164
  const phrase = (closed ? body.slice(1, -1) : body.slice(1)).toLowerCase();
152
165
  if (!phrase)
153
166
  return null;