Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(chat): preserve reading anchors before painted layout changes
new-Beginner11fa50d372ad
diff --git a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.tsindex f8d314dc1..231b415ef 100644--- a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts+++ b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts@@ -8,6 +8,7 @@ import {type Hold = {position: TranscriptReadingPosition;+ point?: { element: HTMLElement; offset: number };settled: boolean;stableFrames: number;page: boolean;@@ -24,18 +25,41 @@ const layoutChanged = (held: Hold, sourceHead: string | undefined) =>held.height !== held.scroller.scrollHeight || held.viewport !== held.scroller.clientHeight ||held.alignedHead !== sourceHead;+function messageRow(content: HTMLElement, position: TranscriptReadingPosition) {+ const id = CSS.escape(position.messageId ?? "");+ return content.querySelector<HTMLElement>(`[data-message-id="${id}"]`)+ ?? content.querySelector<HTMLElement>(`[data-minimap-id="${id}"]`);+}++function contentPoint(scroller: HTMLElement, content: HTMLElement, position: TranscriptReadingPosition) {+ const viewport = scroller.getBoundingClientRect();+ const row = messageRow(content, position);+ for (const element of row?.querySelectorAll<HTMLElement>(".prose-chat p, .prose-chat li, .prose-chat pre, .prose-chat h1, .prose-chat h2, .prose-chat h3, .message-user-text") ?? []) {+ const rect = element.getBoundingClientRect();+ if (rect.height > 0 && rect.bottom > viewport.top && rect.top < viewport.bottom) {+ return { element, offset: rect.top - viewport.top };+ }+ }+}+/** Single-flight page IO and pre-paint anchoring follow the reader's newest* position without blocking input. Cancelled IO cannot acquire a newer target. */-export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, sourceHead, onStart, onPosition, onSettled }: {+export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, sourceHead, canRetain, onStart, onPosition, onSettled }: {scrollRef: RefObject<HTMLDivElement | null>;contentRef: RefObject<HTMLDivElement | null>;visible: boolean;sourceHead: string | undefined;+ canRetain: (paging: boolean) => boolean;onStart: () => void;onPosition: (top: number) => void;onSettled: () => void;}) {const holdRef = useRef<Hold | null>(null);+ // Request ownership ends after settlement; reading ownership lasts until+ // explicit navigation, follow, hide, or unmount takes the viewport back.+ const readingRef = useRef<Hold | null>(null);+ const resizeRef = useRef<ResizeObserver | null>(null);+ const observedRowsRef = useRef(new Set<HTMLElement>());const inFlightRef = useRef(false);const frameRef = useRef(0);const autoBlockedRef = useRef(false);@@ -46,11 +70,20 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, souconst retry = useCallback(() => { autoBlockedRef.current = false; }, []);const [phase, setPhase] = useState<"idle" | "mount" | "page">("idle");const [, refresh] = useState(0);- const callbacks = useRef({ onStart, onPosition, onSettled });- callbacks.current = { onStart, onPosition, onSettled };+ const callbacks = useRef({ canRetain, onStart, onPosition, onSettled });+ callbacks.current = { canRetain, onStart, onPosition, onSettled };+ const readingHold = useCallback(() => {+ if (!callbacks.current.canRetain(holdRef.current !== null)) {+ readingRef.current = null;+ return null;+ }+ if (holdRef.current) return holdRef.current;+ return readingRef.current;+ }, []);const dropHold = useCallback(() => {holdRef.current = null;+ readingRef.current = null;cancelAnimationFrame(frameRef.current);frameRef.current = 0;}, []);@@ -58,9 +91,23 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, soudropHold();setPhase("idle");}, [dropHold]);+ const captureHold = useCallback((windowSize: number, page = false): Hold | null => {+ const scroller = scrollRef.current;+ const content = contentRef.current;+ if (!scroller || !content) return null;+ const position = captureTranscriptReadingPosition(scroller, content, false, windowSize)+ ?? { pinned: false, offset: 0, scrollTop: scroller.scrollTop, windowSize };+ return { position, point: contentPoint(scroller, content, position), settled: false, stableFrames: 0, page, windowSize,+ sourceHead: sourceHeadRef.current, alignedHead: sourceHeadRef.current,+ height: scroller.scrollHeight, top: scroller.scrollTop, viewport: scroller.clientHeight, scroller };+ }, [contentRef, scrollRef]);const isHeld = useCallback(() => holdRef.current !== null, []);- const track = useCallback(() => {- const held = holdRef.current;+ const track = useCallback((windowSize = 0) => {+ let held = readingHold();+ if (!held && callbacks.current.canRetain(false)) {+ held = captureHold(windowSize);+ readingRef.current = held;+ }const scroller = scrollRef.current;const content = contentRef.current;if (!held || !scroller || !content) return;@@ -68,41 +115,51 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, sou// to a newly exposed, estimated row lets its late layout move the text away.held.position = { ...held.position, offset: held.position.offset - (scroller.scrollTop - held.top),scrollTop: scroller.scrollTop };+ const movement = scroller.scrollTop - held.top;+ if (held.point) held.point.offset -= movement;if (!layoutChanged(held, sourceHeadRef.current) &&!isTranscriptReadingAnchorVisible(scroller, content, held.position)) {const position = captureTranscriptReadingPosition(scroller, content, false, held.windowSize);- if (position) held.position = position;+ if (position) {+ held.position = position;+ held.point = contentPoint(scroller, content, position);+ }+ }+ if (!layoutChanged(held, sourceHeadRef.current) && (!held.point?.element.isConnected ||+ held.point.offset >= scroller.clientHeight || held.point.offset + held.point.element.getBoundingClientRect().height <= 0)) {+ held.point = contentPoint(scroller, content, held.position);}held.top = scroller.scrollTop;- }, [contentRef, scrollRef]);+ }, [captureHold, contentRef, readingHold, scrollRef]);const restore = useCallback(() => {- const held = holdRef.current;+ const held = readingHold();const scroller = scrollRef.current;const content = contentRef.current;if (!held || !scroller || !content) return false;track();- if (!layoutChanged(held, sourceHeadRef.current)) return false;const before = scroller.scrollTop;- restoreTranscriptReadingPosition(scroller, content, held.position);+ const changed = layoutChanged(held, sourceHeadRef.current);+ if (held.point?.element.isConnected) {+ const delta = held.point.element.getBoundingClientRect().top - scroller.getBoundingClientRect().top - held.point.offset;+ if (Math.abs(delta) > 0.5) scroller.scrollTop += delta;+ const row = messageRow(content, held.position);+ if (row) held.position = { ...held.position, offset: row.getBoundingClientRect().top - scroller.getBoundingClientRect().top };+ } else restoreTranscriptReadingPosition(scroller, content, held.position);held.height = scroller.scrollHeight;held.viewport = scroller.clientHeight;held.alignedHead = sourceHeadRef.current;held.top = scroller.scrollTop;if (Math.abs(scroller.scrollTop - before) > 1) held.stableFrames = 0;callbacks.current.onPosition(scroller.scrollTop);- return true;- }, [contentRef, scrollRef, track]);+ return changed || Math.abs(scroller.scrollTop - before) > 0.5;+ }, [contentRef, readingHold, scrollRef, track]);const run = useCallback((action: () => void | Promise<void>, windowSize: number, page = false) => {const scroller = scrollRef.current;const content = contentRef.current;if (holdRef.current || inFlightRef.current || autoBlockedRef.current || !scroller || !content) return;- const position = captureTranscriptReadingPosition(scroller, content, false, windowSize)- ?? { pinned: false, offset: 0, scrollTop: scroller.scrollTop, windowSize };- const hold: Hold = { position, settled: false, stableFrames: 0, page, windowSize,- sourceHead: sourceHeadRef.current, alignedHead: sourceHeadRef.current,- height: scroller.scrollHeight, top: scroller.scrollTop, viewport: scroller.clientHeight,- scroller };+ const hold = captureHold(windowSize, page);+ if (!hold) return;holdRef.current = hold; // Synchronous: two scroll events cannot start two pages.inFlightRef.current = true;callbacks.current.onStart();@@ -129,14 +186,14 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, soufinish();console.error("Transcript history page failed", error);}- }, [contentRef, scrollRef]);+ }, [captureHold, contentRef, scrollRef]);// Correct React commits synchronously, before paint, not on raw source length.useLayoutEffect(() => {if (!visible) { cancel(); return; }+ restore();const hold = holdRef.current;if (!hold) return;- restore();if (frameRef.current) return;const align = () => {frameRef.current = 0;@@ -151,6 +208,7 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, sou// A failed/empty read must not loop at an unchanged visible boundary.if (hold.page && hold.sourceHead === sourceHeadRef.current) autoBlockedRef.current = true;dropHold();+ readingRef.current = hold;setPhase("idle");callbacks.current.onSettled();return;@@ -167,7 +225,7 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, souconst scroller = scrollRef.current;if (!content || !scroller) return;const observer = new ResizeObserver(() => {- const held = holdRef.current;+ const held = readingHold();if (!held) return;const before = scroller.scrollTop;restore();@@ -175,8 +233,26 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, sou});observer.observe(content, { box: "border-box" });observer.observe(scroller, { box: "border-box" });- return () => observer.disconnect();- }, [contentRef, restore, scrollRef]);+ resizeRef.current = observer;+ return () => {+ observer.disconnect();+ resizeRef.current = null;+ observedRowsRef.current.clear();+ };+ }, [contentRef, readingHold, restore, scrollRef]);++ // Opposing row resizes can leave the content's total height unchanged.+ // Observe row boxes too, and repair the anchor in this pre-paint delivery,+ // rather than scheduling a correction for the next painted frame.+ useLayoutEffect(() => {+ const observer = resizeRef.current;+ const content = contentRef.current;+ if (!observer || !content) return;+ const rows = new Set(content.querySelectorAll<HTMLElement>("[data-message-id], [data-minimap-id]"));+ for (const row of observedRowsRef.current) if (!rows.has(row)) observer.unobserve(row);+ for (const row of rows) if (!observedRowsRef.current.has(row)) observer.observe(row, { box: "border-box" });+ observedRowsRef.current = rows;+ });useLayoutEffect(() => () => dropHold(), [dropHold]);diff --git a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.tsindex 2bacea480..908dc5f75 100644--- a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts+++ b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts@@ -204,6 +204,8 @@ export function useTranscriptScroll({track: trackHistoryPosition, cancel: cancelHistoryPaging, readLatency: historyReadLatency,} = useTranscriptHistoryPaging({scrollRef, contentRef, visible: paneVisible, sourceHead: messages[0]?.id, onStart: startHistoryReading,+ canRetain: (paging) => paneVisible && !pinnedRef.current && (paging || (!latestNavigation.isActive() &&+ !readingPositionPendingRef.current && !isDisclosureAnchorHeld() && !searchTarget)),onPosition: recordScrollPosition, onSettled: rememberReadingPosition,});const releaseNavigationFollow = useCallback(() => {@@ -487,8 +489,9 @@ export function useTranscriptScroll({pinnedRef.current = transition.pinned;setShowJump(transition.showJump);}+ trackHistoryPosition(windowSize);rememberReadingPosition();- }, [cancelFollowScroll, historyReadLatency, latestNavigation, reachTop, readingPositionPendingRef, readingWindow, recordScrollPosition, rememberReadingPosition, scheduleFollowScroll, trackHistoryPosition]);+ }, [cancelFollowScroll, historyReadLatency, latestNavigation, reachTop, readingPositionPendingRef, readingWindow, recordScrollPosition, rememberReadingPosition, scheduleFollowScroll, trackHistoryPosition, windowSize]);// Send / retry / regenerate always re-pins follow mode so the new prompt and// its stream stay in view, even if the user had scrolled up through history.diff --git a/apps/desktop/src/lib/transcript-reading-position.ts b/apps/desktop/src/lib/transcript-reading-position.tsindex 4cb58c8c1..d754329c0 100644--- a/apps/desktop/src/lib/transcript-reading-position.ts+++ b/apps/desktop/src/lib/transcript-reading-position.ts@@ -101,7 +101,10 @@ export function restoreTranscriptReadingPosition(if (row) {const rect = row.getBoundingClientRect();if (rect.height > 0) {- scroller.scrollTop += rect.top - scroller.getBoundingClientRect().top - position.offset;+ const delta = rect.top - scroller.getBoundingClientRect().top - position.offset;+ // Even assigning the same scrollTop interrupts native smooth travel.+ // Ignore subpixel rounding instead of repeatedly cancelling that input.+ if (Math.abs(delta) > 0.5) scroller.scrollTop += delta;return true;}}@@ -116,6 +119,6 @@ export function restoreTranscriptReadingPosition(// back to it for an approximate position. `false` is reserved for a bookmark// with no usable offset at all, which only a never-laid-out pane produces.if (!Number.isFinite(position.scrollTop) || position.scrollTop < 0) return false;- scroller.scrollTop = position.scrollTop;+ if (Math.abs(scroller.scrollTop - position.scrollTop) > 0.5) scroller.scrollTop = position.scrollTop;return true;}diff --git a/apps/desktop/test/transcript-reading-position-fallback.test.mjs b/apps/desktop/test/transcript-reading-position-fallback.test.mjsindex 4fe40cf85..cecbba4dc 100644--- a/apps/desktop/test/transcript-reading-position-fallback.test.mjs+++ b/apps/desktop/test/transcript-reading-position-fallback.test.mjs@@ -67,6 +67,29 @@ test("an anchored row that is mounted still restores by its rect", () => {assert.equal(scroller.scrollTop, 216);});+test("unchanged/subpixel anchor alignment does not write scrollTop or stop native travel", () => {+ const scroller = fakeScroller({ scrollTop: 480 });+ let top = scroller.scrollTop;+ let writes = 0;+ Object.defineProperty(scroller, "scrollTop", {+ get: () => top,+ set: value => { writes++; top = value; },+ });+ let rowTop = 24;+ const row = { getBoundingClientRect: () => ({ top: rowTop, height: 80 }) };+ const content = fakeContent({ row });+ assert.equal(restoreTranscriptReadingPosition(scroller, content, bookmark()), true);+ rowTop = 24.25;+ assert.equal(restoreTranscriptReadingPosition(scroller, content, bookmark()), true);+ assert.equal(writes, 0);+ rowTop = 144;+ restoreTranscriptReadingPosition(scroller, content, bookmark());+ assert.equal(writes, 1);+ assert.equal(top, 600);+ restoreTranscriptReadingPosition(scroller, fakeContent(), bookmark({ scrollTop: 600 }));+ assert.equal(writes, 1, "an unchanged missing-row fallback also leaves native travel alone");+});+test("a bookmark whose row is above the mounted window falls back to its offset", () => {const scroller = fakeScroller({ scrollTop: 0, top: 0 });const content = fakeContent({ row: null });diff --git a/docs/adr/0130-bounded-mounted-transcript-window.md b/docs/adr/0130-bounded-mounted-transcript-window.mdindex a70debb3e..af67c6eef 100644--- a/docs/adr/0130-bounded-mounted-transcript-window.md+++ b/docs/adr/0130-bounded-mounted-transcript-window.md@@ -53,7 +53,12 @@ reference-equal, and that runs on every streamed token.newest visible message anchor without hiding overflow or discarding input,including the hard-edge (`<= 120px`), explicit continuation, and underfilledtop-boundary fallback. The moving anchor remains owned through IO and three- stable layout frames; it never owns user input. Explicit latest navigation retires+ stable layout frames; it never owns user input. Settlement ends request+ ownership, not reading ownership. Ordinary reading retains the actual+ message and its visible prose block for late layout, with row-level resize+ observation even when total height is unchanged. Navigation/follow/hide+ release that reading state. No-op scroll writes are skipped so compensation+ cannot stop native smooth input. Explicit latest navigation retiresthe prior gesture and hold so queued scroll events cannot start another read.This replaces the old `prependHeightRef` total-height delta: deferred DOM,tail updates, and intrinsic-size estimates made that delta unreliable.diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.mdindex a774779c1..d4752e46d 100644--- a/docs/spec/04-ux/09-interaction-patterns.md+++ b/docs/spec/04-ux/09-interaction-patterns.md@@ -1650,7 +1650,13 @@ Project drag/drop follows these patterns:latency plus `150ms` can increase the lead, capped at`max(base, min(12000px, 12 * clientHeight))`. Cached history mounts before HostIO; requests stay single-flight. The actual-message anchor tracks user- displacement and corrects prepend/layout changes before paint.+ displacement and corrects prepend/layout changes before paint. Request+ settlement does not release the reading anchor: ordinary reading retains its+ actual message and, where available, visible prose block until follow or+ explicit navigation takes over. Row-level resize observation catches changes+ whose total heights cancel. Corrections run in the current layout/resize+ delivery, not in a later painted frame, and unchanged/subpixel alignment does+ not write `scrollTop` and interrupt native smooth scrolling.- All paging paths leave `overflow-y` and input untouched, including the`<= 120px` hard edge, explicit earlier-history actions, and the underfilledtop-boundary observer. Wheel/trackpad, touch and keyboard input continuediff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 5024b9b89..72c98b5f4 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -13627,6 +13627,14 @@ This test plan spec is accepted when:messages, then the actual latest button reaches the bottom with nonblanksampled frames and <=2px tail drift during 600ms after arrival. The isolatedinstance confirms the application's normal quit dialog and exits.+ Late-reading regressions wait until the page has settled, then change content+ above the reading point by 120px, balance it with a -120px change below, and+ change an earlier paragraph inside a long answer. Nonempty pre-paint samples+ must stay within 1px. Six consecutive 20px steps additionally compare the+ actual painted text crop byte-for-byte, not merely the eventual scrollTop.+ Full-Desktop interaction smoke repeats the painted reading check after a real+ Host page. Original native smooth input, resumed follow, search, disclosure,+ hide/reveal and turn-completion paths remain required.- **Specs linked**: `04-ux/09-interaction-patterns.md` §2.2 / §9.1 / §10.4, ADR 0130.- **Acceptance**: C (conversation), Quality.- **Status**: Automated Electron fixture and unit regressions implemented; rundiff --git a/scripts/e2e-transcript-history-loading.mjs b/scripts/e2e-transcript-history-loading.mjsindex 8962806ce..7fbf94d24 100644--- a/scripts/e2e-transcript-history-loading.mjs+++ b/scripts/e2e-transcript-history-loading.mjs@@ -12,6 +12,7 @@ const { build } = createRequire(join(root, "packages/agent-runtime/package.json"const { electronBinary } = resolveElectronBinary(root);const manual = process.argv.includes("--manual");const manualSmoke = process.argv.includes("--manual-smoke");+const anchorOnly = process.argv.includes("--anchor-only");const temp = await mkdtemp(join(process.env.PI_SCRATCH_DIR ?? root, "history-loading-"));try {await build({ entryPoints: [join(root, "scripts/e2e/transcript-history-loading.tsx")],@@ -89,6 +90,32 @@ app.whenReady().then(async () => {console.log('HISTORY_LOADING_PROBE ' + JSON.stringify({ ok: true, manualControls: true, pages: 2 }));app.exit(0); return;}+ const settledResults = [];+ for (const kind of ['late', 'balanced', 'paragraph']) {+ const result = await call('settledLayout(' + JSON.stringify(kind) + ')');+ settledResults.push(result);+ console.log('HISTORY_SETTLED_LAYOUT ' + JSON.stringify(result));+ }+ for (const result of settledResults) {+ assert(result.after.layoutSampleCount >= 8, 'late-layout regression needs actual frame samples');+ assert(result.after.layoutMaxDrift <= 1, 'a painted late-layout frame moved the reading anchor: ' + result.after.layoutMaxDrift);+ if (result.kind === 'balanced') assert(Math.abs(result.totalDelta) <= 1, 'balanced layout fixture changed total height');+ }+ for (const kind of ['late', 'balanced', 'paragraph']) {+ const prepared = await call('prepareSettledLayout(' + JSON.stringify(kind) + ')');+ const baseline = (await win.webContents.capturePage(prepared.crop)).toBitmap();+ assert(new Set(baseline).size > 8, 'pixel probe captured a blank/uniform region');+ for (let amount = 20; amount <= 120; amount += 20) {+ await call('mutateSettledLayout(' + amount + ')');+ const painted = (await win.webContents.capturePage(prepared.crop)).toBitmap();+ assert(baseline.equals(painted), kind + ': painted text changed during layout step ' + amount);+ }+ console.log('HISTORY_PAINTED_ANCHOR ' + JSON.stringify({ kind, captures: 6, identical: true }));+ }+ if (${anchorOnly}) {+ console.log('HISTORY_LOADING_PROBE ' + JSON.stringify({ ok: true, settledLayout: true }));+ app.exit(0); return;+ }const results = [];for (const name of ['wheel', 'quiet', 'tail', 'late-layout', 'failure', 'empty', 'hide']) {await call('reset()');diff --git a/scripts/e2e/full-desktop-transcript.mjs b/scripts/e2e/full-desktop-transcript.mjsindex fe5f192f3..30fa7d848 100644--- a/scripts/e2e/full-desktop-transcript.mjs+++ b/scripts/e2e/full-desktop-transcript.mjs@@ -28,6 +28,7 @@ export async function verifyFullDesktopTranscript({ send, evaluate, waitFor }) {assert(reading.bottom > 100, "upward reading must leave the live bottom");await waitFor(() => evaluate("Boolean(document.querySelector('.jump-latest-btn'))"), 5000, "return-to-latest control");assert(reading.rows > 100 && reading.rows < 1000, "cross the initial Host page without loading the entire conversation");+ const readingAnchor = await verifyReadingAnchor({ send, evaluate });const motion = await evaluate(`new Promise(resolve => {const el = document.querySelector('.thread-scroll');const samples = [];@@ -57,7 +58,51 @@ export async function verifyFullDesktopTranscript({ send, evaluate, waitFor }) {const tailTops = settled.map(sample => sample.tailTop);const drift = Math.max(...tailTops) - Math.min(...tailTops);assert(drift <= 2, `full Desktop bottom handoff drift: ${drift}px`);- const result = { initial, reading, final: await geometry(), samples: motion.samples.length, drift, nativeWheelEvents };+ const result = { initial, reading, final: await geometry(), samples: motion.samples.length, drift, nativeWheelEvents, readingAnchor };console.log("FULL_DESKTOP_INTERACTION " + JSON.stringify(result));return result;}++async function verifyReadingAnchor({ send, evaluate }) {+ const prepared = await evaluate(`(async () => {+ const el = document.querySelector('.thread-scroll');+ for (const row of el.querySelectorAll('.message-row')) row.style.contentVisibility = 'visible';+ let previous = -1, stable = 0;+ while (stable < 6) {+ await new Promise(resolve => requestAnimationFrame(resolve));+ stable = previous === el.scrollTop ? stable + 1 : 0;+ previous = el.scrollTop;+ }+ const viewport = el.getBoundingClientRect();+ const rows = [...el.querySelectorAll('.message-row')];+ const above = rows.find(row => row.getBoundingClientRect().bottom < viewport.top);+ const below = rows.at(-1);+ const point = [...el.querySelectorAll('.prose-chat p, .message-user-text')].find(node => {+ const rect = node.getBoundingClientRect();+ return rect.height > 0 && rect.top > viewport.top + 30 && rect.bottom < viewport.bottom - 30;+ });+ if (!above || !below || !point) throw new Error('Full Desktop reading probe needs above/visible/below content');+ const range = document.createRange(); range.selectNodeContents(point);+ const line = [...range.getClientRects()].find(rect => rect.width >= 200 && rect.height >= 12);+ if (!line) throw new Error('Full Desktop reading probe needs a rendered text line');+ const padding = parseFloat(getComputedStyle(above).paddingBottom);+ globalThis.fullDesktopReadingProbe = { el, above, point, padding, baseline: point.getBoundingClientRect().top - viewport.top };+ return { x: Math.ceil(line.left), y: Math.ceil(line.top), width: 200, height: 12, scale: 1 };+ })()`);+ const baseline = await send('Page.captureScreenshot', { format: 'png', clip: prepared });+ let maxDrift = 0;+ try {+ for (let amount = 20; amount <= 120; amount += 20) {+ await evaluate(`(() => { const p = globalThis.fullDesktopReadingProbe; p.above.style.paddingBottom = (p.padding + ${amount}) + 'px'; })()`);+ const frame = await send('Page.captureScreenshot', { format: 'png', clip: prepared });+ assert.equal(frame.data, baseline.data, 'full Desktop painted reading text moved during late layout');+ const drift = await evaluate(`(() => { const p = globalThis.fullDesktopReadingProbe;+ return Math.abs(p.point.getBoundingClientRect().top - p.el.getBoundingClientRect().top - p.baseline); })()`);+ maxDrift = Math.max(maxDrift, drift);+ }+ assert(maxDrift <= 1, 'full Desktop late layout changed the reading anchor');+ } finally { await evaluate('delete globalThis.fullDesktopReadingProbe'); }+ const result = { captures: 6, identical: true, maxDrift };+ console.log('FULL_DESKTOP_READING_ANCHOR ' + JSON.stringify(result));+ return result;+}diff --git a/scripts/e2e/transcript-history-loading.tsx b/scripts/e2e/transcript-history-loading.tsxindex 08d385976..e734b3e16 100644--- a/scripts/e2e/transcript-history-loading.tsx+++ b/scripts/e2e/transcript-history-loading.tsx@@ -199,10 +199,10 @@ async function jumpWhileLoading() {await until(() => Math.abs(el.scrollHeight - el.clientHeight - el.scrollTop) <= 2, "latest navigation did not arrive");return { ...inspect(), distanceFromBottom: el.scrollHeight - el.clientHeight - el.scrollTop };}-function track() {+function track(readingNode?: HTMLElement) {cancelAnimationFrame(sampling);const el = scroller();- anchor = [...el.querySelectorAll<HTMLElement>("[data-minimap-id]")].find(row => {+ anchor = readingNode ?? [...el.querySelectorAll<HTMLElement>("[data-minimap-id]")].find(row => {const r = row.getBoundingClientRect(); return r.bottom > el.getBoundingClientRect().top && r.height > 0;});if (!anchor) throw new Error("Missing visible reading anchor");@@ -245,15 +245,69 @@ async function growMountedWindow() {cancelAnimationFrame(sampling);return { before, after: inspect() };}+let mutateSettledLayout: (amount: number) => void = () => { throw new Error("No prepared layout case"); };+async function prepareSettledLayout(kind: "late" | "balanced" | "paragraph") {+ await reset(); await beginAhead(); await release();+ const el = scroller();+ if (kind === "paragraph") {+ const id = current.at(-3)!.id;+ current = current.map(message => message.id === id ? { ...message,+ content: Array.from({ length: 40 }, (_, n) => `Paragraph ${n}. ${"Stable long-answer reading content. ".repeat(12)}`).join("\n\n") } : message);+ render();+ el.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: 120 }));+ el.scrollTo({ top: el.scrollHeight, behavior: "instant" });+ el.dispatchEvent(new Event("scroll", { bubbles: true }));+ }+ const rows = [...el.querySelectorAll<HTMLElement>("[data-message-id], [data-minimap-id]")];+ for (const row of rows) row.style.contentVisibility = "visible";+ const below = rows.at(-1)!;+ below.style.paddingBottom = "120px";+ for (let n = 0; n < 8; n++) await frame();+ const paragraphs = [...el.querySelectorAll<HTMLElement>(`[data-message-id="${current.at(-3)!.id}"] .prose-chat p`)];+ const paragraph = kind === "paragraph" ? paragraphs[20] : undefined;+ if (kind === "paragraph" && !paragraph) throw new Error("Long-answer paragraph missing");+ el.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -120 }));+ el.scrollTo({ top: paragraph ? el.scrollTop + paragraph.getBoundingClientRect().top - el.getBoundingClientRect().top - 120 : el.scrollHeight / 2,+ behavior: "instant" });+ el.dispatchEvent(new Event("scroll", { bubbles: true }));+ for (let n = 0; n < 12; n++) await frame();+ const before = track(paragraph);+ const above = kind === "paragraph" ? paragraphs[0] : rows.find(row => row.getBoundingClientRect().bottom < el.getBoundingClientRect().top);+ if (!above || above === below) throw new Error("Need distinct content above/below the reading point");+ const padding = parseFloat(getComputedStyle(above).paddingBottom);+ const height = el.scrollHeight;+ mutateSettledLayout = amount => {+ above.style.paddingBottom = `${padding + amount}px`;+ if (kind === "balanced") below.style.paddingBottom = `${120 - amount}px`;+ };+ const viewport = el.getBoundingClientRect();+ let line: DOMRect | undefined;+ for (const node of el.querySelectorAll(".prose-chat p, .message-user-text")) {+ const range = document.createRange(); range.selectNodeContents(node);+ line = [...range.getClientRects()].find(rect => rect.width > 200 && rect.top > viewport.top + 20 && rect.bottom < viewport.bottom - 20);+ if (line) break;+ }+ if (!line) throw new Error("Need a visible text line for painted-pixel comparison");+ return { kind, before, height, crop: { x: Math.ceil(line.left), y: Math.ceil(line.top), width: 200, height: 12 } };+}+async function settledLayout(kind: "late" | "balanced" | "paragraph") {+ const prepared = await prepareSettledLayout(kind);+ mutateSettledLayout(120);+ for (let n = 0; n < 12; n++) await frame();+ cancelAnimationFrame(sampling);+ return { ...prepared, after: inspect(), totalDelta: scroller().scrollHeight - prepared.height };+}declare global { var historyLoadingFixture: { reset: typeof reset; begin: typeof begin; release: typeof release;inspect: typeof inspect; growTail: typeof growTail; hideAndReveal: typeof hideAndReveal;inputOwnership: typeof inputOwnership; jumpWhileLoading: typeof jumpWhileLoading; beginAhead: typeof beginAhead; track: typeof track;growMountedWindow: typeof growMountedWindow; crossAhead: typeof crossAhead; armNativeInput: typeof armNativeInput;+ settledLayout: typeof settledLayout; prepareSettledLayout: typeof prepareSettledLayout; mutateSettledLayout: (amount: number) => void;finishNativeInput: typeof finishNativeInput; frames: () => Promise<void> }; }await i18n.init({ lng: "en", resources: { en: { translation: en } } });useAppStore.setState({ activeSessionId: "history-fixture", messages: [], sessions: [], runningSessions: {},pendingPlans: {}, pendingAsks: {}, pendingPermissions: {}, planningStates: {}, latestTurnResults: {},settings: { ...useAppStore.getState().settings, smoothStreaming: false } });-globalThis.historyLoadingFixture = { reset, begin, beginAhead, track, release, inspect, growTail, hideAndReveal, inputOwnership, jumpWhileLoading, growMountedWindow, crossAhead, armNativeInput, finishNativeInput,+globalThis.historyLoadingFixture = { reset, begin, beginAhead, track, release, inspect, growTail, hideAndReveal, inputOwnership, jumpWhileLoading, growMountedWindow, crossAhead, armNativeInput, finishNativeInput, settledLayout,+ prepareSettledLayout, mutateSettledLayout: amount => mutateSettledLayout(amount),frames: async () => { for (let n = 0; n < 4; n++) await frame(); } };await reset();diff --git a/tests/history-loading-scroll-test-cases.md b/tests/history-loading-scroll-test-cases.mdindex d9c91a756..9397fefde 100644--- a/tests/history-loading-scroll-test-cases.md+++ b/tests/history-loading-scroll-test-cases.md@@ -55,6 +55,19 @@ button, and checks visible rows on every sampled navigation frame and at mostand exits normally. These checks complement, rather than replace, the held-IOcomponent fixture's prepend-anchor and request-concurrency measurements.+## Stable reading after page settlement++`node scripts/e2e-transcript-history-loading.mjs --anchor-only` runs the targeted+late-reading regressions. It first loads a page through production ChatTranscript,+then waits for settlement before changing the layout: content above grows 120px;+a balanced case also shrinks content below by 120px; a long-answer case grows+an earlier paragraph within the same message. Nonempty layout samples remain+within 1px, and six 20px steps require identical captured text pixels. There is+no loading veil, delayed reveal, input cancellation, or final-position-only check.+The full suite still exercises native wheel/smooth travel and navigation handoff.+The full application's `--interaction-smoke` also checks a painted reading crop+after real Host pagination. These checks do not change page-cache lifetime.+## Start the controlled manual fixture```bash