Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

test(chat): reproduce clamped and reconstructed reading anchors

new-Beginnerd0e18ba45225
diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.md
index 96b421e5b..02e09f7ee 100644
--- a/docs/spec/04-ux/09-interaction-patterns.md
+++ b/docs/spec/04-ux/09-interaction-patterns.md
@@ -1667,6 +1667,14 @@ Project drag/drop follows these patterns:
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.
+- Reading displacement excludes the browser's mandatory boundary clamp after
+ content/viewport shrinkage; that clamp must not shift the intended text offset
+ a second time. Native input in the same layout delivery still advances the
+ reading 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.
- All paging paths leave `overflow-y` and input untouched, including the
`<= 120px` hard edge, explicit earlier-history actions, and the underfilled
top-boundary observer. Wheel/trackpad, touch and keyboard input continue
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 874869cd9..9a51ded0f 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -13986,6 +13986,13 @@ This test plan spec is accepted when:
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.
+ `node scripts/e2e-transcript-anchor-repair.mjs` additionally mounts the real
+ paging hook and Markdown in Chromium. It verifies actual native boundary
+ clamping, 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.
- **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; run
diff --git a/scripts/README.md b/scripts/README.md
index b0af877d0..17155fbdb 100644
--- a/scripts/README.md
+++ b/scripts/README.md
@@ -64,6 +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 |
| `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.mjs
new file mode 100644
index 000000000..9b1535abd
--- /dev/null
+++ b/scripts/e2e-transcript-anchor-repair.mjs
@@ -0,0 +1,58 @@
+#!/usr/bin/env node
+/** Real React/Markdown/Chromium geometry; synthetic state, no Host or providers. */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+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 temp = await mkdtemp(join(process.env.PI_SCRATCH_DIR ?? root, "transcript-anchor-"));
+try {
+ await build({ entryPoints: [join(root, "scripts/e2e/transcript-anchor-repair.tsx")],
+ outfile: join(temp, "renderer.js"), bundle: true, platform: "browser", format: "esm", jsx: "automatic",
+ define: { "process.env.NODE_ENV": '"production"', "import.meta.env": '{"DEV":false,"MODE":"production"}' },
+ loader: { ".css": "empty" }, alias: {
+ "@pi-desktop/shared": join(root, "packages/shared/src/index.ts"),
+ "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),
+ react: join(root, "apps/desktop/node_modules/react"), "react-dom": join(root, "apps/desktop/node_modules/react-dom") },
+ nodePaths: [join(root, "apps/desktop/node_modules")], plugins: [{ name: "assets", setup(b) {
+ b.onResolve({ filter: /\?url$/ }, ({ path, resolveDir }) => ({ path: join(resolveDir, path.slice(0, -4)), namespace: "asset" }));
+ b.onLoad({ filter: /.*/, namespace: "asset" }, async ({ path }) => ({ contents: await readFile(path), loader: "file" }));
+ } }],
+ });
+ 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');
+app.setPath('userData',require('node:path').join(__dirname,'profile'));
+app.disableHardwareAcceleration();
+app.whenReady().then(async()=>{
+ const win=new BrowserWindow({show:true,width:900,height:720,webPreferences:{sandbox:true,contextIsolation:true,nodeIntegration:false,backgroundThrottling:false}});
+ 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()');
+ console.log('TRANSCRIPT_ANCHOR_REPAIR '+JSON.stringify(results));
+ app.exit(0);
+ }catch(e){console.error(e.stack||String(e));app.exit(1);}
+});`);
+ const env = { ...process.env }; delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(electronBinary, [join(temp, "main.cjs")], { env, stdio: ["ignore", "pipe", "pipe"] });
+ let output = "";
+ for (const stream of [child.stdout, child.stderr]) stream.on("data", data => { output += data; process.stdout.write(data); });
+ const timer = setTimeout(() => child.kill("SIGKILL"), 60_000);
+ let code;
+ try { code = await new Promise((resolve, reject) => { child.once("error", reject); child.once("close", resolve); }); }
+ finally { clearTimeout(timer); }
+ assert.equal(code, 0, output.slice(-4000));
+ const line = output.split(/\r?\n/).find(line => line.startsWith("TRANSCRIPT_ANCHOR_REPAIR "));
+ assert(line, "Missing actual Chromium results");
+ const results = JSON.parse(line.slice("TRANSCRIPT_ANCHOR_REPAIR ".length));
+ 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);
+ 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-anchor-repair.tsx b/scripts/e2e/transcript-anchor-repair.tsx
new file mode 100644
index 000000000..e1da8ad00
--- /dev/null
+++ b/scripts/e2e/transcript-anchor-repair.tsx
@@ -0,0 +1,79 @@
+import { useLayoutEffect, useRef } 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";
+
+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)}";
+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 growth = 0;
+let revision = 0;
+let clampWitness = 0;
+let api: ReturnType<typeof useTranscriptHistoryPaging>;
+const source = "Earlier paragraph with unchanged source.\n\nReading paragraph with **stable inline text**.\n\nLast paragraph.";
+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; });
+ 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" }}>
+ <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>
+ <div style={{ height: beforeHeight === 200 ? 600 : 300 }} />
+ </div>
+ </div>;
+}
+function render() { flushSync(() => root.render(<Fixture key={serial} />)); }
+const scroller = () => host.querySelector<HTMLDivElement>("[data-scroller]")!;
+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();
+ 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 });
+ }
+ return results;
+}
+declare global { var transcriptAnchorRepairProbe: typeof probe; }
+globalThis.transcriptAnchorRepairProbe = probe;
+await i18n.use(initReactI18next).init({ lng: "en", resources: { en: { translation: {} } } });