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 source-owned text across history layout repairs
new-Beginner7aa385a0e251
diff --git a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.tsindex 231b415ef..5b004a685 100644--- a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts+++ b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts@@ -5,10 +5,16 @@ import {restoreTranscriptReadingPosition,type TranscriptReadingPosition,} from "../../../../lib/transcript-reading-position";+import {+ captureTranscriptTextAnchor,+ resolveTranscriptTextAnchor,+ transcriptReaderMovement,+ type TranscriptTextAnchor,+} from "../../../../lib/transcript-reading-anchor";type Hold = {position: TranscriptReadingPosition;- point?: { element: HTMLElement; offset: number };+ point?: TranscriptTextAnchor;settled: boolean;stableFrames: number;page: boolean;@@ -32,14 +38,7 @@ function messageRow(content: HTMLElement, position: TranscriptReadingPosition) {}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 };- }- }+ return captureTranscriptTextAnchor(scroller, messageRow(content, position));}/** Single-flight page IO and pre-paint anchoring follow the reader's newest@@ -113,9 +112,8 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, souif (!held || !scroller || !content) return;// Retain the same readable message across a gesture. Switching immediately// 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;+ const movement = transcriptReaderMovement(held.top, scroller.scrollTop, scroller.scrollHeight, scroller.clientHeight);+ held.position = { ...held.position, offset: held.position.offset - movement, scrollTop: scroller.scrollTop };if (held.point) held.point.offset -= movement;if (!layoutChanged(held, sourceHeadRef.current) &&!isTranscriptReadingAnchorVisible(scroller, content, held.position)) {@@ -125,8 +123,9 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, souheld.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)) {+ const rect = held.point && resolveTranscriptTextAnchor(messageRow(content, held.position), held.point);+ if (!layoutChanged(held, sourceHeadRef.current) && (!held.point || (rect &&+ (held.point.offset >= scroller.clientHeight || held.point.offset + rect.height <= 0)))) {held.point = contentPoint(scroller, content, held.position);}held.top = scroller.scrollTop;@@ -139,12 +138,21 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, soutrack();const before = scroller.scrollTop;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);+ const row = messageRow(content, held.position);+ const rect = held.point && resolveTranscriptTextAnchor(row, held.point);+ if (held.point && rect) {+ const delta = rect.top - scroller.getBoundingClientRect().top - held.point.offset;+ const target = scroller.scrollTop + delta;+ if (Math.abs(delta) > 0.5) scroller.scrollTop = target;+ // A physically unreachable text offset must not cause repeated writes.+ if (target < 0 || target > scroller.scrollHeight - scroller.clientHeight) {+ held.point.offset += target - scroller.scrollTop;+ }+ } else {+ restoreTranscriptReadingPosition(scroller, content, held.position);+ held.point = contentPoint(scroller, content, held.position);+ }+ if (row) held.position = { ...held.position, offset: row.getBoundingClientRect().top - scroller.getBoundingClientRect().top };held.height = scroller.scrollHeight;held.viewport = scroller.clientHeight;held.alignedHead = sourceHeadRef.current;diff --git a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.tsindex 836c9842c..cee7af317 100644--- a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts+++ b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts@@ -239,6 +239,9 @@ export function useTranscriptScroll({if (latestNavigation.isActive()) {latestNavigation.cancel(); leaveFollow(); rememberReadingPosition();}+ // Settle pending geometry before the browser applies this input. A recent+ // wheel timestamp cannot distinguish its movement from a same-frame clamp.+ restoreHistoryAnchor();if (!(event instanceof WheelEvent) || (!event.ctrlKey && event.deltaY !== 0)) retryHistoryPaging();// Minimap / jump navigation runs in the browser, independently of our// follow rAF. Real input must retire that animation at its current offset@@ -249,7 +252,7 @@ export function useTranscriptScroll({// Real input takes the viewport back from a held disclosure position.releaseDisclosureAnchor();},- [cancelReadingPosition, latestNavigation, leaveFollow, releaseDisclosureAnchor, rememberReadingPosition, retryHistoryPaging],+ [cancelReadingPosition, latestNavigation, leaveFollow, releaseDisclosureAnchor, rememberReadingPosition, restoreHistoryAnchor, retryHistoryPaging],);useEffect(() => {diff --git a/apps/desktop/src/lib/transcript-reading-anchor.ts b/apps/desktop/src/lib/transcript-reading-anchor.tsnew file mode 100644index 000000000..4a6793527--- /dev/null+++ b/apps/desktop/src/lib/transcript-reading-anchor.ts@@ -0,0 +1,90 @@+const BLOCKS = ".prose-chat p, .prose-chat li, .prose-chat pre, .prose-chat h1, .prose-chat h2, .prose-chat h3, .message-user-text";++export type TranscriptTextAnchor = {+ element: HTMLElement;+ sourceStart?: string;+ sourceEnd?: string;+ text: string;+ textOffset?: number;+ offset: number;+};++/** Own repairs update previousTop synchronously. A shrinking legal range can+ * move that position without input; only movement beyond that clamp is reading. */+export function transcriptReaderMovement(previousTop: number, top: number, height: number, viewport: number) {+ const clampedPrevious = Math.min(Math.max(0, previousTop), Math.max(0, height - viewport));+ return top - clampedPrevious;+}++function characterRange(node: Text, offset: number) {+ const range = document.createRange();+ range.setStart(node, offset);+ range.setEnd(node, Math.min(node.length, offset + 1));+ return range;+}++function textRect(element: HTMLElement, offset: number): DOMRect | undefined {+ const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {+ const text = node as Text;+ if (offset < text.length) return characterRange(text, offset).getBoundingClientRect();+ offset -= text.length;+ }+}++/** Capture a visible character, not just the top of a potentially huge paragraph.+ * Tree walking is limited to the single visible block, never the whole history. */+function visibleCharacter(element: HTMLElement, viewport: DOMRect) {+ const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);+ let preceding = 0;+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {+ const text = node as Text;+ const range = document.createRange();+ range.selectNodeContents(text);+ const visible = [...range.getClientRects()].some(rect => rect.height > 0 && rect.bottom > viewport.top && rect.top < viewport.bottom);+ if (visible && text.length) {+ let low = 0;+ let high = text.length - 1;+ while (low < high) {+ const middle = Math.floor((low + high) / 2);+ if (characterRange(text, middle).getBoundingClientRect().bottom > viewport.top) high = middle;+ else low = middle + 1;+ }+ const rect = characterRange(text, low).getBoundingClientRect();+ if (rect.height > 0 && rect.bottom > viewport.top && rect.top < viewport.bottom) {+ return { textOffset: preceding + low, rect };+ }+ }+ preceding += text.length;+ }+}++export function captureTranscriptTextAnchor(scroller: HTMLElement, row: HTMLElement | null): TranscriptTextAnchor | undefined {+ const viewport = scroller.getBoundingClientRect();+ for (const element of row?.querySelectorAll<HTMLElement>(BLOCKS) ?? []) {+ const block = element.getBoundingClientRect();+ if (block.height <= 0 || block.bottom <= viewport.top || block.top >= viewport.bottom) continue;+ const character = visibleCharacter(element, viewport);+ return { element, sourceStart: element.dataset.sourceStart, sourceEnd: element.dataset.sourceEnd,+ text: element.textContent ?? "", textOffset: character?.textOffset,+ offset: (character?.rect ?? block).top - viewport.top };+ }+}++/** Parser range + exact rendered text guards against reusing offsets after an+ * edit. The element is only a cache: unchanged Markdown can be reconstructed. */+export function resolveTranscriptTextAnchor(row: HTMLElement | null, point: TranscriptTextAnchor): DOMRect | undefined {+ if (!row) return;+ let element = point.element;+ if (!row.contains(element)) {+ if (point.sourceStart === undefined || point.sourceEnd === undefined) return;+ const selector = `${element.tagName.toLowerCase()}[data-source-start="${CSS.escape(point.sourceStart)}"][data-source-end="${CSS.escape(point.sourceEnd)}"]`;+ const replacement = [...row.querySelectorAll<HTMLElement>(selector)].find(candidate => candidate.textContent === point.text);+ if (!replacement) return;+ element = replacement;+ }+ if (element.dataset.sourceStart !== point.sourceStart || element.dataset.sourceEnd !== point.sourceEnd || element.textContent !== point.text) return;+ point.element = element;+ const rect = point.textOffset === undefined ? element.getBoundingClientRect() : textRect(element, point.textOffset);+ return rect && rect.height > 0 ? rect : undefined;+}diff --git a/apps/desktop/test/transcript-reading-anchor.test.mjs b/apps/desktop/test/transcript-reading-anchor.test.mjsnew file mode 100644index 000000000..403d2cb92--- /dev/null+++ b/apps/desktop/test/transcript-reading-anchor.test.mjs@@ -0,0 +1,21 @@+import assert from "node:assert/strict";+import test from "node:test";+import { transcriptReaderMovement } from "../src/lib/transcript-reading-anchor.ts";++test("a mandatory shrink clamp is not reader displacement", () => {+ assert.equal(transcriptReaderMovement(800, 500, 1000, 500), 0);+ assert.equal(transcriptReaderMovement(800, 800, 1400, 500), 0);+});+test("reader movement in the clamped layout is still applied", () => {+ assert.equal(transcriptReaderMovement(800, 450, 1000, 500), -50);+ assert.equal(transcriptReaderMovement(500, 540, 1500, 500), 40);+});+test("viewport growth, underfill and fractional offsets retain legal geometry", () => {+ assert.equal(transcriptReaderMovement(800, 500, 1500, 1000), 0);+ assert.equal(transcriptReaderMovement(200, 0, 400, 500), 0);+ assert.equal(transcriptReaderMovement(800.25, 450.125, 1000, 500), -49.875);+});+test("own compensation is rebased before its queued scroll event", () => {+ assert.equal(transcriptReaderMovement(300, 300, 1000, 500), 0);+ assert.equal(transcriptReaderMovement(300, 260, 1000, 500), -40);+});diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.mdindex 02e09f7ee..c6eb146d3 100644--- a/docs/spec/04-ux/09-interaction-patterns.md+++ b/docs/spec/04-ux/09-interaction-patterns.md@@ -1672,9 +1672,11 @@ Project drag/drop follows these patterns:a second time. Native input in the same layout delivery still advances thereading target. An unreachable target degrades to the legal scroll boundary.Where parser-owned source positions exist, the anchor identifies the message,- source block, and text position rather than treating a DOM node as identity.- Reconstructed unchanged content is re-resolved; changed/missing content falls- back to the message anchor without inventing an equivalent sentence.+ source block, exact rendered text version, and visible character rather than+ treating a DOM node as identity. Reconstructed unchanged content is re-resolved,+ including line wrapping within a long paragraph. Changed/missing content falls+ back to the message anchor without inventing an equivalent sentence. Boundary+ fallback rebases the held target so repeated restores do not repeat writes.- 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 9a51ded0f..18f64d6d7 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -13989,10 +13989,18 @@ This test plan spec is accepted when:`node scripts/e2e-transcript-anchor-repair.mjs` additionally mounts the realpaging hook and Markdown in Chromium. It verifies actual native boundaryclamping, reconstructed paragraph nodes with unchanged parser source ranges,- ordinary non-clamping shrinkage, and reader movement. The same readable- content must remain within <2 CSS px when reachable. Extend this regression- with simultaneous input/layout, legal-boundary fallback, frame/paint samples,- and the production transcript journey before declaring the repair complete.+ ordinary non-clamping shrinkage, balanced internal reflow, reader movement,+ and unreachable-target legal-boundary fallback without repeated scroll writes.+ A known-character oracle covers long-paragraph width reflow and rejects+ edited/missing text. Identical native wheel input is compared with and without+ same-delivery layout/clamping at equivalent geometry. Reachable readable content+ must stay within <2 CSS px in eight post-layout samples; stable-content painted+ crops must be nonempty and byte-identical. `--inject-drift` adds a real 20px+ displacement after sampling and must fail the final geometry/paint checks.+ This focused fixture uses inline layout, so production CSS/recycling, native+ navigation, disclosure and long-history journeys remain separate required+ checks. Painted crops are not a claim of every-frame or human visual approval.+ The regression runs from the existing `e2e-transcript-render.mjs` CI entry.- **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/README.md b/scripts/README.mdindex 17155fbdb..e75326ee0 100644--- a/scripts/README.md+++ b/scripts/README.md@@ -64,7 +64,7 @@ The scenarios are specified in| `e2e-settings-scroll.mjs` | `pnpm test:e2e:settings-scroll` | Production Settings component navigation, search anchoring, focus-on-mount, and scroll behavior || `e2e-transcript-render.mjs` | `pnpm test:e2e:transcript` | Production transcript render boundaries, runtime status geometry, and deterministic smooth-text cadence || `e2e-transcript-history-loading.mjs` | `node scripts/e2e-transcript-history-loading.mjs [--manual]` | Production transcript and `SessionPane`/store probe for unlocked ahead-loading prefetch (`100px` mid-IO scroll + `<= 2px` prepend anchor), adaptive speed/latency lead and unlocked hard-edge fallback, paired idle/running × tail/paginated smooth return-to-latest (`>= 3` intermediate frames, `<= 2px` reversal, no blank frame), native wheel input, and error/empty/hide recovery; included by `e2e-transcript-render.mjs`. `--manual` opens a disposable 1,000-message synthetic conversation (40 initially loaded, 100 per page) with page-complete/fail controls and request status; `--manual-smoke` verifies toolbar paging/reset and bidirectional native-wheel frame gaps; see [manual cases](../tests/history-loading-scroll-test-cases.md) |-| `e2e-transcript-anchor-repair.mjs` | `node scripts/e2e-transcript-anchor-repair.mjs` | Real React/Markdown/Chromium regressions for browser boundary clamps and reconstructed reading text; synthetic state with an isolated profile, no Host or providers |+| `e2e-transcript-anchor-repair.mjs` | `node scripts/e2e-transcript-anchor-repair.mjs` | Real React/Markdown/Chromium clamp, source/text/character reconstruction, native input/layout and boundary regressions; nonempty painted crops, `<2px` samples, `--inject-drift` negative control; isolated profile, no Host/providers; included in transcript-render CI || `manual-transcript-desktop.mjs` | `node scripts/manual-transcript-desktop.mjs [--smoke\|--interaction-smoke]` | Complete PI-Desktop sidebar/chat/Composer with scratch-isolated Host data and 1,000-message plus long-answer sessions. `--smoke` checks readiness; `--interaction-smoke` crosses a real Host page with native wheel input and checks the actual latest button, nonblank navigation and <=2px arrival drift. Automated modes confirm normal application quit; no provider is configured || `e2e-gen-ui.mjs` | `pnpm test:e2e:gen-ui` | Offline production GenUI card/protocol journey: slider, theme, expand/Escape, viewport cleanup, global frame quota, and response-level cross-session sandbox || `e2e-renderer-responsiveness.mjs` | `pnpm test:e2e:renderer-responsiveness` | Native Electron click, typing, session switching, disclosure, and scroll while an isolated child process streams large transcript deltas |diff --git a/scripts/e2e-transcript-anchor-repair.mjs b/scripts/e2e-transcript-anchor-repair.mjsindex 9b1535abd..cd8c64a4d 100644--- a/scripts/e2e-transcript-anchor-repair.mjs+++ b/scripts/e2e-transcript-anchor-repair.mjs@@ -10,6 +10,7 @@ import { resolveElectronBinary } from "./e2e/boot.mjs";const root = fileURLToPath(new URL("..", import.meta.url));const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");const { electronBinary } = resolveElectronBinary(root);+const injectDrift = process.argv.includes("--inject-drift");const temp = await mkdtemp(join(process.env.PI_SCRATCH_DIR ?? root, "transcript-anchor-"));try {await build({ entryPoints: [join(root, "scripts/e2e/transcript-anchor-repair.tsx")],@@ -27,6 +28,7 @@ try {await writeFile(join(temp, "index.html"), '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; style-src \'self\' \'unsafe-inline\'; img-src \'self\' data:"><title>Transcript anchor repair</title><script type="module" src="renderer.js"></script>');await writeFile(join(temp, "main.cjs"), `const {app,BrowserWindow}=require('electron');+const assert=require('node:assert/strict');app.setPath('userData',require('node:path').join(__dirname,'profile'));app.disableHardwareAcceleration();app.whenReady().then(async()=>{@@ -34,7 +36,37 @@ app.whenReady().then(async()=>{win.webContents.on('console-message',e=>console.error(e.message));try{await win.loadFile(require('node:path').join(__dirname,'index.html'));- const results=await win.webContents.executeJavaScript('globalThis.transcriptAnchorRepairProbe()');+ const js=expression=>win.webContents.executeJavaScript(expression);+ const call=expression=>js('globalThis.transcriptAnchorRepairFixture.'+expression);+ const results=[];+ for(const kind of ['ordinary-shrink','browser-clamp','paragraph-remount','balanced-remount','reader-scroll','unreachable']) {+ const prepared=await call('prepareCase('+JSON.stringify(kind)+')');+ const before=(await win.webContents.capturePage(prepared.crop)).toBitmap();+ assert(new Set(before).size>8,'Empty/uniform painted text');+ const result=await call('mutateCase(${injectDrift})');+ const painted=(await win.webContents.capturePage(prepared.crop)).toBitmap();+ if(!['reader-scroll','unreachable'].includes(kind)) result.identicalPaint=before.equals(painted);+ results.push(result);+ }+ const text=await call('textContracts()');+ console.log('TRANSCRIPT_TEXT_ANCHOR '+JSON.stringify(text));+ assert(text.character>0&&text.reconstructed&&text.resolved&&text.rejectedEdit&&text.rejectedMissing&&text.fallbackLegal&&text.fallbackStable,'Text identity/fallback contract failed');+ assert(text.drift<2&&text.maxFrameDrift<2,'Intra-paragraph character moved');+ const nativeResults=[];+ for(const withLayout of [false,true]) {+ const input=await call('prepareNative('+withLayout+')');+ win.focus();+ win.webContents.sendInputEvent({type:'mouseMove',x:input.x,y:input.y});+ win.webContents.sendInputEvent({type:'mouseWheel',x:input.x,y:input.y,deltaY:60,deltaX:0,canScroll:true});+ const native=await call('nativeResult()');+ nativeResults.push({input,native});+ assert(!native.nativeLayout&&native.top>2&&native.top<280,'Native input did not move the reader without hitting a boundary');+ assert.equal(native.observerWarnings.length,0,'Unexpected ResizeObserver notification loop');+ assert(Math.abs(native.actual-input.baseline-(300-native.top))<2,'Native input was confused with layout movement');+ if(withLayout) assert(native.clamped<800,'Same-delivery layout did not clamp');+ }+ console.log('TRANSCRIPT_NATIVE_CLAMP '+JSON.stringify(nativeResults));+ assert(Math.abs(nativeResults[0].native.top-nativeResults[1].native.top)<2,'Layout swallowed part of native input');console.log('TRANSCRIPT_ANCHOR_REPAIR '+JSON.stringify(results));app.exit(0);}catch(e){console.error(e.stack||String(e));app.exit(1);}@@ -54,5 +86,13 @@ app.whenReady().then(async()=>{const clamp = results.find(result => result.kind === "browser-clamp");assert(clamp.clamped < clamp.oldTop, "Fixture did not trigger native boundary clamping");assert.equal(results.find(result => result.kind === "paragraph-remount").replaced, true);+ for (const result of results) {+ assert(result.samples >= 8 && result.maxFrameDrift < 2, "A sampled frame drifted: " + JSON.stringify(result));+ assert.equal(result.repeatedWrites, 0, "Stable/boundary restore repeated a scroll write");+ if (result.identicalPaint !== undefined) assert.equal(result.identicalPaint, true, "Painted text changed: " + result.kind);+ if (result.kind.includes("remount")) assert.equal(result.replaced && !result.connected, true);+ if (result.kind === "balanced-remount") assert.equal(result.oldHeight, result.height);+ if (result.kind === "unreachable") assert.equal(result.top, 0);+ }assert(results.every(result => result.drift < 2), "Same readable paragraph moved: " + JSON.stringify(results));} finally { await rm(temp, { recursive: true, force: true }); }diff --git a/scripts/e2e-transcript-render.mjs b/scripts/e2e-transcript-render.mjsindex 40c1de575..74d50b2cb 100644--- a/scripts/e2e-transcript-render.mjs+++ b/scripts/e2e-transcript-render.mjs@@ -296,3 +296,4 @@ app.whenReady().then(async () => {// Keep history paging's real native-input regression in the existing CI suite.await import("./e2e-transcript-history-loading.mjs");+await import("./e2e-transcript-anchor-repair.mjs");diff --git a/scripts/e2e/transcript-anchor-repair.tsx b/scripts/e2e/transcript-anchor-repair.tsxindex e1da8ad00..859a78e0f 100644--- a/scripts/e2e/transcript-anchor-repair.tsx+++ b/scripts/e2e/transcript-anchor-repair.tsx@@ -1,79 +1,198 @@-import { useLayoutEffect, useRef } from "react";+import { useLayoutEffect, useRef, type CSSProperties } from "react";import { createRoot } from "react-dom/client";import { flushSync } from "react-dom";import i18n from "i18next";import { initReactI18next } from "react-i18next";import { Markdown } from "../../apps/desktop/src/components/Markdown";import { useTranscriptHistoryPaging } from "../../apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging";+import { captureTranscriptTextAnchor, resolveTranscriptTextAnchor } from "../../apps/desktop/src/lib/transcript-reading-anchor";const host = document.createElement("div");document.body.append(host);const style = document.createElement("style");-style.textContent = "body{margin:0} .prose-chat p{margin:0;height:100px;line-height:20px} .prose-chat p:first-child{padding-bottom:var(--growth,0px)}";+style.textContent = "body{margin:0} .prose-chat p{margin:0;height:100px;line-height:20px} .prose-chat.long p{height:auto} .prose-chat p:first-child{padding-bottom:var(--growth,0px)}";document.head.append(style);const root = createRoot(host);const frame = () => new Promise<void>(resolve => requestAnimationFrame(() => resolve()));async function frames() { for (let n = 0; n < 8; n++) await frame(); }let serial = 0;let beforeHeight = 900;+let tailHeight = 300;+let width = 600;let growth = 0;let revision = 0;+let long = false;let clampWitness = 0;+let scrollWrites = 0;+let nativeLayout = false;+let nativeEnded = false;+const observerWarnings: string[] = [];+let stage = "initial";+window.addEventListener("error", event => {+ if (event.message.includes("ResizeObserver loop")) observerWarnings.push(stage);+});let api: ReturnType<typeof useTranscriptHistoryPaging>;const source = "Earlier paragraph with unchanged source.\n\nReading paragraph with **stable inline text**.\n\nLast paragraph.";+const longSource = "Long paragraph with **inline emphasis** and stable characters. ".repeat(140);function Fixture() {const scrollRef = useRef<HTMLDivElement>(null);const contentRef = useRef<HTMLDivElement>(null);- // Observe actual browser clamping before the production layout effect repairs it.- useLayoutEffect(() => { clampWitness = scrollRef.current!.scrollTop; });+ useLayoutEffect(() => {+ const element = scrollRef.current!;+ // Pass-through write spy: every value and geometry still comes from Chromium.+ if (!Object.hasOwn(element, "scrollTop")) {+ const descriptor = Object.getOwnPropertyDescriptor(Element.prototype, "scrollTop")!;+ Object.defineProperty(element, "scrollTop", { configurable: true,+ get: () => descriptor.get!.call(element),+ set: (value: number) => { scrollWrites++; descriptor.set!.call(element, value); } });+ }+ clampWitness = element.scrollTop;+ });api = useTranscriptHistoryPaging({ scrollRef, contentRef, visible: true, sourceHead: "before",canRetain: () => true, onStart: () => {}, onPosition: () => {}, onSettled: () => {} });- return <div ref={scrollRef} onScroll={() => api.track()} data-scroller="" style={{ height: 500, width: 600, overflow: "auto", overflowAnchor: "none" }}>+ return <div ref={scrollRef} onScroll={() => { nativeEnded = false; api.track(); }} onWheel={() => {+ if (nativeLayout) {+ nativeLayout = false;+ beforeHeight = 400;+ contentRef.current!.firstElementChild!.setAttribute("style", "height:400px");+ clampWitness = scrollRef.current!.scrollTop;+ }+ api.restore();+ }} data-scroller="" style={{ height: 500, width, overflow: "auto", overflowAnchor: "none" }}><div ref={contentRef}><div style={{ height: beforeHeight }} />- <div data-message-id="reading" className="prose-chat" style={{ "--growth": `${growth}px` } as React.CSSProperties}>- <Markdown key={revision} source={source} />+ <div data-message-id="reading" className={`prose-chat${long ? " long" : ""}`} style={{ "--growth": `${growth}px` } as CSSProperties}>+ <Markdown key={revision} source={long ? longSource : source} /></div>- <div style={{ height: beforeHeight === 200 ? 600 : 300 }} />+ <div style={{ height: tailHeight }} /></div></div>;}function render() { flushSync(() => root.render(<Fixture key={serial} />)); }const scroller = () => host.querySelector<HTMLDivElement>("[data-scroller]")!;+const row = () => host.querySelector<HTMLElement>('[data-message-id="reading"]')!;const paragraph = (n: number) => host.querySelectorAll<HTMLElement>(".prose-chat p")[n];const offset = (n: number) => paragraph(n).getBoundingClientRect().top - scroller().getBoundingClientRect().top;-async function prepare(pre: number, top: number) {- console.log("ANCHOR_PREPARE", pre, top);- serial++; beforeHeight = pre; growth = 0; revision = 0; render(); await frames();+async function prepare(pre: number, top: number, longText = false) {+ serial++; beforeHeight = pre; tailHeight = pre === 200 ? 600 : 300;+ width = 600; growth = 0; revision = 0; long = longText; nativeLayout = false;+ render(); await frames();scroller().scrollTop = top;scroller().dispatchEvent(new Event("scroll", { bubbles: true }));api.run(() => Promise.resolve(), 60, true);await frames();}-async function probe() {- const results = [];- for (const kind of ["ordinary-shrink", "browser-clamp", "paragraph-remount", "reader-scroll"] as const) {- console.log("ANCHOR_CASE", kind);- const remount = kind === "paragraph-remount";- await prepare(remount ? 200 : 900, remount ? 320 : 800);- const index = remount ? 1 : 0;- const baseline = offset(index);- const oldNode = paragraph(index);- const oldTop = scroller().scrollTop;- const oldHeight = scroller().scrollHeight;- if (remount) { growth = 80; revision++; }- else if (kind === "reader-scroll") scroller().scrollTop += 40;- else beforeHeight -= kind === "browser-clamp" ? 500 : 100;- render();- const clamped = clampWitness;- await frames();- const expected = baseline - (kind === "reader-scroll" ? 40 : 0);- results.push({ kind, baseline, expected, actual: offset(index), drift: Math.abs(offset(index) - expected),- oldTop, clamped, top: scroller().scrollTop, oldHeight, height: scroller().scrollHeight,- replaced: oldNode !== paragraph(index), connected: oldNode.isConnected });+function crop() {+ const viewport = scroller().getBoundingClientRect();+ for (const p of row().querySelectorAll("p")) {+ const range = document.createRange(); range.selectNodeContents(p);+ const rect = [...range.getClientRects()].find(rect => rect.width > 90 && rect.top > viewport.top + 20 && rect.bottom < viewport.bottom - 20);+ if (rect) return { x: Math.ceil(rect.left + 2), y: Math.ceil(rect.top), width: 80, height: 12 };+ }+ throw new Error("No actual text crop");+}+async function afterLayout() {+ await new Promise<void>(resolve => {+ const observer = new ResizeObserver(() => { observer.disconnect(); resolve(); });+ observer.observe(scroller().firstElementChild!);+ });+}+async function samples(read: () => number, expected: number) {+ const offsets = [];+ for (let n = 0; n < 8; n++) { await frame(); await afterLayout(); offsets.push(read()); }+ return { samples: offsets.length, maxFrameDrift: Math.max(...offsets.map(value => Math.abs(value - expected))) };+}+type Kind = "ordinary-shrink" | "browser-clamp" | "paragraph-remount" | "balanced-remount" | "reader-scroll" | "unreachable";+let prepared: { kind: Kind; baseline: number; index: number; oldNode: HTMLElement; oldTop: number; oldHeight: number };+async function prepareCase(kind: Kind) {+ const remount = kind.includes("remount");+ stage = kind;+ await prepare(remount ? 200 : 900, remount ? 320 : 800);+ const index = remount ? 1 : 0;+ prepared = { kind, baseline: offset(index), index, oldNode: paragraph(index), oldTop: scroller().scrollTop, oldHeight: scroller().scrollHeight };+ return { crop: crop() };+}+async function mutateCase(injectDrift = false) {+ const { kind, baseline, index, oldNode, oldTop, oldHeight } = prepared;+ if (kind.includes("remount")) { growth = 80; revision++; if (kind === "balanced-remount") tailHeight -= 80; }+ else if (kind === "reader-scroll") scroller().scrollTop += 40;+ else beforeHeight -= kind === "browser-clamp" ? 500 : kind === "unreachable" ? 900 : 100;+ render();+ const clamped = clampWitness;+ const expected = baseline - (kind === "reader-scroll" ? 40 : kind === "unreachable" ? 100 : 0);+ const sampling = await samples(() => offset(index), expected);+ const writesBefore = scrollWrites;+ for (let n = 0; n < 4; n++) api.restore();+ if (injectDrift) { paragraph(index).style.transform = "translateY(20px)"; await frames(); }+ return { kind, baseline, expected, actual: offset(index), drift: Math.abs(offset(index) - expected), ...sampling,+ oldTop, clamped, top: scroller().scrollTop, oldHeight, height: scroller().scrollHeight,+ repeatedWrites: scrollWrites - writesBefore, replaced: oldNode !== paragraph(index), connected: oldNode.isConnected };+}+// Independent oracle walks the known character offset without re-resolving the+// production descriptor. This catches block-only anchoring during line reflow.+function characterOffset(character: number) {+ const walker = document.createTreeWalker(paragraph(0), NodeFilter.SHOW_TEXT);+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {+ const length = node.textContent!.length;+ if (character < length) {+ const range = document.createRange(); range.setStart(node, character); range.setEnd(node, character + 1);+ return range.getBoundingClientRect().top - scroller().getBoundingClientRect().top;+ }+ character -= length;}- return results;+ throw new Error("Oracle character missing");+}+async function textContracts() {+ stage = "text-contracts";+ await prepare(200, 700, true);+ const point = captureTranscriptTextAnchor(scroller(), row())!;+ if (!point.textOffset || point.sourceStart === undefined) throw new Error("Need a source-owned intra-paragraph character");+ const baseline = characterOffset(point.textOffset);+ const oldNode = point.element;+ width = 510; revision++; render();+ const sampling = await samples(() => characterOffset(point.textOffset!), baseline);+ const actual = characterOffset(point.textOffset);+ const resolved = resolveTranscriptTextAnchor(row(), point);+ // Same length and parser range, different text: a source range alone is unsafe.+ stage = "edited-content";+ paragraph(0).firstChild!.textContent = paragraph(0).firstChild!.textContent!.replace("Long", "Edit");+ const rejectedEdit = resolveTranscriptTextAnchor(row(), point) === undefined;+ api.restore();+ await frames();+ const editedTop = scroller().scrollTop;+ stage = "missing-content";+ row().replaceChildren();+ const rejectedMissing = resolveTranscriptTextAnchor(row(), point) === undefined;+ api.restore();+ await frames();+ const warningsBefore = observerWarnings.length;+ const writesBefore = scrollWrites;+ for (let n = 0; n < 4; n++) api.restore();+ await frames();+ const fallbackStable = observerWarnings.length === warningsBefore && scrollWrites === writesBefore;+ return { character: point.textOffset, baseline, actual, drift: Math.abs(actual - baseline), ...sampling,+ reconstructed: !oldNode.isConnected, resolved: Boolean(resolved), rejectedEdit, rejectedMissing,+ fallbackLegal: editedTop >= 0 && scroller().scrollTop >= 0, fallbackStable };+}+async function prepareNative(withLayout = true) {+ stage = withLayout ? "native-clamp" : "native-control";+ await prepare(withLayout ? 900 : 400, withLayout ? 800 : 300);+ nativeLayout = withLayout; nativeEnded = false;+ scroller().addEventListener("scrollend", () => { nativeEnded = true; });+ const rect = scroller().getBoundingClientRect();+ return { baseline: offset(0), x: Math.round(rect.left + 200), y: Math.round(rect.top + 200) };+}+async function nativeResult() {+ // An instant repair may emit an earlier scrollend; a later scroll invalidates+ // it. Wait for the final native end, not a fixed animation duration.+ const end = performance.now() + 6000;+ do {+ if (performance.now() > end) throw new Error("Native input did not settle");+ await frames();+ } while (!nativeEnded);+ return { actual: offset(0), top: scroller().scrollTop, clamped: clampWitness, nativeLayout, observerWarnings: [...observerWarnings] };}-declare global { var transcriptAnchorRepairProbe: typeof probe; }-globalThis.transcriptAnchorRepairProbe = probe;+const fixture = { prepareCase, mutateCase, textContracts, prepareNative, nativeResult, frames };+declare global { var transcriptAnchorRepairFixture: typeof fixture; }await i18n.use(initReactI18next).init({ lng: "en", resources: { en: { translation: {} } } });+globalThis.transcriptAnchorRepairFixture = fixture;diff --git a/tests/history-loading-scroll-test-cases.md b/tests/history-loading-scroll-test-cases.mdindex 722f0d9c1..b5b7ff5fd 100644--- a/tests/history-loading-scroll-test-cases.md+++ b/tests/history-loading-scroll-test-cases.md@@ -68,6 +68,37 @@ The full suite still exercises native wheel/smooth travel and navigation handoffThe full application's `--interaction-smoke` also checks a painted reading cropafter real Host pagination. These checks do not change page-cache lifetime.+## Boundary clamp and reconstructed text++```bash+node scripts/e2e-transcript-anchor-repair.mjs+```++The focused React/Markdown fixture uses actual Chromium layout, not mocked+geometry. It covers shrinkage with and without a mandatory boundary clamp,+unchanged paragraph reconstruction, balanced internal reflow, genuine reading+movement, and an unreachable old offset. Reachable text must remain within+`<2 CSS px` in eight post-layout samples. Nonempty painted text crops must be+identical for the stable-content cases; repeated stable/boundary restores must+perform zero additional scroll writes.++A long-paragraph known-character oracle covers width reflow, source/text version+invalidation and missing-content fallback. Identical native wheel input is tested+with and without same-delivery shrinkage at equivalent final geometry; the+resulting reading movement must agree within `<2 CSS px`.++Negative control (expected nonzero exit):++```bash+node scripts/e2e-transcript-anchor-repair.mjs --inject-drift+```++It applies a real `translateY(20px)` after the frame samples. The final reading+and paint assertions must reject it; it does not test transient-frame injection.+The isolated inline-layout fixture complements, not replaces, production+stylesheet/recycling and full-Desktop journeys. These measurements do not claim+every painted frame, all hardware, or human visual acceptance.+## Start the controlled manual fixture```bash@@ -202,6 +233,7 @@ are used. It is not a mock implementation of scrolling.```bashnode --test apps/desktop/test/transcript-latest-navigation.test.mjs apps/desktop/test/transcript-reading.test.mjs apps/desktop/test/transcript-scroll.test.mjsnode scripts/e2e-transcript-history-loading.mjs+node scripts/e2e-transcript-anchor-repair.mjsnode scripts/e2e-transcript-reading-position.mjsnode scripts/e2e-transcript-minimap-jump.mjsnode scripts/e2e-transcript-disclosure-anchor.mjs