Agent page: a changed view waits while the reader reads history
Jonas Templestein, 2026-11-28 01:48 UTC · 1c1c7152fd9219760ae6782714a807f3ed38432c · parent f5fd37e
10 files changed
- M src/agent-kind-view/bridge.ts
- M src/agent-kind-view/dash-agents.test.tsx
- M src/agent-kind-view/dash-agents.tsx
- M src/agent-kind-view/frame-view.test.tsx
- M src/agent-kind-view/frame-view.tsx
- M src/agent-kind-view/host.ts
- M src/components/virtual-log/AGENTS.md
- M src/components/virtual-log/use-reader.ts
- M src/components/virtual-log/virtual-log-scroll.test.tsx
- M src/components/virtual-log/virtual-log.tsx
M src/agent-kind-view/bridge.ts
@@ -4,7 +4,8 @@ // host → frame `update(delta)`: what changed of the view's inputs since the last update. Events // go as the pages added at either end, never the whole log again. // host → frame `start(input)`: the kind's `newAgent.start`, for the Dash's New agent. -// frame → host `loaded(…)` once (what the live read should include), then the verbs: message, +// frame → host `loaded(…)` once (what the live read should include), `atEnd(…)` when its reader +// leaves or reaches the end of the view's lists, then the verbs: message, // append, fileUrl, storeFiles, setState, loadOlder, readEvents, and an MCP App's callTool and // readResource. Each acts on the one agent the host shows; // the host never hands over its context stub, whose `invoke` and `cd` reach the @@ -71,6 +72,11 @@ export interface AgentKindViewHostApi { loaded(result: AgentKindViewLoaded): void; + /** `false`: the frame's reader is away from the end of a list of the view (they read history); + * `true`: back at the end. The page cannot see the frame's scroll, and holds a changed view + * until the reader is back: a new frame starts at the end. A frame that has said nothing is at + * the end. */ + atEnd(atEnd: boolean): void; message(input: Parameters<AgentKindViewProps["onMessage"]>[0]): Promise<void>; append(events: unknown[]): Promise<void>; fileUrl(path: string): Promise<string>;
M src/agent-kind-view/dash-agents.test.tsx
@@ -727,6 +727,101 @@ expect(again.host.querySelector("[role=log]")).not.toBe(null); }); +test.for<{ name: string; change: "source" | "kind" }>([ + { name: "the kinds say another source of its file", change: "source" }, + { name: "the catalog says another kind", change: "kind" }, +])( + "a frame whose reader reads history keeps its place when $name: the view changes once they are back at the end, and the store has the new view at once", + async ({ change }) => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const path = `/agents/claude-reading-${change}`; + await rememberKindView(path, "export default { old: true };"); + const second = mind({ + kinds: { claude: "agent-kinds/claude.ts" }, + source: change === "source" ? "export default {};" : "export default { old: true };", + // the frame's load starts the read: a log with rows keeps the store's record + logs: { [path]: [words(1, "Hello")] }, + }); + second.holdKinds(); + await using again = await draw(DashAgents, second.itx, { waiting: 0, agents: "unread" }); + const frame = again.host.querySelector("iframe")!; + const view = await viewFrame(frame); + await act(async () => void (await view.atEnd(false))); + second.releaseKinds(); + await again.draw( + change === "source" + ? claudeRows(path) + : agentRowsOf({ agents: { [path]: { createdAt: now, kind: "iterate" } } }), + ); + // the same element: the frame's document and the reader's place in it stay + expect(again.host.querySelector("iframe")).toBe(frame); + // a reload draws the new view + expect(savedLogTails(member).peek(path)?.view).toMatchObject( + change === "source" + ? { kind: "claude", file: { source: "export default {};" } } + : { kind: "iterate", file: undefined }, + ); + await act(async () => void (await view.atEnd(true))); + // iterate's chat is a part that loads first: the frame stays, hidden, until it has + await drawnUntil(() => { + if (change === "source") { + expect(again.host.querySelector("iframe")).not.toBe(null); + expect(again.host.querySelector("iframe")).not.toBe(frame); + } else { + expect(again.host.querySelector("iframe")).toBe(null); + expect(again.host.querySelector("[role=log]")).not.toBe(null); + } + }); + }, +); + +test("a frame whose reader reads history: another view mounts once the page is hidden, when nobody looks", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const path = "/agents/claude-hidden"; + await rememberKindView(path, "export default { old: true };"); + const second = mind({ kinds: { claude: "agent-kinds/claude.ts" }, source: "export default {};" }); + second.holdKinds(); + await using again = await draw(DashAgents, second.itx, { waiting: 0, agents: "unread" }); + const frame = again.host.querySelector("iframe")!; + const view = await viewFrame(frame); + await act(async () => void (await view.atEnd(false))); + second.releaseKinds(); + await again.draw(claudeRows(path)); + expect(again.host.querySelector("iframe")).toBe(frame); + using _hidden = hiddenPage(); + await again.settle(); + expect(again.host.querySelector("iframe")).not.toBe(null); + expect(again.host.querySelector("iframe")).not.toBe(frame); +}); + +test("an iterate agent's chat whose reader scrolled up keeps its place when the catalog says a kind with a file, and the frame comes when they are back at the end", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _layout = laidOut(); + const path = "/agents/iterate-reading"; + history.replaceState(null, "", `/agents${path}`); + const { itx } = mind({ + kinds: { claude: "agent-kinds/claude.ts" }, + logs: { [path]: [words(1, "Words to read again")] }, + }); + await using page = await draw(DashAgents, itx, { + waiting: 0, + agents: agentRowsOf({ agents: { [path]: { createdAt: now, kind: "iterate" } } }), + }); + // the chat's part loads after the page drew + await drawnUntil(() => expect(page.host.querySelector("[role=log]")).not.toBe(null)); + const log = page.host.querySelector("[role=log]"); + const scroller = page.host.querySelector<HTMLElement>("[data-slot=virtual-log]")!; + Object.defineProperty(scroller, "scrollHeight", { configurable: true, get: () => 2_400 }); + readerScrolls(scroller, 0, -120); + await page.draw(claudeRows(path)); + expect(page.host.querySelector("iframe")).toBe(null); + expect(page.host.querySelector("[role=log]")).toBe(log); + // back at the end: 2,400 px of rows less the view's 600 + readerScrolls(scroller, 1_800, 120); + await page.settle(); + expect(page.host.querySelector("iframe")).not.toBe(null); +}); + test("another member's remembered view is never drawn: the page waits for the kinds and the catalog as on a first visit", async () => { vi.spyOn(console, "error").mockImplementation(() => {}); const path = "/agents/claude-of-a"; @@ -3526,6 +3621,68 @@ } const host = newMessagePortRpcSession<AgentKindViewHostApi>(await port, new Frame()); await host.loaded({ ephemeralEvents: [], newAgent: kind.newAgent }); +} + +/** THE FRAME'S SIDE OF A KIND'S VIEW, as frame.ts plays it: it says it is ready, takes the page's + * port and reports its kind file. The answer is the page's side of the session, for the frame's + * words to it (`atEnd`). jsdom runs no frame script. */ +async function viewFrame(iframe: HTMLIFrameElement) { + const window = iframe.contentWindow!; + const port = new Promise<MessagePort>((resolve) => { + // the cast: the page calls `postMessage(hello, "*", [port])`, the overload the spy's type omits + vi.spyOn(window, "postMessage").mockImplementation((...args: unknown[]) => + resolve((args[2] as MessagePort[])[0]!), + ); + }); + await act(async () => + globalThis.dispatchEvent( + new MessageEvent("message", { source: window, data: { type: AGENT_KIND_VIEW_READY } }), + ), + ); + class Frame extends RpcTarget { + update() {} + start() { + return []; + } + } + const host = newMessagePortRpcSession<AgentKindViewHostApi>(await port, new Frame()); + await act(async () => void (await host.loaded({ ephemeralEvents: [] }))); + return host; +} + +/** Waits for what `check` expects, a frame at a time. Each wait is an act of its own: React draws + * only when one ends, so a part that loads meanwhile is drawn between two checks. */ +async function drawnUntil(check: () => void) { + await vi.waitFor( + async () => { + await act(() => new Promise((resolve) => setTimeout(resolve, 20))); + check(); + }, + { timeout: 4_000 }, + ); +} + +/** A reader's scroll of a virtual log to `top`: the wheel says which way, then the scroll lands. */ +function readerScrolls(scroller: HTMLElement, top: number, deltaY: number) { + act(() => { + scroller.dispatchEvent(new WheelEvent("wheel", { deltaY, bubbles: true })); + scroller.scrollTop = top; + scroller.dispatchEvent(new Event("scroll")); + }); +} + +/** The page hidden, as the browser says it when another tab is in front; disposing shows it. */ +function hiddenPage() { + const say = () => document.dispatchEvent(new Event("visibilitychange")); + Object.defineProperty(document, "visibilityState", { configurable: true, get: () => "hidden" }); + say(); + return { + [Symbol.dispose]: () => { + // the cast: the document's own key is not indexable by a string in its type + delete (document as unknown as Record<string, unknown>).visibilityState; + say(); + }, + }; } /** The new-agent composer of a drawn page. Its editor is a part that loads after the page drew,
M src/agent-kind-view/dash-agents.tsx
@@ -90,6 +90,7 @@ } from "#/lib/agent-summary.ts"; import { itxSessionOf, keptRead, versionOf, type KeptRead } from "#/lib/itx-session.ts"; import { sameView, savedLogTails, type SavedView } from "#/lib/saved-log-tail.ts"; +import { ReaderAtEnd, readersAtEnd, useReportAtEnd } from "#/components/virtual-log/use-reader.ts"; import { go, hrefOf, linkTo, pageHref, usePageParam, useView } from "#/lib/page-url.ts"; type Itx = AuthenticatedApp["itx"]; @@ -714,7 +715,12 @@ * iterate's chat over the log of another kind holds no row, and would say that nothing was said. * A remembered view is drawn at once, and stays the same element when the kinds and the catalog * say the same view; when they say another, that one is mounted in its place. A path that the - * catalog does not list draws as iterate's. */ + * catalog does not list draws as iterate's. + * ANOTHER VIEW WAITS FOR THE READER. A new element is a new chat, or a new frame, drawn from its + * end: one publish of the mind's config moved the row in the middle of a reader's view by + * 1,902 px. So while a list of the drawn chat is away from its end (`ReaderAtEnd`: a kind's + * frame says it through its link), the view stays as it is. It changes when the reader is back + * at the end, or the page is hidden. The store keeps the new view at once: a reload draws it. */ function AgentViewOfKind({ itx, path, @@ -745,11 +751,20 @@ const { files, kinds } = useKindFiles(itx); // the view the mind's answer says, once the kinds and the catalog have both answered const said = useMemo(() => kinds && agents && viewOf(path, agents, kinds), [path, agents, kinds]); + // whether the reader of the drawn chat is at its end: until a list says otherwise, they are + const [atEnd, setAtEnd] = useState(true); + const [reportAtEnd] = useState(() => readersAtEnd(setAtEnd)); + const hidden = useSyncExternalStore( + watchVisibility, + () => document.visibilityState === "hidden", + () => false, + ); // What is drawn, and its mount: a view the mind's answer changes is another element. const [drawn, setDrawn] = useState<{ view: SavedView; mount: number } | undefined>(); const shown = drawn || (remembered && { view: remembered, mount: 0 }); + const waits = Boolean(shown) && !atEnd && !hidden; const next = - said && !(shown && sameView(shown.view, said)) + said && !(shown && sameView(shown.view, said)) && !waits ? { view: said, mount: (shown?.mount ?? 0) + 1 } : shown; if (next !== drawn) setDrawn(next); @@ -772,36 +787,46 @@ ); } const { view, mount } = next; - return view.file ? ( - <KindChat - key={mount} - itx={itx} - path={path} - file={view.file} - agents={agents} - presence={presence} - call={Boolean(call)} - share={Boolean(share)} - me={me} - tails={tails} - /> - ) : ( - <IterateChat - key={mount} - itx={itx} - path={path} - kind={view.kind} - agents={agents} - opener={opener} - presence={presence} - call={call} - share={share} - me={me} - tails={tails} - /> + return ( + <ReaderAtEnd value={reportAtEnd}> + {view.file ? ( + <KindChat + key={mount} + itx={itx} + path={path} + file={view.file} + agents={agents} + presence={presence} + call={Boolean(call)} + share={Boolean(share)} + me={me} + tails={tails} + /> + ) : ( + <IterateChat + key={mount} + itx={itx} + path={path} + kind={view.kind} + agents={agents} + opener={opener} + presence={presence} + call={call} + share={share} + me={me} + tails={tails} + /> + )} + </ReaderAtEnd> ); } +/** The page is hidden or shown: a view that waited for its reader changes while nobody looks. */ +function watchVisibility(changed: () => void) { + document.addEventListener("visibilitychange", changed); + return () => document.removeEventListener("visibilitychange", changed); +} + /** The view that the catalog and the kinds say for `path`. */ function viewOf(path: string, agents: readonly AgentRow[], kinds: KindFile[]): SavedView { // a row with no kind, and a path with no row, are drawn alike: as iterate's @@ -1025,7 +1050,9 @@ const { view, patchView } = useView(); const session = itxSessionOf(itx); const agent = useHeldContext(session, () => itx.cd(path), [itx, path]); - const { link, loaded } = useAgentKindViewLink(file.name, file.source); + const { link, loaded, atEnd } = useAgentKindViewLink(file.name, file.source); + // the frame's lists are in another document: their reader's place is what the frame said + useReportAtEnd(atEnd); const load = useMemo(() => frameLoadOf(loaded), [loaded]); // every durable event (the frame's Events tab is the whole log) and, by name, the ephemeral // ones the view reads, which a wildcard never matches; nothing until the frame has said which
M src/agent-kind-view/frame-view.test.tsx
@@ -224,6 +224,42 @@ expect(frame.host.loadOlder).not.toHaveBeenCalled(); }); +test("the frame tells the host when its reader leaves the end of a kind's AgentChat and when they are back, with no prop of the kind's file", async () => { + using _layout = laidOut(); + const { html, ui } = agentKindViewKit; + const view: LoadedView = { + // as the kind `agent` writes its view + component: (props: AgentKindViewProps) => html`<${ui.AgentChat} ...${props} />`, + ephemeralEvents: [], + }; + using frame = await mount( + { caughtUp: true, older: null, events: [event(1, "test/said")], tabsInHeader: true }, + view, + ); + const scroller = document.querySelector<HTMLElement>("[data-slot=virtual-log]")!; + Object.defineProperty(scroller, "scrollHeight", { configurable: true, get: () => 2_400 }); + // a chat drawn at its end says nothing: the host counts a frame that said nothing as there + expect(frame.host.atEnd).not.toHaveBeenCalled(); + await readerScrolls(scroller, 0, -120); + expect(frame.host.atEnd.mock.calls).toEqual([[false]]); + // back at the end: 2,400 px of rows less the view's 600 + await readerScrolls(scroller, 1_800, 120); + expect(frame.host.atEnd.mock.calls).toEqual([[false], [true]]); +}); + +test("a page older than the frame's word on its reader's place refuses it, and the frame shows nothing of the refusal", async () => { + using _layout = laidOut(); + using frame = await mount({ caughtUp: true, older: null, events: [event(1, "test/said")] }); + frame.host.atEnd.mockImplementation(() => { + throw new Error("no such method: atEnd"); + }); + const scroller = document.querySelector<HTMLElement>("[data-slot=virtual-log]")!; + Object.defineProperty(scroller, "scrollHeight", { configurable: true, get: () => 2_400 }); + await readerScrolls(scroller, 0, -120); + expect(frame.host.atEnd).toHaveBeenCalledWith(false); + expect(document.querySelector("[data-type=error]")).toBeNull(); +}); + test.for<{ name: string; offsets: number[]; answered: "rows" | "empty" }>([ { name: "a session with words", offsets: [1, 2], answered: "rows" }, { name: "a session in which nothing was said", offsets: [], answered: "empty" }, @@ -264,6 +300,16 @@ }, ); +/** A reader's scroll of a virtual log to `top`: the wheel says which way, then the scroll lands. + * What the frame tells the host goes after a microtask. */ +async function readerScrolls(scroller: HTMLElement, top: number, deltaY: number) { + await act(async () => { + scroller.dispatchEvent(new WheelEvent("wheel", { deltaY, bubbles: true })); + scroller.scrollTop = top; + scroller.dispatchEvent(new Event("scroll")); + }); +} + /** Older pages remain, and none is being read. */ function pagesLeft() { return { loading: false, exhausted: false }; @@ -425,7 +471,7 @@ documentClass: "", ...sent, }); - const host = { loadOlder: vi.fn(), setState: vi.fn() }; + const host = { loadOlder: vi.fn(), setState: vi.fn(), atEnd: vi.fn() }; const root = createRoot(document.body.appendChild(document.createElement("div"))); await act(async () => root.render(<FrameView inputs={inputs} host={host as never} view={view} />),
M src/agent-kind-view/frame-view.tsx
@@ -6,6 +6,7 @@ import { AgentShell } from "../components/agent-chat/agent-shell.tsx"; import { AgentTabsInHeader } from "../components/agent-chat/agent-shell-contexts.ts"; import { OLDER_FAILED } from "../components/virtual-log/older-pages.ts"; +import { ReaderAtEnd, readersAtEnd } from "../components/virtual-log/use-reader.ts"; import type { AgentKindViewHostApi, AgentKindViewInputs } from "./bridge.ts"; import type { InputsStore, LoadedView } from "./frame.ts"; import type { AgentKindViewProps } from "./types.ts"; @@ -31,12 +32,25 @@ () => held && propsOf(held, host, verbs, kindFileError), [held, host, verbs, kindFileError], ); + // the page cannot read this document's scroll: the view's lists say through the host whether + // the reader is at their end, with no prop of the kind's file + const reportAtEnd = useMemo(() => readersAtEnd((atEnd) => tellAtEnd(host, atEnd)), [host]); // the page's header has the tabs: every shell in the frame draws none return ( - <AgentTabsInHeader value={Boolean(held?.tabsInHeader)}> - <FrameBody props={props} view={view} /> - </AgentTabsInHeader> + <ReaderAtEnd value={reportAtEnd}> + <AgentTabsInHeader value={Boolean(held?.tabsInHeader)}> + <FrameBody props={props} view={view} /> + </AgentTabsInHeader> + </ReaderAtEnd> ); +} + +/** The reader's place, to the host. A page older than this verb refuses it and mounts a changed + * view at once, as before: the refusal is no error of the view's. */ +function tellAtEnd(host: Host, atEnd: boolean) { + void Promise.resolve() + .then(() => host.atEnd(atEnd)) + .catch(() => {}); } function FrameBody({ props, view }: { props: AgentKindViewProps | undefined; view: LoadedView }) {
M src/agent-kind-view/host.ts
@@ -23,7 +23,7 @@ * `storeFiles` refuses a message with files that a kind appends itself. */ export type AgentKindViewVerbs = Omit< AgentKindViewHostApi, - "loaded" | "storeFiles" | "callTool" | "readResource" | "readContext" | "readEvents" + "loaded" | "atEnd" | "storeFiles" | "callTool" | "readResource" | "readContext" | "readEvents" > & Partial< Pick< @@ -39,6 +39,7 @@ /** The page's verbs as of its last render. */ verbs: AgentKindViewVerbs | undefined; #loaded: AgentKindViewLoaded | undefined; + #atEnd = true; #listeners = new Set<() => void>(); #frame: RpcStub<AgentKindViewFrameApi> | undefined; #sent: AgentKindViewInputs | undefined; @@ -50,6 +51,8 @@ } loaded = () => this.#loaded; + /** Whether the frame's reader is at the end of the view's lists, as it last said. */ + atEnd = () => this.#atEnd; subscribe = (listener: () => void) => { this.#listeners.add(listener); return () => void this.#listeners.delete(listener); @@ -71,6 +74,8 @@ if (event.source !== iframe.contentWindow || event.data?.type !== AGENT_KIND_VIEW_READY) return; this.#close(); + // a new document draws its lists at their ends + this.setAtEnd(true); const channel = new MessageChannel(); const hello: AgentKindViewHello = { type: "iterate/agent-kind-view", @@ -105,6 +110,12 @@ for (const listener of this.#listeners) listener(); } + setAtEnd(atEnd: boolean) { + if (atEnd === this.#atEnd) return; + this.#atEnd = atEnd; + for (const listener of this.#listeners) listener(); + } + #close() { this.#frame?.[Symbol.dispose](); this.#frame = undefined; @@ -126,6 +137,10 @@ loaded(result: Parameters<AgentKindViewHostApi["loaded"]>[0]) { this.#link.setLoaded(result); } + // the frame runs a config repo's code: a word that is no boolean is not heard + atEnd(atEnd: unknown) { + if (typeof atEnd === "boolean") this.#link.setAtEnd(atEnd); + } message(input: Parameters<AgentKindViewHostApi["message"]>[0]) { return this.#verbs().message(input); } @@ -168,12 +183,14 @@ } } -/** A link for the kind file `name` (its `source`, or `null` for a kind without one), and what its - * frame reported once it read the file: until then, `undefined`. */ +/** A link for the kind file `name` (its `source`, or `null` for a kind without one), what its + * frame reported once it read the file (until then, `undefined`), and whether its reader is at + * the end of the view's lists. */ export function useAgentKindViewLink(name: string, source: string | null) { const link = useMemo(() => new AgentKindViewLink(name, source), [name, source]); const loaded = useSyncExternalStore(link.subscribe, link.loaded, () => undefined); - return { link, loaded }; + const atEnd = useSyncExternalStore(link.subscribe, link.atEnd, () => true); + return { link, loaded, atEnd }; } export function AgentKindViewFrame({
M src/components/virtual-log/AGENTS.md
@@ -42,6 +42,9 @@ a finger on a phone. - What a person touches stays theirs (`use-reader.ts`). A finger on the glass holds the view until it lifts. A row that a press opens past the height of the view shows from its top. +- Every list under a `ReaderAtEnd` (`use-reader.ts`) says whether its reader is at its end. The + Dash's agent page holds a changed view while one is not, and a kind's frame passes it on to the + page: a view is never handed the report as a prop. - The footer brings its own background. - The browser's find sees only the rows in the DOM.
M src/components/virtual-log/use-reader.ts
@@ -3,8 +3,11 @@ // with no one asking, and while the virtualizer catches up the position alone says "behind". Being // there again is all it takes to be back. import { + createContext, + use, useCallback, useEffect, + useId, useRef, useState, type KeyboardEvent, @@ -36,6 +39,44 @@ scrollHeight - clientHeight - scrollTop; const nearEnd = (scroller: Element) => Math.abs(shortOfEnd(scroller)) <= SCROLL_END_THRESHOLD; + +/** One list's word on where its reader is: `log` names the list, `atEnd` is `undefined` when the + * list is gone. */ +export type ReportAtEnd = (log: string, atEnd: boolean | undefined) => void; + +/** WHERE THE READER IS, FOR A PAGE THAT CANNOT SEE THE SCROLL. Each virtual log under it says + * whether its reader is at its end. The Dash mounts a changed view of an agent as a new element, + * which throws a reader in history back to the end (1,902 px at one publish), so it holds the + * change while a list of the chat is away from its end. A kind's view runs in a sandboxed frame + * whose scroll the page cannot read: the frame's runtime puts this around the view, and the + * view's lists report with no prop that a kind's file has to pass. */ +export const ReaderAtEnd = createContext<ReportAtEnd | undefined>(undefined); + +/** Says to the `ReaderAtEnd` around the caller whether its reader is at the end; nothing without + * one. */ +export function useReportAtEnd(atEnd: boolean) { + const report = use(ReaderAtEnd); + const log = useId(); + // apart from the report of each change: a gone list is said once, never between two reports + useEffect(() => { + if (!report) return; + return () => report(log, undefined); + }, [report, log]); + useEffect(() => report?.(log, atEnd), [report, log, atEnd]); +} + +/** Many lists' reports as one answer: at the end while no list is away from its end, so a list + * that has said nothing yet counts as at the end. `changed` hears each change of the answer. */ +export function readersAtEnd(changed: (atEnd: boolean) => void): ReportAtEnd { + const away = new Set<string>(); + return (log, atEnd) => { + const before = away.size === 0; + if (atEnd === false) away.add(log); + else away.delete(log); + const now = away.size === 0; + if (now !== before) changed(now); + }; +} export function useReader( footerRef: RefObject<HTMLElement | null>,
M src/components/virtual-log/virtual-log-scroll.test.tsx
@@ -1,9 +1,11 @@ // @vitest-environment jsdom -// Unit checks for VirtualLog scroll stability: pixel-based overscan over runs of 4 px rows and -// surviving-row fallback anchoring when a prepend re-keys the oldest row at scrollTop 0. +// Unit checks for VirtualLog scroll stability: pixel-based overscan over runs of 4 px rows, +// surviving-row fallback anchoring when a prepend re-keys the oldest row at scrollTop 0, and the +// reader's place said to a page that cannot see the scroll (`ReaderAtEnd`). import { act, type ReactElement } from "react"; import { createRoot } from "react-dom/client"; import { beforeAll, expect, test } from "vitest"; +import { ReaderAtEnd, readersAtEnd } from "./use-reader.ts"; import { VirtualLog, type VirtualLogRowInfo } from "./virtual-log.tsx"; (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; @@ -190,3 +192,52 @@ ); expect(scroller.scrollTop).toBe(1_300); }); + +test("under ReaderAtEnd the logs say whether their reader is at the end: away while one log is, and a log that goes while away holds nothing up", () => { + const heard: boolean[] = []; + const report = readersAtEnd((atEnd) => heard.push(atEnd)); + const rows: TestRow[] = Array.from({ length: 40 }, (_, i) => ({ + id: `row-${i}`, + offset: i + 1, + estimate: 60, + })); + const log = (label: string) => ( + <VirtualLog + key={label} + rows={rows} + rowInfo={ROW_INFO} + renderRow={(row) => <div data-row={row.id}>{row.id}</div>} + label={label} + /> + ); + using view = mount( + <ReaderAtEnd value={report}> + {log("chat")} + {log("trace")} + </ReaderAtEnd>, + 60, + ); + const [chat, trace] = view.container.querySelectorAll<HTMLDivElement>( + '[data-slot="virtual-log"]', + ); + for (const scroller of [chat!, trace!]) + Object.defineProperty(scroller, "scrollHeight", { configurable: true, get: () => 2_400 }); + // drawn at their ends, the logs say nothing + expect(heard).toEqual([]); + readerScrolls(chat!, 0, -120); + readerScrolls(trace!, 0, -120); + // back at the end: 2,400 px of rows less the view's 600; the trace is still away + readerScrolls(chat!, 1_800, 120); + expect(heard).toEqual([false]); + view.rerender(<ReaderAtEnd value={report}>{log("chat")}</ReaderAtEnd>); + expect(heard).toEqual([false, true]); +}); + +/** A reader's scroll of a log to `top`: the wheel says which way, then the scroll lands. */ +function readerScrolls(scroller: HTMLDivElement, top: number, deltaY: number) { + act(() => { + scroller.dispatchEvent(new WheelEvent("wheel", { deltaY, bubbles: true })); + scroller.scrollTop = top; + scroller.dispatchEvent(new Event("scroll")); + }); +}
M src/components/virtual-log/virtual-log.tsx
@@ -59,7 +59,7 @@ type NewerPages, type OlderPages, } from "./older-pages.ts"; -import { SCROLL_END_THRESHOLD, useReader } from "./use-reader.ts"; +import { SCROLL_END_THRESHOLD, useReader, useReportAtEnd } from "./use-reader.ts"; /** Rows kept mounted at the edge the view is bound for: a view's worth at the smallest rows on a * usual screen, so that a jump there, which the virtualizer only reads back a frame later, lands on @@ -162,6 +162,8 @@ const { atEnd, atTop, atEndRef, goingToTopRef, touchingRef, pressedRef, follow, runOwnScroll } = reader; const attachedToHead = newer.exhausted; + // a window of history away from the head is history too, wherever its scroll is + useReportAtEnd(atEnd && attachedToHead); const visibleTail = attachedToHead ? tail : undefined; const count = rows.length + (visibleTail ? 1 : 0); const virtualizer = useLogVirtualizer({