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): retain readable anchors through lazy history layout
new-Beginnerbb25eb01347b
diff --git a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.tsindex a1b8ff62c..81137a769 100644--- a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts+++ b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts@@ -1,6 +1,7 @@import { useCallback, useLayoutEffect, useRef, useState, type RefObject } from "react";import {captureTranscriptReadingPosition,+ isTranscriptReadingAnchorVisible,restoreTranscriptReadingPosition,type TranscriptReadingPosition,} from "../../../../lib/transcript-reading-position";@@ -70,11 +71,12 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, souconst scroller = scrollRef.current;const content = contentRef.current;if (!held?.background || !scroller || !content) return;- if (layoutChanged(held, sourceHeadRef.current)) {- // Keep intentional scrolling, but not the displacement caused by layout.- held.position = { ...held.position, offset: held.position.offset - (scroller.scrollTop - held.top),- scrollTop: scroller.scrollTop };- } else {+ // 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 };+ if (!layoutChanged(held, sourceHeadRef.current) &&+ !isTranscriptReadingAnchorVisible(scroller, content, held.position)) {const position = captureTranscriptReadingPosition(scroller, content, false, held.windowSize);if (position) held.position = position;}diff --git a/apps/desktop/src/lib/transcript-reading-position.ts b/apps/desktop/src/lib/transcript-reading-position.tsindex d26dc8e15..4cb58c8c1 100644--- a/apps/desktop/src/lib/transcript-reading-position.ts+++ b/apps/desktop/src/lib/transcript-reading-position.ts@@ -72,6 +72,23 @@ export function captureTranscriptReadingPosition(}}+function readingPositionRow(content: HTMLElement, messageId: string): HTMLElement | null {+ const id = CSS.escape(messageId);+ return content.querySelector<HTMLElement>(`[data-message-id="${id}"]`)+ ?? content.querySelector<HTMLElement>(`[data-minimap-id="${id}"]`);+}++/** Test the intended reading offset, before compensating a changed layout. */+export function isTranscriptReadingAnchorVisible(+ scroller: HTMLElement,+ content: HTMLElement,+ position: TranscriptReadingPosition,+): boolean {+ if (!transcriptHasLayout(scroller) || !position.messageId) return false;+ const height = readingPositionRow(content, position.messageId)?.getBoundingClientRect().height ?? 0;+ return height > 0 && position.offset < scroller.clientHeight && position.offset + height > 0;+}+/** Returns false until the bookmarked row is actually mounted. */export function restoreTranscriptReadingPosition(scroller: HTMLElement,@@ -80,9 +97,7 @@ export function restoreTranscriptReadingPosition(): boolean {if (!transcriptHasLayout(scroller)) return false;if (position.messageId) {- const id = CSS.escape(position.messageId);- const row = content.querySelector<HTMLElement>(`[data-message-id="${id}"]`)- ?? content.querySelector<HTMLElement>(`[data-minimap-id="${id}"]`);+ const row = readingPositionRow(content, position.messageId);if (row) {const rect = row.getBoundingClientRect();if (rect.height > 0) {diff --git a/apps/desktop/test/transcript-reading-position-fallback.test.mjs b/apps/desktop/test/transcript-reading-position-fallback.test.mjsindex 7ea245fd3..4fe40cf85 100644--- a/apps/desktop/test/transcript-reading-position-fallback.test.mjs+++ b/apps/desktop/test/transcript-reading-position-fallback.test.mjs@@ -7,7 +7,7 @@ register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));// `restoreTranscriptReadingPosition` escapes the id with the browser-only// `CSS.escape`; this suite runs the function directly in Node.globalThis.CSS ??= { escape: (value) => String(value).replace(/["\\]/g, "\\$&") };-const { captureTranscriptReadingPosition, restoreTranscriptReadingPosition } = await import(+const { captureTranscriptReadingPosition, restoreTranscriptReadingPosition, isTranscriptReadingAnchorVisible } = await import("../src/lib/transcript-reading-position.ts");@@ -151,3 +151,21 @@ test("restore prefers the actual message over a group with the same marker id",assert.equal(restoreTranscriptReadingPosition(scroller, content, bookmark({ offset: 20 })), true);assert.equal(scroller.scrollTop, 200);});++test("anchor visibility uses its intended offset, not displacement from a lazy predecessor", () => {+ const scroller = fakeScroller();+ const row = { getBoundingClientRect: () => ({ top: 900, height: 800 }) };+ assert.equal(isTranscriptReadingAnchorVisible(scroller, fakeContent({ row }), bookmark({ offset: 77 })), true);+});++test("an anchor changes only after its full row leaves the intended viewport", () => {+ const scroller = fakeScroller();+ const row = { getBoundingClientRect: () => ({ top: 0, height: 800 }) };+ const content = fakeContent({ row });+ for (const [offset, visible] of [[599, true], [600, false], [-799, true], [-800, false]]) {+ assert.equal(isTranscriptReadingAnchorVisible(scroller, content, bookmark({ offset })), visible);+ }+ assert.equal(isTranscriptReadingAnchorVisible(scroller, fakeContent(), bookmark()), false);+ assert.equal(isTranscriptReadingAnchorVisible(scroller, content, bookmark({ messageId: undefined })), false);+ assert.equal(isTranscriptReadingAnchorVisible({ ...scroller, clientHeight: 0 }, content, bookmark()), false);+});diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 50723e30f..9c54c9428 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -13562,7 +13562,10 @@ This test plan spec is accepted when:running, asserting `>= 3` intermediate frames, no reverse `> 2px`, and zeroempty visible-message frames) and ahead-read cases (standalone user rows andmixed grouped answers moving the same visible message `100px` during pending- IO and keeping drift `<= 2px` after prepend) alongside the retained quiet+ IO and keeping drift `<= 2px` after prepend). A preceding-row case then grows+ the newly exposed message by `400px`: retain the original readable message+ until its intended offset leaves the viewport rather than adopting that lazy+ predecessor's unstable geometry. This runs alongside the retained quietstability and pending/settled latest-button cases. Additional regressions covernative browser smooth travel across the prefetch threshold, resuming followduring pending IO, press-only interruption plus remount, delayed failed search,diff --git a/scripts/e2e/transcript-history-navigation.tsx b/scripts/e2e/transcript-history-navigation.tsxindex 12062b7fe..99b620efa 100644--- a/scripts/e2e/transcript-history-navigation.tsx+++ b/scripts/e2e/transcript-history-navigation.tsx@@ -312,18 +312,36 @@ globalThis.transcriptHistoryNavigationProbe = async (reducedOnly = false) => {} catch (error) { failures.push(String(error)); console.log("PREFETCH_REPIN_ERROR " + String(error)); }finally { anchor.stop(); }}- for (const role of ["user", "mixed"] as const) {- await reset(`prefetch-${role}`, role);+ for (const { role, lateEntry } of [+ { role: "user", lateEntry: false }, { role: "mixed", lateEntry: false },+ { role: "user", lateEntry: true },+ ] as const) {+ await reset(`prefetch-${role}${lateEntry ? "-late-entry" : ""}`, role);const anchor = begin(scroller().clientHeight * 2);try {await until(() => pending.length === 1, "history was not requested before reaching the top");assert(scroller().scrollTop > scroller().clientHeight, "prefetch started too close to the edge");assert(scroller().style.overflowY !== "hidden", "background prefetch locked scrolling");+ let previous: HTMLElement | undefined;+ if (lateEntry) {+ const row = scroller().querySelector<HTMLElement>(`[data-message-id="${CSS.escape(anchor.messageId)}"]`);+ const sibling = row?.previousElementSibling;+ assert(sibling instanceof HTMLElement, "preceding lazy message missing");+ previous = sibling;+ previous.style.contentVisibility = "visible";+ await frame(); await frame();+ const el = scroller();+ el.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -100 }));+ el.scrollTo({ top: el.scrollTop + anchor.measure() + 20, behavior: "instant" });+ el.dispatchEvent(new Event("scroll", { bubbles: true }));+ await frame(); await frame();+ }const before = scroller().scrollTop;const offsetBeforeScroll = anchor.measure();scroller().dispatchEvent(new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: -100 }));scroller().scrollTo({ top: before - 100, behavior: "instant" });await frame();+ if (previous) previous.style.paddingBottom = "400px";await frame();assert(Math.abs(anchor.measure() - offsetBeforeScroll - 100) <= 2,`prefetch undid a newer reading point: before=${offsetBeforeScroll}, now=${anchor.measure()}`);@@ -331,7 +349,7 @@ globalThis.transcriptHistoryNavigationProbe = async (reducedOnly = false) => {const offset = anchor.measure();await finish();const drift = Math.abs(anchor.measure() - offset);- const result = { role, prefetch: true, drift, top: scroller().scrollTop };+ const result = { role, lateEntry, prefetch: true, drift, top: scroller().scrollTop };console.log("EARLY_HISTORY " + JSON.stringify(result));assert(drift <= 2, `prefetched page moved the reading point: ${JSON.stringify(result)}`);results.push(result);diff --git a/tests/history-loading-scroll-test-cases.md b/tests/history-loading-scroll-test-cases.mdindex eefebbe64..9822e1736 100644--- a/tests/history-loading-scroll-test-cases.md+++ b/tests/history-loading-scroll-test-cases.md@@ -156,9 +156,11 @@ unlocked ahead-loading with native wheel movement (`beginAhead`). Itsstore, and delayed external Host IPC reads: four paired return-to-latest motioncases (ordinary tail vs paginated history × idle vs running, asserting `>= 3`intermediate frames, reversal `<= 2px`, and zero empty visible-message frames),-two ahead-read prefetch cases (standalone user rows and mixed grouped answers-moving the same visible message `100px` during IO and staying within `2px` after-prepend), two quiet message-stability cases, and four pending/settled+three ahead-read prefetch cases (standalone user rows, mixed grouped answers,+and a preceding message that grows `400px` after upward input). All move the+same visible message `100px` during IO and stay within `2px` after prepend;+the delayed predecessor must not replace a still-visible original anchor.+There are also two quiet message-stability cases and four pending/settledlatest-button cases. Boundary regressions also cross the prefetch threshold withbrowser-native smooth travel, resume follow during pending IO, interrupt by apress without a scroll and remount the saved message, start a delayed failed