Archilyzer · Source

archilyzer

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

commit 49c16369d40de79fc87ec0a737bcb919bd827073
parent 99f1794e45f4d20b1d233709803d1aa8161b5624
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 20:27:17 -0400

umtool: the board's second redraw gap — settled only after the redraw's passive effects; the view, light and list one state

- Race 3, found: R6.1's full run's "`e` did not focus the claim" reproduced
  (a throwaway stress spec under CDP CPU throttling, 6x: 10 of 25 rounds on
  3e11767e). The page log showed `e` arriving AFTER the move's commit but
  BEFORE its passive effects: the board counted itself settled at the commit
  (a layout effect), so `e` focused the new claim field, and the deferred
  refocus of the moved line then took the focus back. The remounted list's
  light and j/k listener are passive effects too. The settle point is now a
  passive effect declared after the refocus (and, being the parent's, after
  the list's own): 0 of 25 at 6x, 0 of 40 at 10x.
- The view, the light and the list's key are ONE state with the answer's
  number (`v`), so they can never commit apart; an added section is lit and
  focused in the redraw that draws it, inside the write (it was a second
  remount after the write had ended).
- board.spec: the gap test hits both gaps for certain from inside the page —
  `e` 50 microtasks after the answer is read (before the commit), and `n`
  from a MutationObserver that sees the remounted list arrive (after the
  commit, before the passive effects). 3e11767e fails the second, main
  (639ebb07) the first and the original chain.

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

Diffstat:
Mumtool/components/research/BoardView.tsx | 118+++++++++++++++++++++++++++++++++++++++++--------------------------------------
Mumtool/e2e/board.spec.ts | 114++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------
2 files changed, 131 insertions(+), 101 deletions(-)

diff --git a/umtool/components/research/BoardView.tsx b/umtool/components/research/BoardView.tsx @@ -2,7 +2,7 @@ import Link from "next/link"; import { useRouter } from "next/navigation"; -import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import AppHeader from "@/components/shell/AppHeader"; import { buttonVariants } from "@/components/ui/button"; import { Dialog } from "@/components/ui/dialog"; @@ -123,14 +123,19 @@ type Ask = export default function BoardView({ initial }: { initial: CaseView }) { const router = useRouter(); const hydrated = useHydrated(); - const [view, setView] = useState<CaseView>(initial); + // WHAT IS DRAWN, as ONE state: the case's view, the light, the list's key + // (it remounts on an arrangement) and `v`, which answer this is. One state, + // so they can never commit apart -- React may render an update made with a + // key event's priority before one made from a fetch's continuation, and a + // board whose light, list and view committed in different renders sent a + // key to a line the next render replaced (race 3). + const [board, setBoard] = useState<{ view: CaseView; litId: string | null; listKey: number; v: number }>({ view: initial, litId: null, listKey: 0, v: 0 }); + const { view, litId, listKey } = board; // 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); const [ask, setAsk] = useState<Ask | null>(null); const [askText, setAskText] = useState(""); const [handoff, setHandoff] = useState<"article" | "video" | "sweep" | null>(null); @@ -175,29 +180,38 @@ export default function BoardView({ initial }: { initial: CaseView }) { return null; }); chain.current = run.finally(() => { - // NOT settled yet: the answer is applied (setView, the list's key) but - // not drawn -- React renders it in a later task, and a key can arrive - // in between (under load, often). The ref drops once the render that - // carries this answer has committed (the layout effect below). - answered.current += 1; + pendingRef.current -= 1; setPending((n) => n - 1); - setDrawn((n) => n + 1); }); return run; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); - // Writes answered but not yet drawn. A state update is never rendered ahead - // of one queued before it in the same lane, so the commit that carries - // `drawn`'s update carries the answer's view and list key too. - const answered = useRef(0); - const [drawn, setDrawn] = useState(0); - useLayoutEffect(() => { - pendingRef.current -= answered.current; - answered.current = 0; - }, [drawn]); - const apply = (v: CaseView) => { + + // SETTLED = no write queued or answering AND the last answer is on screen + // with everything that follows a redraw done. An answer is applied (`apply`) + // before it is drawn: React commits it in a later task, and runs the passive + // effects after the commit later still -- the moved line's refocus above, + // the remounted list's light and its j/k listener. A key landing in either + // gap (under load, often) acted on a list or a focus about to change: `e` + // focused the claim, then the refocus put the focus back on the line (race + // 3). So the board is settled only once this effect -- a passive one, + // declared after the refocus, and a parent's, so after the list's own -- + // has run for answer `applied` (`drawnV`). + const applied = useRef(0); + const drawnV = useRef(0); + useEffect(() => { + drawnV.current = board.v; + }, [board.v]); + const settled = () => pendingRef.current === 0 && drawnV.current === applied.current; + + /** Draw an answer: its view, and with it the light and a remount when the list was rearranged. */ + const apply = (v: CaseView, o: { remount?: boolean; lit?: string | null; focus?: string | null } = {}) => { docRef.current = v.case; - setView(v); + applied.current += 1; + const n = applied.current; + if (o.lit !== undefined) litRef.current = o.lit; + if (o.remount) refocus.current = o.focus ?? null; + setBoard((b) => ({ view: v, litId: o.lit !== undefined ? o.lit : b.litId, listKey: o.remount ? b.listKey + 1 : b.listKey, v: n })); }; /** An arrangement (sections, order), computed on the case when its turn comes. */ @@ -207,13 +221,7 @@ export default function BoardView({ initial }: { initial: CaseView }) { 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) { - litRef.current = keep; - setLitId(keep); - } - setListKey((k) => k + 1); + apply(v, { remount: true, focus: keep, ...(keep ? { lit: keep } : {}) }); }), [write], ); @@ -226,27 +234,24 @@ export default function BoardView({ initial }: { initial: CaseView }) { 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); - } + apply(r.case, "section" in b ? { remount: true, focus: quoteLineId(qid) } : {}); 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], ); + /** The case's fields; `keep` the line lit and focused after a section change (from the answer, if a function). */ const patchCase = useCallback( - (body: Record<string, unknown> | ((d: CaseView["case"]) => Record<string, unknown>), keep: string | null = null) => + ( + body: Record<string, unknown> | ((d: CaseView["case"]) => Record<string, unknown>), + keep: string | null | ((v: CaseView) => 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); - } + const k = typeof keep === "function" ? keep(v) : keep; + apply(v, b.sections ? { remount: true, focus: k, ...(typeof keep === "function" && k ? { lit: k } : {}) } : {}); return v; }), // eslint-disable-next-line react-hooks/exhaustive-deps @@ -292,8 +297,7 @@ export default function BoardView({ initial }: { initial: CaseView }) { (q: Quote) => write(async () => { const r = await call<{ case: CaseView }>(researchCaseQuoteApi(docRef.current.id, q.id), "DELETE"); - apply(r.case); - setListKey((k) => k + 1); + apply(r.case, { remount: true }); say(`Removed “${q.text.slice(0, 60)}${q.text.length > 60 ? "…" : ""}”`); }), // eslint-disable-next-line react-hooks/exhaustive-deps @@ -311,14 +315,14 @@ export default function BoardView({ initial }: { initial: CaseView }) { const t = askText.trim(); setAsk(null); if (a.kind === "add-section" && 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); - } + // The new section is lit and focused in the same redraw that draws it. + await patchCase( + (d) => ({ sections: [...d.sections, { title: t }] }), + (v) => { + const added = v.case.sections.at(-1); + return added ? sectionLineId(added.id) : null; + }, + ); } else if (a.kind === "rename-section" && t) { 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") { @@ -363,7 +367,7 @@ export default function BoardView({ initial }: { initial: CaseView }) { 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; + if (held.current.length === 0 && (typing || settled())) return; e.preventDefault(); e.stopImmediatePropagation(); held.current.push({ key: e.key, code: e.code, altKey: e.altKey, shiftKey: e.shiftKey }); @@ -400,15 +404,15 @@ export default function BoardView({ initial }: { initial: CaseView }) { // Settled (nothing queued or answering, the redraw committed): replay. useEffect(() => { - if (replaying.current || pending > 0 || held.current.length === 0) return; + if (replaying.current || !settled() || held.current.length === 0) return; replaying.current = true; void (async () => { try { - while (held.current.length && pendingRef.current === 0) { + while (held.current.length && settled()) { // 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; + if (!settled()) break; const k = held.current.shift()!; replayKey(k); } @@ -417,11 +421,11 @@ export default function BoardView({ initial }: { initial: CaseView }) { 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); + if (held.current.length && settled()) setKick((n) => n + 1); } })(); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [pending, listKey, heldN, kick]); + }, [pending, board.v, heldN, kick]); useEffect(() => { const onKey = (e: KeyboardEvent) => { @@ -493,7 +497,7 @@ export default function BoardView({ initial }: { initial: CaseView }) { const onLight = useCallback((d: LitDetail) => { litRef.current = d.id; - setLitId(d.id); + setBoard((b) => (b.litId === d.id ? b : { ...b, litId: d.id })); }, []); const s = doc.scope; @@ -537,7 +541,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 || heldN > 0 ? "" : undefined} data-board-keys={keysReady ? "ready" : undefined}> + <div className="min-h-0 flex-1 overflow-auto px-7 pb-4 pt-2" data-board-busy={busy || heldN > 0 || board.v !== applied.current ? "" : undefined} data-board-keys={keysReady ? "ready" : 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"> diff --git a/umtool/e2e/board.spec.ts b/umtool/e2e/board.spec.ts @@ -321,15 +321,68 @@ test("keys pressed while a write is held wait for it, then act on the settled bo expect(order()).toBe("q3 q1"); }); -// THE REDRAW GAP (race 3, after R6.1): a write's answer is applied before it -// is drawn -- React renders it in a later task -- and a key landing between -// the two acted on the list the redraw was about to replace (`e` focused the -// old claim field, the redraw took it away, the claim typed next ran as board -// commands). Under load that gap is wide; here it is hit for certain: the -// page's own Response.json is wrapped (spec-only) so that, when the held -// move's answer is read, `e` is dispatched 50 microtasks later -- after the -// write has finished, before any task (so before React draws the answer). -test("a key landing after a write has answered but before the board has redrawn waits for the redraw", async ({ page }) => { +// THE REDRAW GAPS (race 3, after R6.1). A write's answer is applied before it +// is drawn (React commits it in a later task), and the commit's passive effects +// -- the moved line's refocus, the remounted list's light and j/k listener -- +// run later still. A key landing in either gap acted on a list or a focus about +// to change: `e` focused the claim, then the deferred refocus put the focus +// back on the line, and the claim typed next went nowhere (or ran as board +// commands). Under load the gaps are wide; here each is hit for certain, from +// inside the page (spec-only hooks): +// answer the page's Response.json is wrapped: `e` is dispatched 50 +// microtasks after the held move's answer is read -- after the write, +// before any task, so before the commit; +// commit a MutationObserver sees the remounted list arrive: `e` is +// dispatched in its callback -- after the commit, before the passive +// effects' task. +// Each time the key (`e`, then `n`) must wait, then focus its field, and what +// is typed next must be saved whole. +async function gapRound(page: Page, hook: "answer" | "commit", key: "e" | "n", text: string, dir: "Alt+j" | "Alt+k") { + const h = await holdNext(page, "PATCH", "/cases/lighthouse-case"); + await page.keyboard.press(dir); + await h.seen; + await page.evaluate(([hook, key]) => { + const w = window as unknown as { __gap?: string }; + const send = () => { + const el = (document.activeElement as HTMLElement | null) ?? document.body; + el.dispatchEvent(new KeyboardEvent("keydown", { key, code: `Key${key.toUpperCase()}`, bubbles: true, cancelable: true })); + w.__gap = "sent"; + }; + w.__gap = "armed"; + if (hook === "answer") { + const json = Response.prototype.json; + Response.prototype.json = function (this: Response) { + const p = json.call(this); + if (w.__gap === "armed" && this.url.endsWith("/api/research/cases/lighthouse-case")) { + w.__gap = "answered"; + Response.prototype.json = json; + void p.then(async () => { + for (let i = 0; i < 50; i++) await null; + send(); + }); + } + return p; + }; + } else { + const root = document.querySelector("[data-board-keys]")!; + const mo = new MutationObserver((records) => { + const remounted = records.some((r) => [...r.addedNodes].some((n) => n instanceof HTMLElement && n.matches("[data-lit-list]"))); + if (!remounted) return; + mo.disconnect(); + send(); + }); + mo.observe(root, { childList: true, subtree: true }); + } + }, [hook, key] as const); + h.release(); + await page.waitForFunction(() => (window as unknown as { __gap?: string }).__gap === "sent"); + await page.keyboard.type(text); + await page.keyboard.press("Enter"); + await expect(page.locator("[data-board-busy]")).toHaveCount(0); + await h.done(); +} + +test("a key in the gap between a write's answer and its redraw, or its redraw and its effects, waits for both", async ({ page }) => { await openBoard(page, "lighthouse-case"); const b = board(page); await expect(b.locator("[data-quote]")).toHaveCount(3); @@ -343,47 +396,20 @@ test("a key landing after a write has answered but before the board has redrawn await b.locator('[data-quote="q3"]').click({ position: { x: 8, y: 8 } }); await expect(litId(page)).toHaveAttribute("data-lit-id", "q:q3"); - const h = await holdNext(page, "PATCH", "/cases/lighthouse-case"); - await page.keyboard.press("Alt+j"); - await h.seen; - await page.evaluate(() => { - const w = window as unknown as { __gap?: string }; - w.__gap = "armed"; - const json = Response.prototype.json; - Response.prototype.json = function (this: Response) { - const p = json.call(this); - if (w.__gap === "armed" && this.url.endsWith("/api/research/cases/lighthouse-case")) { - w.__gap = "answered"; - void p.then(async () => { - for (let i = 0; i < 50; i++) await null; - const el = (document.activeElement as HTMLElement | null) ?? document.body; - el.dispatchEvent(new KeyboardEvent("keydown", { key: "e", code: "KeyE", bubbles: true, cancelable: true })); - w.__gap = "sent"; - Response.prototype.json = json; - }); - } - return p; - }; - }); - h.release(); - await page.waitForFunction(() => (window as unknown as { __gap?: string }).__gap === "sent"); - await page.keyboard.type("Recorded in the gap"); - await page.keyboard.press("Enter"); + await gapRound(page, "answer", "e", "Recorded in the gap", "Alt+j"); await expect.poll(() => quote("q3").claim).toBe("Recorded in the gap"); - await expect(page.locator("[data-board-busy]")).toHaveCount(0); - await h.done(); expect(order()).toBe("q1 q3"); + await expect(litId(page)).toBeFocused(); + + await gapRound(page, "commit", "n", "Noted after the redraw", "Alt+k"); + await expect.poll(() => quote("q3").note).toBe("Noted after the redraw"); + expect(quote("q3").claim).toBe("Recorded in the gap"); + expect(order()).toBe("q3 q1"); expect(caseJson("lighthouse-case").title).toBe("Lighthouse case"); await expect(page.locator("dialog[open]")).toHaveCount(0); // Back as the tests below expect it. - expect((await page.request.patch("/api/research/cases/lighthouse-case/quotes/q3", { data: { claim: "" } })).ok()).toBe(true); - await page.reload(); - await expect(page.locator('[data-board-keys="ready"]')).toHaveCount(1); - await b.locator('[data-quote="q3"]').click({ position: { x: 8, y: 8 } }); - await page.keyboard.press("Alt+k"); - await expect.poll(order).toBe("q3 q1"); - await expect(page.locator("[data-board-busy]")).toHaveCount(0); + expect((await page.request.patch("/api/research/cases/lighthouse-case/quotes/q3", { data: { claim: "", note: "" } })).ok()).toBe(true); }); test("the export: cited markdown in the house format, copied and downloadable", async ({ page, context, request }) => {