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(transcript): wait for history before applying fallback
vastsae0cedc300802
diff --git a/apps/desktop/src/hooks/use-transcript-reading-position.ts b/apps/desktop/src/hooks/use-transcript-reading-position.tsindex e2ab87c91..9a1ec2d4e 100644--- a/apps/desktop/src/hooks/use-transcript-reading-position.ts+++ b/apps/desktop/src/hooks/use-transcript-reading-position.ts@@ -31,6 +31,9 @@ export function useTranscriptReadingPosition({const [initialPosition] = useState(() => getTranscriptReadingPosition(sessionId));const pendingRef = useRef(initialPosition?.pinned === false ? initialPosition : undefined);const requestRef = useRef<AbortController | null>(null);+ const completedRestoreRef = useRef<TranscriptReadingPosition | null>(null);+ const restoreReadyRef = useRef(!onRestore);+ const [restoreRevision, setRestoreRevision] = useState(0);const alignmentUntilRef = useRef(0);const wasVisibleRef = useRef(visible);useLayoutEffect(() => {@@ -67,11 +70,20 @@ export function useTranscriptReadingPosition({// completion when a pane hides/unmounts, or the reader takes over during IO.useLayoutEffect(() => {const position = pendingRef.current;- if (!visible || !position || !onRestore) return;+ if (!visible || !position || !onRestore || completedRestoreRef.current === position) return;+ // Do not start the bounded alignment window while the target may still be+ // loading. A slow history read must not be aborted by the fallback timer.+ restoreReadyRef.current = false;const controller = new AbortController();requestRef.current = controller;void onRestore(position, controller.signal).then((found) => {- if (controller.signal.aborted || found) return;+ if (controller.signal.aborted) return;+ if (found) {+ completedRestoreRef.current = position;+ restoreReadyRef.current = true;+ setRestoreRevision((revision) => revision + 1);+ return;+ }cancel();callbacks.current.onMissing();callbacks.current.remember();@@ -87,10 +99,11 @@ export function useTranscriptReadingPosition({return;}if (!pendingRef.current || !scroller || !content) return;+ if (!restoreReadyRef.current) return;let timer = 0;const align = () => {const position = pendingRef.current;- if (!position) return;+ if (!position || !restoreReadyRef.current) return;if (alignmentUntilRef.current && performance.now() >= alignmentUntilRef.current) {cancel();callbacks.current.remember();@@ -114,7 +127,7 @@ export function useTranscriptReadingPosition({window.clearTimeout(timer);observer?.disconnect();};- }, [cancel, contentRef, contentVersion, onPosition, scrollRef, visible]);+ }, [cancel, contentRef, contentVersion, onPosition, onRestore, restoreRevision, scrollRef, visible]);// Save laid-out geometry as well as native scrolls (e.g. disclosure changes).useLayoutEffect(() => {diff --git a/apps/desktop/src/lib/transcript-reading-position.ts b/apps/desktop/src/lib/transcript-reading-position.tsindex d24fbe9e3..4f6433265 100644--- a/apps/desktop/src/lib/transcript-reading-position.ts+++ b/apps/desktop/src/lib/transcript-reading-position.ts@@ -88,15 +88,14 @@ export function restoreTranscriptReadingPosition(}}// The anchored row is not mounted. A reveal mounts only a trailing slice of- // history (lib/transcript-window.ts:23-28), so an older bookmark routinely- // points at a row that is not in the DOM yet — and waiting for it to arrive- // cannot work, because a pending restore makes `useTranscriptScroll` discard- // every scroll event, so the reader can never travel up to mount it.+ // history (lib/transcript-window.ts:23-28), so an older bookmark can point+ // at a row that is not in the DOM yet. The restore hook waits for the history+ // lookup to finish before applying this fallback; otherwise its alignment+ // deadline could abort a slow lookup.//// The bookmark already recorded the absolute offset it was taken at, so fall- // back to it: an approximation of the same place beats a pane that cannot be- // scrolled and does not restore. `false` is reserved for a bookmark with no- // usable offset at all, which only a never-laid-out pane produces.+ // 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;return true;diff --git a/apps/desktop/test/transcript-reading-position-fallback.test.mjs b/apps/desktop/test/transcript-reading-position-fallback.test.mjsindex f0ba7a301..d20cde836 100644--- a/apps/desktop/test/transcript-reading-position-fallback.test.mjs+++ b/apps/desktop/test/transcript-reading-position-fallback.test.mjs@@ -17,9 +17,9 @@ const { restoreTranscriptReadingPosition } = await import(A reveal mounts only a trailing slice of history(lib/transcript-window.ts:23-28: TRANSCRIPT_INITIAL_MOUNT 15, thenTRANSCRIPT_WINDOW_MIN 60), so an older bookmark routinely names a row that is- not in the DOM. While a restore is pending `useTranscriptScroll` discards- every scroll event, so the reader cannot travel up to mount that row either —- the two together used to deadlock: no restore, no scrolling, ever.+ not in the DOM. Without a fallback, the restore loop did not move to the+ saved position. Real scroll gestures can cancel the pending restore, but+ without such a gesture the session returned at its initial position.The bookmark already carries the absolute offset it was taken at, so amissing row now falls back to that offset instead of reporting failure.@@ -73,7 +73,7 @@ test("a bookmark whose row is above the mounted window falls back to its offset"assert.equal(restoreTranscriptReadingPosition(scroller, content, bookmark({ scrollTop: 480 })),true,- "a missing row must not report failure: that is what stalled the pane",+ "a missing row with a usable offset must still restore",);assert.equal(scroller.scrollTop, 480);});diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 8ac8be4e7..7fbc06daa 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -119,7 +119,10 @@ Outer frame that positions Topbar, Sidebar, MainChat, and WorkPanel. Owns resizelayout box and its scroll offset — and are `aria-hidden` and non-interactive.Eviction releases the DOM, not the renderer-lifetime reading bookmark. Onreturn, restore the bookmarked message and its viewport offset, loading a- bounded historical range when necessary without search focus/highlighting.+ bounded historical range when necessary without search focus/highlighting. If+ the message is already loaded but outside the mounted row window, first restore+ the saved absolute scroll offset; the bounded window can then grow as the user+ scrolls toward the anchor.Explicit disclosure choices and the mounted-window budget survive eviction;bookmarks do not persist across renderer/app restarts.- A pane renders the store's live `messages` while its session is the active onediff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.mdindex 231f704e3..47687e778 100644--- a/docs/spec/04-ux/09-interaction-patterns.md+++ b/docs/spec/04-ux/09-interaction-patterns.md@@ -350,7 +350,9 @@ may be retained while exactly one workspace supplies the visible shell context.Reading bookmarks outlive DOM eviction and project switches, but not arenderer/app restart; deleting the session releases them. If the bookmarkedmessage is outside the loaded page, read a bounded range around it using the- existing history API, without search focus or highlighting. Revalidation must+ existing history API, without search focus or highlighting. If it is loaded+ but outside the mounted row window, first restore the saved absolute scroll+ offset; the user can grow the window to reach the anchor. Revalidation mustnot replace that reading range with the latest page. Real scroll input, searchnavigation, return-to-latest, and send/retry/regenerate take priority overrestoration; obsolete reads cannot reclaim the viewport. A missing anchordiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 13e71e3bb..3968d43a7 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -6080,7 +6080,9 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.paints the retained frame and offset immediately. Returning to an evictedsession restores the message and viewport offset recorded before eviction,including explicit expanded content, using a bounded historical read if the- latest page no longer contains the anchor. The cold selection's progress track+ latest page no longer contains the anchor. If the anchor is already loaded but+ outside the mounted window, the saved absolute scroll offset is restored while+ the row window remains bounded. The cold selection's progress trackand composer fence remain unchanged. No search highlight is introduced, livemodel-input messages are unchanged, and real input or a new turn cancelsautomatic alignment. First visits and pinned revisits still follow latest. Nothing isdiff --git a/scripts/e2e/transcript-reading-position.tsx b/scripts/e2e/transcript-reading-position.tsxindex 98d3dca79..f44870dc5 100644--- a/scripts/e2e/transcript-reading-position.tsx+++ b/scripts/e2e/transcript-reading-position.tsx@@ -1,10 +1,12 @@import "./session-reading-position";+import { useCallback } from "react";import { createRoot } from "react-dom/client";import { flushSync } from "react-dom";import type { UiMessage } from "@pi-desktop/shared";import { useTranscriptScroll } from "../../apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll";import { transcriptEntryMessages } from "../../apps/desktop/src/lib/assistant-turns";import { retainSessionPane, type RetainedPanes } from "../../apps/desktop/src/lib/session-panes";+import { sessionReadingState, type TranscriptReadingPosition } from "../../apps/desktop/src/lib/transcript-reading-position";import { TranscriptDisclosureProvider, useAutomaticDisclosure } from "../../apps/desktop/src/features/chat/transcript/disclosure";import { DisclosureAnchorContext } from "../../apps/desktop/src/lib/disclosure-anchor-context";@@ -13,6 +15,8 @@ const messages: UiMessage[] = Array.from({ length: 100 }, (_, index) => ({createdAt: "2026-09-01T00:00:00Z", status: "complete",}));const frame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+let finishDeferredRestore: ((found: boolean) => void) | undefined;+let deferredRestoreAborted = false;function assert(condition: unknown, label: string): asserts condition {if (!condition) throw new Error(label);}@@ -33,10 +37,17 @@ function Row({ message }: { message: UiMessage }) {}function Pane({ id, visible, running }: { id: string; visible: boolean; running: boolean }) {+ const onRestoreReading = useCallback((position: TranscriptReadingPosition, signal: AbortSignal) => {+ if (id === "G") return new Promise<boolean>((resolve) => {+ finishDeferredRestore = resolve;+ signal.addEventListener("abort", () => { deferredRestoreAborted = true; }, { once: true });+ });+ return Promise.resolve(!signal.aborted && messages.some((message) => message.id === position.messageId));+ }, [id]);const scroll = useTranscriptScroll({sessionId: id, messages, hasMoreBefore: false, isRunning: running,askPending: false, approvalPending: false, paneVisible: visible,- searchTarget: null, readingWindow: false,+ searchTarget: null, readingWindow: false, onRestoreReading,});const rows = transcriptEntryMessages(scroll.tailEntry? [...scroll.historyEntries, scroll.tailEntry] : scroll.historyEntries);@@ -119,6 +130,23 @@ globalThis.transcriptReadingPositionProbe = async () => {running = false;select("A");await until(() => bottom(scroller("A")), "pinned revisit follows latest");+ sessionReadingState("G").position = {+ pinned: false, messageId: "m10", offset: 24, scrollTop: 650, windowSize: 60,+ };+ select("G");+ await until(() => finishDeferredRestore !== undefined, "historical restore lookup starts");+ const deferredScroller = scroller("G");+ assert(!deferredScroller.querySelector('[data-message-id="m10"]'),+ "the deferred restore anchor must be outside the mounted window");+ const initialTop = deferredScroller.scrollTop;+ for (let frameIndex = 0; frameIndex < 3; frameIndex++) await frame();+ assert(Math.abs(deferredScroller.scrollTop - initialTop) < 2,+ "the saved offset must wait until the restore lookup completes");+ assert(!deferredRestoreAborted, "the alignment deadline must not abort a pending history lookup");+ finishDeferredRestore(true);+ finishDeferredRestore = undefined;+ await until(() => Math.abs(deferredScroller.scrollTop - 650) < 2,+ "the saved offset applies after a successful restore lookup");return { ok: true, warmOffset: 650, restoredOffset, panes: host.querySelectorAll("[data-pane]").length };} catch (error) {return { ok: false, error: error instanceof Error ? error.stack : String(error) };