Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit e6bcf51f6876c0499fdb33f314ac118b3643aac1
parent 4ef7dd96f4e8e8bb9366a1b86ffc6fd59ccb9cd8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 16:35:00 -0400

umtool: the board's races — one write queue, keys held while it settles and replayed on the redrawn board

- Every board write (a move, a claim, a note, the speaker check, a section,
  a removal, a re-verify, a hand-off's reload) goes through ONE queue: run in
  the order asked, each computed on the case the last one left, each answer
  applied in order. Two writes in flight used to race their answers, and the
  speaker toggle was computed on the render that queued it.
- A key pressed while a write is queued or answering is held (a capture
  listener, before the list's j/k or any field) and replayed once the board
  has settled, one per frame: a command acts on the redrawn board, text lands
  in the field it was typed for, Enter submits it. Replaces R5's pending-field
  rule, which swallowed the text typed while it waited.
- The light is read from a ref the list sets, not the last render.
- Dialog: a field marked data-autofocus takes the focus after showModal (React's
  autoFocus never writes the attribute the browser reads); the board's ask uses it.
- board.spec: a new test holds a write at the network (page.route) and presses
  e + a claim full of command letters + Enter, n + note + Enter then s twice,
  alt+k then j, a + a title + Enter, x then Escape under it — each asserted on
  the settled board.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/components/research/BoardView.tsx | 379+++++++++++++++++++++++++++++++++++++++++++++----------------------------------
Mumtool/components/ui/dialog.tsx | 8+++++++-
Mumtool/e2e/board.spec.ts | 147++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
3 files changed, 371 insertions(+), 163 deletions(-)

diff --git a/umtool/components/research/BoardView.tsx b/umtool/components/research/BoardView.tsx @@ -39,10 +39,29 @@ import QuoteSlip, { quoteLineId } from "./QuoteSlip"; // // Every change is the API's (app/api/research/cases/route.ts); the board // redraws from what it answers. +// +// ONE WRITER, AND KEYS ON A SETTLED BOARD (the board.spec races, root-caused +// after P6a). Every write -- a move, a claim, a note, the speaker check, a +// section, a removal, a re-verify -- goes through ONE queue (`write`): run in +// the order asked, each computed on the case the previous one left, each +// answer applied in order (two writes in flight used to race their answers: +// an older one landing last put the speaker check back). While a write is +// queued or answering, the board's keys are BUFFERED, not acted on: the list +// is about to be redrawn (it remounts on an arrangement), so a key acting now +// acts on lines and fields the answer replaces -- `e` focused a field the +// redraw took away and the claim typed after it ran as commands (`r` opened +// the case's rename, `s` toggled the speaker, Enter renamed the case). Once +// the board has settled, the buffer is replayed in order, one key per frame: +// a command acts on the redrawn board, text lands in the field it was typed +// for (`e` + text + Enter is a saved claim, `a` + text + Enter a section). // --------------------------------------------------------------------------- const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']"; const sectionLineId = (sid: string | null) => `s:${sid ?? "unsorted"}`; +/** A key held while the board settles, replayed after. */ +type HeldKey = { key: string; code: string; altKey: boolean; shiftKey: boolean }; +/** The keys besides a character that the buffer holds (Tab and the modifiers pass). */ +const HOLDABLE = new Set(["Enter", "Escape", "Backspace", "Delete", "ArrowUp", "ArrowDown", "Home", "End"]); async function call<T>(url: string, method: string, body?: unknown): Promise<T> { const r = await fetch(url, { @@ -104,7 +123,10 @@ export default function BoardView({ initial }: { initial: CaseView }) { const router = useRouter(); const hydrated = useHydrated(); const [view, setView] = useState<CaseView>(initial); - const [busy, setBusy] = useState(false); + // Writes queued or answering (the ref is read synchronously by the keys). + const [pending, setPending] = useState(0); + const pendingRef = useRef(0); + const busy = pending > 0; const [status, setStatus] = useState<{ text: string; href?: string; tone?: "error" } | null>(null); const [litId, setLitId] = useState<string | null>(null); const [listKey, setListKey] = useState(0); @@ -116,8 +138,9 @@ export default function BoardView({ initial }: { initial: CaseView }) { const doc = view.case; const groups = useMemo(() => groupsOf(doc) as unknown as BoardGroup[], [doc]); const byId = useMemo(() => new Map(doc.quotes.map((q) => [q.id, q])), [doc]); - const litQuote = litId?.startsWith("q:") ? (byId.get(litId.slice(2)) ?? null) : null; - const litSection = litId?.startsWith("s:") && litId !== "s:unsorted" ? (doc.sections.find((s) => s.id === litId.slice(2)) ?? null) : null; + // The light as the list last said it (a ref: a key in the same tick as a + // j/k reads where the light is, not where the last render had it). + const litRef = useRef<string | null>(null); const say = (text: string, extra: { href?: string; tone?: "error" } = {}) => setStatus({ text, ...extra }); const fail = (e: unknown) => say((e as Error).message, { tone: "error" }); @@ -133,142 +156,105 @@ export default function BoardView({ initial }: { initial: CaseView }) { el?.scrollIntoView({ block: "nearest" }); }, [listKey]); - // The case as the last answer left it: a queued move is computed on it, not + // The case as the last answer left it: a queued write is computed on it, not // on the render that queued it. const docRef = useRef(doc); docRef.current = doc; + const quoteNow = (qid: string) => docRef.current.quotes.find((q) => q.id === qid) ?? null; + + // THE ONE QUEUE. `op` runs when every write before it has answered; its + // answer is applied before the next starts. A failed write says why and the + // ones behind it still run, each on the case as it now is. + const chain = useRef<Promise<unknown>>(Promise.resolve()); + const write = useCallback(<T,>(op: () => Promise<T>): Promise<T | null> => { + pendingRef.current += 1; + setPending((n) => n + 1); + const run = chain.current.then(op).catch((e: unknown) => { + fail(e); + return null; + }); + chain.current = run.finally(() => { + pendingRef.current -= 1; + setPending((n) => n - 1); + }); + return run; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + const apply = (v: CaseView) => { + docRef.current = v.case; + setView(v); + }; + /** An arrangement (sections, order), computed on the case when its turn comes. */ const arrange = useCallback( - async (next: { sections: unknown; order: unknown } | null, keep: string | null): Promise<boolean> => { - if (!next) return true; - setBusy(true); - try { - const v = await call<CaseView>(researchCaseApi(doc.id), "PATCH", next); - docRef.current = v.case; + (next: (d: CaseView["case"]) => { sections: unknown; order: unknown } | null, keep: string | null) => + write(async () => { + const body = next(docRef.current); + if (!body) return; + const v = await call<CaseView>(researchCaseApi(docRef.current.id), "PATCH", body); + apply(v); refocus.current = keep; - if (keep) setLitId(keep); - setView(v); + if (keep) { + litRef.current = keep; + setLitId(keep); + } setListKey((k) => k + 1); - return true; - } catch (e) { - fail(e); - return false; - } finally { - setBusy(false); - } - }, - [doc.id], - ); - - // MOVES ARE QUEUED, never dropped: an alt+j/k pressed while the last move - // is still answering is applied after it, in order, on the case that move - // left. A move that fails drops the ones queued behind it (and says why). - const moves = useRef<{ kind: "quote" | "section"; id: string; dir: number }[]>([]); - const moving = useRef(false); - const [queued, setQueued] = useState(0); - const pumpMoves = useCallback(async () => { - if (moving.current) return; - moving.current = true; - try { - while (moves.current.length) { - const m = moves.current.shift()!; - setQueued(moves.current.length); - const d = docRef.current; - const ok = - m.kind === "quote" - ? await arrange(moveQuote(d, m.id, m.dir), quoteLineId(m.id)) - : await arrange(moveSection(d, m.id, m.dir), sectionLineId(m.id)); - if (!ok) moves.current = []; - } - } finally { - moving.current = false; - setQueued(0); - } - }, [arrange]); - // A FIELD ASKED FOR WHILE THE LIST IS BEING REDRAWN (e, n, m pressed while a - // move or a section write is answering): focusing it now would put the caret - // in an input the answer is about to replace (the list remounts on every - // arrangement), and the keys typed next would land on the line as commands -- - // `s` toggling the speaker check, `x` asking to remove the quote. So the - // field waits for the redraw and takes the focus then; until it does, the - // board's keys are held (Escape lets go). - const pendingField = useRef<{ qid: string; field: string } | null>(null); - useEffect(() => { - const want = pendingField.current; - if (!want || busy || queued > 0 || moving.current) return; - pendingField.current = null; - document.querySelector<HTMLElement>(`[data-quote="${CSS.escape(want.qid)}"] [data-field="${want.field}"]`)?.focus(); - }, [listKey, busy, queued]); - - const queueMove = useCallback( - (m: { kind: "quote" | "section"; id: string; dir: number }) => { - moves.current.push(m); - setQueued(moves.current.length); - void pumpMoves(); - }, - [pumpMoves], + }), + [write], ); + /** A quote's fields; `body` may be computed on the quote as it is when the write runs. */ const patchQuote = useCallback( - async (qid: string, body: Record<string, unknown>) => { - setBusy(true); - try { - const r = await call<{ case: CaseView }>(researchCaseQuoteApi(doc.id, qid), "PATCH", body); - setView(r.case); - if ("section" in body) { + (qid: string, body: Record<string, unknown> | ((q: Quote) => Record<string, unknown>)) => + write(async () => { + const q = quoteNow(qid); + if (!q) return; + const b = typeof body === "function" ? body(q) : body; + const r = await call<{ case: CaseView }>(researchCaseQuoteApi(docRef.current.id, qid), "PATCH", b); + apply(r.case); + if ("section" in b) { refocus.current = quoteLineId(qid); setListKey((k) => k + 1); } - if (body.useCurrentWords) say("The quote now has the transcript's current words; the old ones are kept in its history."); - } catch (e) { - fail(e); - } finally { - setBusy(false); - } - }, - [doc.id], + if (b.useCurrentWords) say("The quote now has the transcript's current words; the old ones are kept in its history."); + }), + // eslint-disable-next-line react-hooks/exhaustive-deps + [write], ); const patchCase = useCallback( - async (body: Record<string, unknown>, keep: string | null = null) => { - setBusy(true); - try { - const v = await call<CaseView>(researchCaseApi(doc.id), "PATCH", body); - setView(v); - if (body.sections) { + (body: Record<string, unknown> | ((d: CaseView["case"]) => Record<string, unknown>), keep: string | null = null) => + write(async () => { + const b = typeof body === "function" ? body(docRef.current) : body; + const v = await call<CaseView>(researchCaseApi(docRef.current.id), "PATCH", b); + apply(v); + if (b.sections) { refocus.current = keep; setListKey((k) => k + 1); } return v; - } catch (e) { - fail(e); - return null; - } finally { - setBusy(false); - } - }, - [doc.id], + }), + // eslint-disable-next-line react-hooks/exhaustive-deps + [write], ); - const verify = useCallback(async () => { - setBusy(true); - say("Re-reading every quote at its cite…"); - try { - const r = await call<{ results: { id: string; verify: { status: string; enOrig?: unknown } }[]; case: CaseView }>(researchCaseVerifyApi(doc.id), "POST", {}); - setView(r.case); - const n = (s: string) => r.results.filter((x) => x.verify.status === s).length; - const en = r.results.filter((x) => x.verify.enOrig).length; - say( - `Re-verified ${r.results.length}: ${n("ok")} as pinned, ${n("drifted")} drifted, ${n("missing")} missing` + - (n("unreadable") ? `, ${n("unreadable")} not readable` : "") + - (en ? `; en-orig differs at ${en}` : ""), - ); - } catch (e) { - fail(e); - } finally { - setBusy(false); - } - }, [doc.id]); + const verify = useCallback( + () => + write(async () => { + say("Re-reading every quote at its cite…"); + const r = await call<{ results: { id: string; verify: { status: string; enOrig?: unknown } }[]; case: CaseView }>(researchCaseVerifyApi(docRef.current.id), "POST", {}); + apply(r.case); + const n = (s: string) => r.results.filter((x) => x.verify.status === s).length; + const en = r.results.filter((x) => x.verify.enOrig).length; + say( + `Re-verified ${r.results.length}: ${n("ok")} as pinned, ${n("drifted")} drifted, ${n("missing")} missing` + + (n("unreadable") ? `, ${n("unreadable")} not readable` : "") + + (en ? `; en-orig differs at ${en}` : ""), + ); + }), + // eslint-disable-next-line react-hooks/exhaustive-deps + [write], + ); const copyMarkdown = useCallback(async () => { try { @@ -284,28 +270,24 @@ export default function BoardView({ initial }: { initial: CaseView }) { } catch (e) { fail(e); } + // eslint-disable-next-line react-hooks/exhaustive-deps }, [doc.id]); const removeQuote = useCallback( - async (q: Quote) => { - setBusy(true); - try { - const r = await call<{ case: CaseView }>(researchCaseQuoteApi(doc.id, q.id), "DELETE"); - setView(r.case); + (q: Quote) => + write(async () => { + const r = await call<{ case: CaseView }>(researchCaseQuoteApi(docRef.current.id, q.id), "DELETE"); + apply(r.case); setListKey((k) => k + 1); say(`Removed “${q.text.slice(0, 60)}${q.text.length > 60 ? "…" : ""}”`); - } catch (e) { - fail(e); - } finally { - setBusy(false); - } - }, - [doc.id], + }), + // eslint-disable-next-line react-hooks/exhaustive-deps + [write], ); const openAsk = (a: Ask) => { setAsk(a); - setAskText(a.kind === "rename-section" ? a.title : a.kind === "rename-case" ? doc.title : ""); + setAskText(a.kind === "rename-section" ? a.title : a.kind === "rename-case" ? docRef.current.title : ""); }; const submitAsk = async () => { @@ -314,17 +296,18 @@ export default function BoardView({ initial }: { initial: CaseView }) { const t = askText.trim(); setAsk(null); if (a.kind === "add-section" && t) { - const v = await patchCase({ sections: [...doc.sections, { title: t }] }); + const v = await patchCase((d) => ({ sections: [...d.sections, { title: t }] })); const added = v?.case.sections.at(-1); if (added) { refocus.current = sectionLineId(added.id); + litRef.current = sectionLineId(added.id); setLitId(sectionLineId(added.id)); setListKey((k) => k + 1); } } else if (a.kind === "rename-section" && t) { - await patchCase({ sections: doc.sections.map((s) => (s.id === a.sid ? { id: s.id, title: t } : s)) }, sectionLineId(a.sid)); + await patchCase((d) => ({ sections: d.sections.map((s) => (s.id === a.sid ? { id: s.id, title: t } : s)) }), sectionLineId(a.sid)); } else if (a.kind === "remove-section") { - await patchCase({ sections: doc.sections.filter((s) => s.id !== a.sid) }, sectionLineId(null)); + await patchCase((d) => ({ sections: d.sections.filter((s) => s.id !== a.sid) }), sectionLineId(null)); } else if (a.kind === "rename-case" && t) { await patchCase({ title: t }); } else if (a.kind === "remove-quote") { @@ -336,42 +319,111 @@ export default function BoardView({ initial }: { initial: CaseView }) { const qid = dragging.current; dragging.current = null; if (!qid || qid === target) return; - const t = byId.get(target); - if (!t) return; - const g = groups.find((x) => x.quotes.some((q) => q.id === target))!; - const without = g.quotes.filter((q) => q.id !== qid); - const at = without.findIndex((q) => q.id === target) + (after ? 1 : 0); - void arrange(placeQuote(doc, qid, g.id, at), quoteLineId(qid)); + void arrange((d) => { + const g = (groupsOf(d) as unknown as BoardGroup[]).find((x) => x.quotes.some((q) => q.id === target)); + if (!g) return null; + const without = g.quotes.filter((q) => q.id !== qid); + const at = without.findIndex((q) => q.id === target) + (after ? 1 : 0); + return placeQuote(d, qid, g.id, at); + }, quoteLineId(qid)); }; // ── keys ── + // + // The buffer: a key pressed while a write is queued or answering, or while + // earlier keys still wait, is held (in a capture listener, before the list's + // own j/k or any field sees it) and replayed once the board has settled. + const held = useRef<HeldKey[]>([]); + const replaying = useRef(false); + const dispatching = useRef(false); + const [heldN, setHeldN] = useState(0); + const [kick, setKick] = useState(0); + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (dispatching.current || e.metaKey || e.ctrlKey) return; + if (e.key.length !== 1 && !HOLDABLE.has(e.key)) return; + const typing = !!(e.target as HTMLElement | null)?.closest?.(TYPING); + // A field the operator is typing in is left alone unless earlier keys + // are still waiting (then this one waits behind them, in order). + if (held.current.length === 0 && (typing || pendingRef.current === 0)) return; + e.preventDefault(); + e.stopImmediatePropagation(); + held.current.push({ key: e.key, code: e.code, altKey: e.altKey, shiftKey: e.shiftKey }); + setHeldN(held.current.length); + }; + window.addEventListener("keydown", onKey, true); + return () => window.removeEventListener("keydown", onKey, true); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + /** Replay one held key where the focus is now: into a field as text, else as the key it was. */ + const replayKey = (k: HeldKey) => { + const el = (document.activeElement as HTMLElement | null) ?? document.body; + dispatching.current = true; + try { + const field = el.matches?.("input:not([type=checkbox]):not([type=radio]), textarea") ? (el as HTMLInputElement | HTMLTextAreaElement) : null; + if (field && (k.key.length === 1 || k.key === "Backspace")) { + const proto = field instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; + const next = k.key === "Backspace" ? field.value.slice(0, -1) : field.value + k.key; + Object.getOwnPropertyDescriptor(proto, "value")?.set?.call(field, next); + field.dispatchEvent(new Event("input", { bubbles: true })); + return; + } + const ev = new KeyboardEvent("keydown", { key: k.key, code: k.code, altKey: k.altKey, shiftKey: k.shiftKey, bubbles: true, cancelable: true }); + const handled = !el.dispatchEvent(ev); + // What only a trusted key does by itself: Enter submits a form, Escape closes a dialog. + if (!handled && field && k.key === "Enter") field.form?.requestSubmit(); + if (!handled && k.key === "Escape") el.closest("dialog")?.close(); + } finally { + dispatching.current = false; + } + }; + + // Settled (nothing queued or answering, the redraw committed): replay. + useEffect(() => { + if (replaying.current || pending > 0 || held.current.length === 0) return; + replaying.current = true; + void (async () => { + try { + while (held.current.length && pendingRef.current === 0) { + // A frame between keys: what the last one did (a focus, a dialog, a + // new light) is on screen before the next one acts. + await new Promise((r) => setTimeout(r, 16)); + if (pendingRef.current > 0) break; + const k = held.current.shift()!; + replayKey(k); + } + } finally { + replaying.current = false; + setHeldN(held.current.length); + // A write that started and answered while this loop waited a frame + // changed `pending` under it: look again. + if (held.current.length && pendingRef.current === 0) setKick((n) => n + 1); + } + })(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [pending, listKey, heldN, kick]); + useEffect(() => { const onKey = (e: KeyboardEvent) => { if (e.defaultPrevented || e.metaKey || e.ctrlKey) return; if ((e.target as HTMLElement | null)?.closest?.(TYPING)) return; if (document.querySelector("dialog[open]")) return; - if (pendingField.current) { - // A field is waiting for the redraw: no key is a command until it has the focus. - if (e.key === "Escape") pendingField.current = null; - if (!e.altKey && e.key.length === 1) e.preventDefault(); - return; - } + const id = litRef.current; + const d = docRef.current; + const litQuote = id?.startsWith("q:") ? (d.quotes.find((q) => q.id === id.slice(2)) ?? null) : null; + const litSection = id?.startsWith("s:") && id !== "s:unsorted" ? (d.sections.find((s) => s.id === id.slice(2)) ?? null) : null; if (e.altKey) { const dir = e.code === "KeyJ" || e.key === "ArrowDown" ? 1 : e.code === "KeyK" || e.key === "ArrowUp" ? -1 : 0; if (!dir) return; e.preventDefault(); - if (litQuote) queueMove({ kind: "quote", id: litQuote.id, dir }); - else if (litSection) queueMove({ kind: "section", id: litSection.id, dir }); + if (litQuote) void arrange((c) => moveQuote(c, litQuote.id, dir), quoteLineId(litQuote.id)); + else if (litSection) void arrange((c) => moveSection(c, litSection.id, dir), sectionLineId(litSection.id)); return; } const focusField = (f: string) => { if (!litQuote) return; - if (busy || moving.current || moves.current.length > 0) { - e.preventDefault(); - pendingField.current = { qid: litQuote.id, field: f }; - return; - } - const el = document.querySelector<HTMLElement>(`[data-quote="${litQuote.id}"] [data-field="${f}"]`); + const el = document.querySelector<HTMLElement>(`[data-quote="${CSS.escape(litQuote.id)}"] [data-field="${f}"]`); if (el) { e.preventDefault(); el.focus(); @@ -388,7 +440,8 @@ export default function BoardView({ initial }: { initial: CaseView }) { focusField("section"); break; case "s": - if (litQuote && litQuote.cite.kind !== "post") void patchQuote(litQuote.id, { speakerChecked: !litQuote.speakerChecked }); + // Toggled on the quote as it is when the write runs, not as this render drew it. + if (litQuote && litQuote.cite.kind !== "post") void patchQuote(litQuote.id, (q) => ({ speakerChecked: !q.speakerChecked })); break; case "x": case "Delete": @@ -404,14 +457,14 @@ export default function BoardView({ initial }: { initial: CaseView }) { else openAsk({ kind: "rename-case" }); break; case "v": - if (!busy) void verify(); + void verify(); break; case "c": void copyMarkdown(); break; case "/": e.preventDefault(); - router.push(researchFromCaseHref(doc)); + router.push(researchFromCaseHref(docRef.current)); break; } }; @@ -419,7 +472,10 @@ export default function BoardView({ initial }: { initial: CaseView }) { return () => document.removeEventListener("keydown", onKey); }); - const onLight = useCallback((d: LitDetail) => setLitId(d.id), []); + const onLight = useCallback((d: LitDetail) => { + litRef.current = d.id; + setLitId(d.id); + }, []); const s = doc.scope; const where = view.sourceLabel ?? (s.source ? s.source.replace(/^(local|remote|hub):/, "") : "no source yet"); @@ -462,7 +518,7 @@ export default function BoardView({ initial }: { initial: CaseView }) { /> <div className="grid min-h-0 flex-1 grid-cols-[minmax(0,1fr)_300px]"> <div className="flex min-h-0 min-w-0 flex-col"> - <div className="min-h-0 flex-1 overflow-auto px-7 pb-4 pt-2" data-board-busy={busy || queued > 0 ? "" : undefined}> + <div className="min-h-0 flex-1 overflow-auto px-7 pb-4 pt-2" data-board-busy={busy || heldN > 0 ? "" : undefined}> {doc.quotes.length === 0 && doc.sections.length === 0 ? ( <EmptyState title="No quotes on this board yet"> <Link prefetch={false} href={researchFromCaseHref(doc)} className="ink-link"> @@ -482,7 +538,7 @@ export default function BoardView({ initial }: { initial: CaseView }) { onDropTop={() => { const qid = dragging.current; dragging.current = null; - if (qid) void arrange(placeQuote(doc, qid, g.id, 0), quoteLineId(qid)); + if (qid) void arrange((d) => placeQuote(d, qid, g.id, 0), quoteLineId(qid)); }} /> {g.quotes.map((q) => ( @@ -588,7 +644,7 @@ export default function BoardView({ initial }: { initial: CaseView }) { value={notes} rows={4} onChange={(e) => setNotes(e.target.value)} - onBlur={() => notes !== doc.notes && void patchCase({ notes })} + onBlur={() => notes !== docRef.current.notes && void patchCase({ notes })} placeholder="What this case is about; the export's summary" className="resize-y rounded-[3px] border border-seam-2 bg-ground px-2 py-1.5 text-[12.5px] text-text outline-none placeholder:text-muted-2 focus:border-muted" /> @@ -640,6 +696,7 @@ export default function BoardView({ initial }: { initial: CaseView }) { ) : ( <input autoFocus + data-autofocus="" aria-label="Title" value={askText} maxLength={120} @@ -670,7 +727,7 @@ export default function BoardView({ initial }: { initial: CaseView }) { onDone={(href, what) => { setHandoff(null); say(what, { href }); - void call<CaseView>(researchCaseApi(doc.id), "GET").then(setView, () => {}); + void write(async () => apply(await call<CaseView>(researchCaseApi(docRef.current.id), "GET"))); }} /> </> diff --git a/umtool/components/ui/dialog.tsx b/umtool/components/ui/dialog.tsx @@ -24,7 +24,13 @@ export function Dialog({ useEffect(() => { const d = ref.current; if (!d) return; - if (open && !d.open) d.showModal(); + if (open && !d.open) { + d.showModal(); + // The browser's focusing steps read the `autofocus` ATTRIBUTE, which + // React's autoFocus never writes: a field that should take the focus + // says so with data-autofocus. + d.querySelector<HTMLElement>("[data-autofocus]")?.focus(); + } if (!open && d.open) d.close(); }, [open]); return ( diff --git a/umtool/e2e/board.spec.ts b/umtool/e2e/board.spec.ts @@ -1,4 +1,4 @@ -import { test, expect, type Page } from "@playwright/test"; +import { test, expect, type Page, type Route } from "@playwright/test"; import { readFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; @@ -25,6 +25,31 @@ const board = (page: Page) => page.getByRole("group", { name: "Board" }); const litId = (page: Page) => board(page).locator("[data-lit-line][data-lit]"); const status = (page: Page) => page.locator("[data-board-status]"); +/** + * Hold the next board write matching `method` and `part` at the network: it + * reaches the server only on `release()`. While it is held the board is + * settling, deterministically, for as long as the spec needs. + */ +async function holdNext(page: Page, method: string, part: string) { + let release!: () => void; + const gate = new Promise<void>((r) => (release = r)); + let arrived!: () => void; + const seen = new Promise<void>((r) => (arrived = r)); + let taken = false; + const pattern = "**/api/research/cases/**"; + const handler = async (route: Route) => { + const req = route.request(); + if (!taken && req.method() === method && req.url().includes(part)) { + taken = true; + arrived(); + await gate; + } + await route.continue(); + }; + await page.route(pattern, handler); + return { seen, release, done: () => page.unroute(pattern, handler) }; +} + async function searched(page: Page) { await page.goto(researchHref({ q: RESEARCH_PHRASE })); await expect(page.locator("[data-honest]")).toBeVisible({ timeout: 30_000 }); @@ -166,6 +191,126 @@ test("sections and order: a, alt+j/k across sections, the section menu; claim, n await expect.poll(() => caseJson("lighthouse-case").sections.map((s: { id: string }) => s.id).join(" ")).toBe("s2 s1"); }); +// THE RACES (root-caused after P6a): every key below is pressed while a board +// write is HELD at the network, so the board is settling for certain. Each +// key must wait for it and then act on the redrawn board -- not on lines and +// fields the answer replaces. On the board as test 102 left it: Unsorted q3, +// q1; The keeper q2; Approval. +test("keys pressed while a write is held wait for it, then act on the settled board", async ({ page }) => { + await page.goto(researchCaseHref("lighthouse-case")); + const b = board(page); + await expect(b.locator("[data-quote]")).toHaveCount(3); + const busy = page.locator("[data-board-busy]"); + const quote = (id: string) => caseJson("lighthouse-case").quotes.find((q: { id: string }) => q.id === id); + // Unsorted's order (the case's `quotes` array is the board's order). + const order = () => + caseJson("lighthouse-case") + .quotes.filter((q: { section: string | null }) => q.section === null) + .map((q: { id: string }) => q.id) + .join(" "); + await expect.poll(order).toBe("q3 q1"); + await b.locator('[data-quote="q3"]').click({ position: { x: 8, y: 8 } }); + await expect(litId(page)).toHaveAttribute("data-lit-id", "q:q3"); + + // 1. A move held; `e`, a claim and Enter typed under it. The claim's letters + // are board commands (r renames the case, a adds a section, c copies, v + // re-verifies, x removes): none may act; all of it is the claim. + let h = await holdNext(page, "PATCH", "/cases/lighthouse-case"); + await page.keyboard.press("Alt+j"); + await h.seen; + await page.keyboard.press("e"); + await page.keyboard.type("Recorded at the vote, x-ray"); + await page.keyboard.press("Enter"); + await expect(busy).toHaveCount(1); + await expect(page.locator("dialog[open]")).toHaveCount(0); + expect(quote("q3").claim).toBe(""); + h.release(); + await expect.poll(() => quote("q3").claim).toBe("Recorded at the vote, x-ray"); + await expect(busy).toHaveCount(0); + await h.done(); + expect(order()).toBe("q1 q3"); + expect(caseJson("lighthouse-case").title).toBe("Lighthouse case"); + await expect(page.locator("dialog[open]")).toHaveCount(0); + await expect(b.locator('[data-quote="q3"] [data-field="claim"]')).toHaveValue("Recorded at the vote, x-ray"); + await expect(litId(page)).toHaveAttribute("data-lit-id", "q:q3"); + + // 2. A note's save held; `s` twice under it. Each toggle is computed on the + // quote as the write before it left it: on, then off -- in that order, + // and the view says what the file says. + const speaker: boolean[] = []; + page.on("request", (r) => { + if (r.method() === "PATCH" && r.url().includes("/quotes/q3")) { + const body = r.postDataJSON() as { speakerChecked?: boolean }; + if (typeof body.speakerChecked === "boolean") speaker.push(body.speakerChecked); + } + }); + h = await holdNext(page, "PATCH", "/quotes/q3"); + await page.keyboard.press("n"); + await page.keyboard.type("held note"); + await page.keyboard.press("Enter"); + await h.seen; + await page.keyboard.press("s"); + await page.keyboard.press("s"); + await expect(busy).toHaveCount(1); + h.release(); + await expect(busy).toHaveCount(0); + await h.done(); + expect(speaker).toEqual([true, false]); + expect(quote("q3")).toMatchObject({ note: "held note", speakerChecked: false }); + await expect(b.locator('[data-quote="q3"] [data-speaker]')).toHaveAttribute("data-speaker", "unchecked"); + + // 3. A move held; `j` under it moves the light on the REDRAWN list: from q3, + // put back above q1, to q1 (the old list would have lit what came after + // q3 where it was, and the redraw then took the light back). + h = await holdNext(page, "PATCH", "/cases/lighthouse-case"); + await page.keyboard.press("Alt+k"); + await h.seen; + await page.keyboard.press("j"); + h.release(); + await expect.poll(order).toBe("q3 q1"); + await expect(busy).toHaveCount(0); + await h.done(); + await expect(litId(page)).toHaveAttribute("data-lit-id", "q:q1"); + + // 4. A save held; `a`, a title and Enter under it add a section once it has + // answered (the dialog's field takes the focus); `x` then Escape under + // another leave every quote where it is. + await page.keyboard.press("k"); + await expect(litId(page)).toHaveAttribute("data-lit-id", "q:q3"); + h = await holdNext(page, "PATCH", "/quotes/q3"); + await page.keyboard.press("s"); + await h.seen; + await page.keyboard.press("a"); + await page.keyboard.type("Held section"); + await page.keyboard.press("Enter"); + await expect(page.locator("dialog[open]")).toHaveCount(0); + h.release(); + await expect.poll(() => caseJson("lighthouse-case").sections.map((s: { title: string }) => s.title)).toEqual(["The keeper", "Approval", "Held section"]); + await expect(busy).toHaveCount(0); + await h.done(); + expect(quote("q3").speakerChecked).toBe(true); + + await b.locator('[data-quote="q3"]').click({ position: { x: 8, y: 8 } }); + h = await holdNext(page, "PATCH", "/quotes/q3"); + await page.keyboard.press("s"); + await h.seen; + await page.keyboard.press("x"); + await page.keyboard.press("Escape"); + h.release(); + await expect(busy).toHaveCount(0); + await h.done(); + await expect(page.locator("dialog[open]")).toHaveCount(0); + await expect(b.locator("[data-quote]")).toHaveCount(3); + expect(quote("q3").speakerChecked).toBe(false); + + // Put the board back as the tests below expect it: no extra section, q3's + // claim and note cleared. + const sections = caseJson("lighthouse-case").sections.filter((s: { title: string }) => s.title !== "Held section"); + expect((await page.request.patch("/api/research/cases/lighthouse-case", { data: { sections } })).ok()).toBe(true); + expect((await page.request.patch("/api/research/cases/lighthouse-case/quotes/q3", { data: { claim: "", note: "" } })).ok()).toBe(true); + expect(order()).toBe("q3 q1"); +}); + test("the export: cited markdown in the house format, copied and downloadable", async ({ page, context, request }) => { const md = await (await request.get("/api/research/cases/lighthouse-case/export.md")).text(); const heads = md.split("\n").filter((l) => l.startsWith("#"));