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(desktop): preserve session reading positions across pane eviction
new-Beginner9c8868c8cc84
diff --git a/apps/desktop/src/components/SessionPane.tsx b/apps/desktop/src/components/SessionPane.tsxindex 3a30fd369..c40194fbb 100644--- a/apps/desktop/src/components/SessionPane.tsx+++ b/apps/desktop/src/components/SessionPane.tsx@@ -1,10 +1,11 @@-import { memo, useMemo } from "react";+import { memo, useCallback, useMemo } from "react";import { ChatTranscript } from "./ChatTranscript";import { useAppStore } from "../stores/app-store";import { headPermission, sessionPermissions } from "../lib/pending-permissions";import { headAsk } from "../lib/pending-asks";import { useTranscriptView } from "../hooks/use-transcript-view";import { TranscriptDisclosureProvider } from "../features/chat/transcript/disclosure";+import type { RestoreTranscriptReading } from "../hooks/use-transcript-reading-position";/*** One retained conversation pane (ADR 0137).@@ -29,6 +30,11 @@ export const SessionPane = memo(function SessionPane({const transcript = useTranscriptView(sessionId);const loadTranscriptPage = useAppStore((state) => state.loadTranscriptPage);const returnToLatest = useAppStore((state) => state.returnToLatestTranscript);+ const restoreTranscriptReading = useAppStore((state) => state.restoreTranscriptReading);+ const restoreReading = useCallback<RestoreTranscriptReading>(+ (position, signal) => restoreTranscriptReading(sessionId, position, signal),+ [restoreTranscriptReading, sessionId],+ );const isRunning = useAppStore((state) => state.runningSessions[sessionId] ?? false,);@@ -65,7 +71,7 @@ export const SessionPane = memo(function SessionPane({aria-hidden={visible ? undefined : true}inert={visible ? undefined : true}>- <TranscriptDisclosureProvider>+ <TranscriptDisclosureProvider sessionId={sessionId}><ChatTranscriptsessionId={sessionId}messages={transcript.messages}@@ -73,6 +79,7 @@ export const SessionPane = memo(function SessionPane({onLoadOlder={() => loadTranscriptPage(sessionId, "before")}searchTarget={searchTarget}readingWindow={transcript.historical}+ onRestoreReading={restoreReading}hasMoreAfter={transcript.hasMoreAfter}onLoadNewer={() => loadTranscriptPage(sessionId, "after")}onReturnToLatest={() => returnToLatest(sessionId)}diff --git a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsxindex 242d6c41f..828ca7779 100644--- a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx+++ b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx@@ -20,6 +20,7 @@ import { collectLiveDelegationEntries } from "../../../lib/live-delegation-entriimport { reuseReadonlyMap } from "../../../lib/assistant-turns";import { useTranscriptScroll } from "./hooks/useTranscriptScroll";import type { TranscriptSearchTarget } from "../../../lib/transcript-reading";+import type { RestoreTranscriptReading } from "../../../hooks/use-transcript-reading-position";import { TranscriptSearchContext } from "../../../lib/transcript-search-context";import { DisclosureAnchorContext } from "../../../lib/disclosure-anchor-context";import { api } from "../../../lib/api";@@ -52,6 +53,7 @@ type ChatTranscriptProps = {paneVisible?: boolean;searchTarget?: TranscriptSearchTarget | null;readingWindow?: boolean;+ onRestoreReading?: RestoreTranscriptReading;hasMoreAfter?: boolean;onLoadNewer?: () => Promise<void>;onReturnToLatest?: () => void;@@ -86,6 +88,7 @@ function TranscriptBody({paneVisible = true,searchTarget = null,readingWindow = false,+ onRestoreReading,hasMoreAfter = false,onLoadNewer,onReturnToLatest,@@ -152,6 +155,7 @@ function TranscriptBody({paneVisible,searchTarget,readingWindow,+ onRestoreReading,});const specializedActivity = agentActivity;diff --git a/apps/desktop/src/features/chat/transcript/disclosure.tsx b/apps/desktop/src/features/chat/transcript/disclosure.tsxindex 5688a9ac9..acb2159b2 100644--- a/apps/desktop/src/features/chat/transcript/disclosure.tsx+++ b/apps/desktop/src/features/chat/transcript/disclosure.tsx@@ -11,14 +11,19 @@ import {type ReactNode,} from "react";import { useDisclosureAnchorNotifier } from "../../../lib/disclosure-anchor-context";+import { sessionReadingState, type TranscriptDisclosureChoice } from "../../../lib/transcript-reading-position";-type Choice = { open: boolean; revealRequest?: number };+type Choice = TranscriptDisclosureChoice;/** Only explicit choices are retained; untouched nodes derive their defaults. */class DisclosureChoices {- private choices = new Map<string, Choice>();+ private choices: Map<string, Choice>;private listeners = new Map<string, Set<() => void>>();+ constructor(choices = new Map<string, Choice>()) {+ this.choices = choices;+ }+get = (key: string) => this.choices.get(key);set(key: string, choice: Choice) {@@ -45,9 +50,11 @@ const ParentContext = createContext<{ claim: () => void; visible: boolean }>({visible: true,});-/** The retained session pane owns this map; no state is persisted to the host. */-export function TranscriptDisclosureProvider({ children }: { children: ReactNode }) {- const [choices] = useState(() => new DisclosureChoices());+/** Explicit choices survive pane eviction, but never persist to the host. */+export function TranscriptDisclosureProvider({ children, sessionId }: { children: ReactNode; sessionId?: string }) {+ const [choices] = useState(() => new DisclosureChoices(+ sessionId ? sessionReadingState(sessionId).disclosures : undefined,+ ));return <ChoicesContext.Provider value={choices}>{children}</ChoicesContext.Provider>;}diff --git a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.tsindex 0d26f4f0d..32a3f525f 100644--- a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts+++ b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts@@ -40,6 +40,8 @@ import { readScrollInputContext } from "../../../../lib/scroll-input";import { useDisclosureAnchor } from "../../../../hooks/use-disclosure-anchor";import type { TranscriptSearchTarget } from "../../../../lib/transcript-reading";import { useTranscriptSearchFocus } from "../../../../hooks/use-transcript-search-focus";+import { getTranscriptReadingPosition } from "../../../../lib/transcript-reading-position";+import { useTranscriptReadingPosition, type RestoreTranscriptReading } from "../../../../hooks/use-transcript-reading-position";type UseTranscriptScrollOptions = {sessionId: string | undefined;@@ -55,6 +57,7 @@ type UseTranscriptScrollOptions = {paneVisible: boolean;searchTarget: TranscriptSearchTarget | null;readingWindow: boolean;+ onRestoreReading?: RestoreTranscriptReading;};export function useTranscriptScroll({@@ -71,12 +74,14 @@ export function useTranscriptScroll({paneVisible,searchTarget,readingWindow,+ onRestoreReading,}: UseTranscriptScrollOptions) {const scrollRef = useRef<HTMLDivElement>(null);const wrapRef = useRef<HTMLDivElement>(null);const contentRef = useRef<HTMLDivElement>(null);const historyBoundaryRef = useRef<HTMLDivElement>(null);- const pinnedRef = useRef(true);+ const [savedReadingPosition] = useState(() => getTranscriptReadingPosition(sessionId));+ const pinnedRef = useRef(savedReadingPosition?.pinned ?? true);const lastScrollTopRef = useRef(0);// Last offset sampled while the scroller had a real layout box. A hidden// pane's `content-visibility: hidden` box reports `scrollTop === 0`, so the@@ -91,7 +96,7 @@ export function useTranscriptScroll({// Steady-state cap on mounted history rows (D261). Grows when the user// reaches the top of the window; reset per session below.- const [windowSize, setWindowSize] = useState(TRANSCRIPT_WINDOW_MIN);+ const [windowSize, setWindowSize] = useState(savedReadingPosition?.windowSize ?? TRANSCRIPT_WINDOW_MIN);// Read by `reachTop`, which must stay referentially stable for the scroll// listener; the projection it describes is only known later in this render.const historyLengthRef = useRef(0);@@ -116,6 +121,24 @@ export function useTranscriptScroll({cancelAnimationFrame(followFrameRef.current);followFrameRef.current = 0;}, []);+ const recordScrollPosition = useCallback((top: number) => {+ lastScrollTopRef.current = top;+ lastLaidOutScrollTopRef.current = top;+ }, []);+ const readingPositionMissing = useCallback(() => {+ pinnedRef.current = true;+ setShowJump(false);+ scrollToBottom();+ }, [scrollToBottom]);+ const {+ pendingRef: readingPositionPendingRef,+ remember: rememberReadingPosition,+ cancel: cancelReadingPosition,+ } = useTranscriptReadingPosition({+ sessionId, scrollRef, contentRef, pinnedRef, visible: paneVisible,+ windowSize, contentVersion: messages, onPosition: recordScrollPosition,+ onRestore: onRestoreReading, onMissing: readingPositionMissing,+ });/*Leave follow mode. Every reader-driven move inside the transcript starts@@ -124,10 +147,11 @@ export function useTranscriptScroll({the view one frame later and undoes the move.*/const releaseFollow = useCallback(() => {+ cancelReadingPosition();cancelFollowScroll();pinnedRef.current = false;setShowJump(true);- }, [cancelFollowScroll]);+ }, [cancelFollowScroll, cancelReadingPosition]);// A manual disclosure (a tool, thinking or activity title; #324) hands this// scroller the very title it was toggled from, before the expansion state@@ -137,10 +161,6 @@ export function useTranscriptScroll({const enterDisclosureReading = useCallback(() => {releaseFollow();}, [releaseFollow]);- const recordScrollPosition = useCallback((top: number) => {- lastScrollTopRef.current = top;- lastLaidOutScrollTopRef.current = top;- }, []);const {notifier: disclosureAnchorNotifier,restore: restoreDisclosureAnchor,@@ -168,11 +188,12 @@ export function useTranscriptScroll({contentRef.current,);if (!isScrollGestureInput(event.type as ScrollInputType, input)) return;+ cancelReadingPosition();lastScrollGestureAtRef.current = performance.now();// Real input takes the viewport back from a held disclosure position.releaseDisclosureAnchor();},- [releaseDisclosureAnchor],+ [cancelReadingPosition, releaseDisclosureAnchor],);useEffect(() => {@@ -192,16 +213,15 @@ export function useTranscriptScroll({};}, [markScrollGesture]);- // This instance belongs to one session for its whole lifetime (ADR 0137), so- // "activation" is its own first layout: settle at the newest turn before the- // first paint, with no cross-session state to unwind.+ // Cold first visits still settle at the newest turn. A runtime bookmark wins+ // over initialization and progressive hydration when an evicted pane remounts.useLayoutEffect(() => {releaseDisclosureAnchor();cancelFollowScroll();- pinnedRef.current = true;- setShowJump(false);- scrollToBottom();- }, [cancelFollowScroll, releaseDisclosureAnchor, scrollToBottom]);+ pinnedRef.current = savedReadingPosition?.pinned ?? true;+ setShowJump(!pinnedRef.current);+ if (pinnedRef.current) scrollToBottom();+ }, [cancelFollowScroll, releaseDisclosureAnchor, savedReadingPosition, scrollToBottom]);// Revisits restore this pane's own position. A hidden scroller can be clamped// while its content grows off screen, so the offset is captured on the way out@@ -227,7 +247,7 @@ export function useTranscriptScroll({retainedScrollTopRef.current = lastLaidOutScrollTopRef.current;return;}- if (!becameVisible) return;+ if (!becameVisible || readingPositionPendingRef.current) return;if (pinnedRef.current) {scrollToBottom();return;@@ -334,6 +354,13 @@ export function useTranscriptScroll({const handleScroll = useCallback(() => {const el = scrollRef.current;if (!el) return;+ if (paneVisibleRef.current && transcriptHasLayout(el)) {+ lastLaidOutScrollTopRef.current = el.scrollTop;+ }+ if (readingPositionPendingRef.current) {+ lastScrollTopRef.current = el.scrollTop;+ return;+ }// A real gesture is never stale noise: the reader's own input took the// scroller to the near-top band, and this event is the last one that// position produces. Suppressing history continuation here would strand an@@ -355,6 +382,7 @@ export function useTranscriptScroll({pinnedRef.current = false;lastScrollTopRef.current = el.scrollTop;setShowJump(true);+ rememberReadingPosition();return;}const wasPinned = pinnedRef.current;@@ -394,7 +422,8 @@ export function useTranscriptScroll({pinnedRef.current = transition.pinned;setShowJump(transition.showJump);}- }, [cancelFollowScroll, reachTop, readingWindow, scheduleFollowScroll]);+ rememberReadingPosition();+ }, [cancelFollowScroll, reachTop, readingPositionPendingRef, readingWindow, rememberReadingPosition, scheduleFollowScroll]);// 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.@@ -405,17 +434,21 @@ export function useTranscriptScroll({const turnStarted = isRunning && !wasRunningRef.current;wasRunningRef.current = isRunning;if (!turnStarted || !paneVisible) return;+ cancelReadingPosition();releaseDisclosureAnchor();cancelFollowScroll();pinnedRef.current = true;setShowJump(false);scrollToBottom();+ rememberReadingPosition();scheduleFollowScroll();}, [cancelFollowScroll,+ cancelReadingPosition,isRunning,paneVisible,releaseDisclosureAnchor,+ rememberReadingPosition,scheduleFollowScroll,scrollToBottom,]);@@ -486,7 +519,8 @@ export function useTranscriptScroll({// its Markdown and highlighting for rows nobody was looking at.const [hydrationTick, setHydrationTick] = useState(0);const hydrationBounded =- !readingWindow && firstCommit && allHistoryEntries.length > TRANSCRIPT_INITIAL_MOUNT;+ !readingWindow && firstCommit && savedReadingPosition?.pinned !== false &&+ allHistoryEntries.length > TRANSCRIPT_INITIAL_MOUNT;// The bounded commit and the expansion must show the transcript at the same// place. A spacer sized from a per-entry guess cannot match the rows it stands// in for, so the expansion moved the visible text by the estimate error - the@@ -546,12 +580,13 @@ export function useTranscriptScroll({);const releaseSearchFollow = useCallback((fresh: boolean) => {+ cancelReadingPosition();if (fresh) prependHeightRef.current = null;releaseDisclosureAnchor();cancelFollowScroll();pinnedRef.current = false;setShowJump(true);- }, [cancelFollowScroll, releaseDisclosureAnchor]);+ }, [cancelFollowScroll, cancelReadingPosition, releaseDisclosureAnchor]);useTranscriptSearchFocus({target: searchTarget,source: searchTarget@@ -651,6 +686,7 @@ export function useTranscriptScroll({}, [reachTop, releaseDisclosureAnchor, releaseFollow]);const jumpToLatest = useCallback(() => {+ cancelReadingPosition();releaseDisclosureAnchor();pinnedRef.current = true;setShowJump(false);@@ -659,7 +695,7 @@ export function useTranscriptScroll({? "auto": "smooth",);- }, [releaseDisclosureAnchor, scrollToBottom]);+ }, [cancelReadingPosition, releaseDisclosureAnchor, scrollToBottom]);// D269: history progression follows the visible top boundary, not only a// native scroll event. A tail page can collapse to less than one viewport,@@ -683,6 +719,7 @@ export function useTranscriptScroll({frame = requestAnimationFrame(() => {if (scrollRef.current !== root ||+ readingPositionPendingRef.current ||!isHistoryRevealPosition(root, pinnedRef.current)) {return;diff --git a/apps/desktop/src/hooks/use-transcript-reading-position.ts b/apps/desktop/src/hooks/use-transcript-reading-position.tsnew file mode 100644index 000000000..0c4ad057e--- /dev/null+++ b/apps/desktop/src/hooks/use-transcript-reading-position.ts@@ -0,0 +1,121 @@+import { useCallback, useLayoutEffect, useRef, useState, type RefObject } from "react";+import {+ captureTranscriptReadingPosition,+ getTranscriptReadingPosition,+ restoreTranscriptReadingPosition,+ sessionReadingState,+ type TranscriptReadingPosition,+} from "../lib/transcript-reading-position";++export type RestoreTranscriptReading = (+ position: TranscriptReadingPosition,+ signal: AbortSignal,+) => Promise<boolean>;++/** A bounded initial alignment, cancelled by real input/navigation/new turns. */+export function useTranscriptReadingPosition({+ sessionId, scrollRef, contentRef, pinnedRef, visible, windowSize,+ contentVersion, onPosition, onRestore, onMissing,+}: {+ sessionId: string | undefined;+ scrollRef: RefObject<HTMLDivElement | null>;+ contentRef: RefObject<HTMLDivElement | null>;+ pinnedRef: RefObject<boolean>;+ visible: boolean;+ windowSize: number;+ contentVersion: unknown;+ onPosition: (top: number) => void;+ onRestore?: RestoreTranscriptReading;+ onMissing: () => void;+}) {+ const [initialPosition] = useState(() => getTranscriptReadingPosition(sessionId));+ const pendingRef = useRef(initialPosition?.pinned === false ? initialPosition : undefined);+ const requestRef = useRef<AbortController | null>(null);+ const alignmentUntilRef = useRef(0);+ const wasVisibleRef = useRef(visible);+ useLayoutEffect(() => {+ if (visible && !wasVisibleRef.current && !pinnedRef.current) {+ pendingRef.current = getTranscriptReadingPosition(sessionId);+ alignmentUntilRef.current = 0;+ }+ wasVisibleRef.current = visible;+ }, [pinnedRef, sessionId, visible]);+ const cancel = useCallback(() => {+ pendingRef.current = undefined;+ requestRef.current?.abort();+ }, []);+ const remember = useCallback(() => {+ const scroller = scrollRef.current;+ const content = contentRef.current;+ if (!sessionId || !visible || !scroller || !content || pendingRef.current) return;+ const position = captureTranscriptReadingPosition(scroller, content, pinnedRef.current, windowSize);+ if (position) sessionReadingState(sessionId).position = position;+ }, [contentRef, pinnedRef, scrollRef, sessionId, visible, windowSize]);+ const callbacks = useRef({ remember, onMissing });+ callbacks.current = { remember, onMissing };++ // Fetch only if the row is outside the current range. Abort also invalidates+ // completion when a pane hides/unmounts, or the reader takes over during IO.+ useLayoutEffect(() => {+ const position = pendingRef.current;+ if (!visible || !position || !onRestore) return;+ const controller = new AbortController();+ requestRef.current = controller;+ void onRestore(position, controller.signal).then((found) => {+ if (controller.signal.aborted || found) return;+ cancel();+ callbacks.current.onMissing();+ callbacks.current.remember();+ });+ return () => controller.abort();+ }, [cancel, onRestore, visible]);++ useLayoutEffect(() => {+ const scroller = scrollRef.current;+ const content = contentRef.current;+ if (!visible) {+ alignmentUntilRef.current = 0;+ return;+ }+ if (!pendingRef.current || !scroller || !content) return;+ let timer = 0;+ const align = () => {+ const position = pendingRef.current;+ if (!position) return;+ if (alignmentUntilRef.current && performance.now() >= alignmentUntilRef.current) {+ cancel();+ callbacks.current.remember();+ return;+ }+ if (!restoreTranscriptReadingPosition(scroller, content, position)) return;+ onPosition(scroller.scrollTop);+ if (!alignmentUntilRef.current) {+ alignmentUntilRef.current = performance.now() + 1500;+ }+ window.clearTimeout(timer);+ timer = window.setTimeout(() => {+ cancel();+ callbacks.current.remember();+ }, Math.max(0, alignmentUntilRef.current - performance.now()));+ };+ align();+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(align);+ observer?.observe(content);+ return () => {+ window.clearTimeout(timer);+ observer?.disconnect();+ };+ }, [cancel, contentRef, contentVersion, onPosition, scrollRef, visible]);++ // Save laid-out geometry as well as native scrolls (e.g. disclosure changes).+ useLayoutEffect(() => {+ if (!visible) return;+ const content = contentRef.current;+ const observer = content && typeof ResizeObserver !== "undefined" ? new ResizeObserver(remember) : null;+ if (content) observer?.observe(content);+ remember();+ return () => observer?.disconnect();+ }, [contentRef, remember, visible]);++ return { initialPosition, pendingRef, remember, cancel };+}diff --git a/apps/desktop/src/hooks/use-transcript-view.ts b/apps/desktop/src/hooks/use-transcript-view.tsindex c9bab9a7d..c778fed5e 100644--- a/apps/desktop/src/hooks/use-transcript-view.ts+++ b/apps/desktop/src/hooks/use-transcript-view.ts@@ -18,7 +18,7 @@ export function useTranscriptView(sessionId: string) {hasMoreAfter: view?.hasMoreAfter ?? false,focus: view?.focus ?? null,parentMessage: view?.parentMessage,- historical: Boolean(view?.focus),+ historical: Boolean(view?.focus || view?.restored),loading: Boolean(view?.loading),};}diff --git a/apps/desktop/src/lib/transcript-reading-position.ts b/apps/desktop/src/lib/transcript-reading-position.tsnew file mode 100644index 000000000..b4a5b8911--- /dev/null+++ b/apps/desktop/src/lib/transcript-reading-position.ts@@ -0,0 +1,69 @@+import { transcriptHasLayout } from "./transcript-scroll";++export type TranscriptReadingPosition = {+ pinned: boolean;+ messageId?: string;+ offset: number;+ scrollTop: number;+ windowSize: number;+};+export type TranscriptDisclosureChoice = { open: boolean; revealRequest?: number };+type ReadingState = {+ position?: TranscriptReadingPosition;+ disclosures: Map<string, TranscriptDisclosureChoice>;+};++// Renderer-lifetime bookmarks, independent of the bounded DOM and message caches.+// No messages, elements, subscriptions, or persisted user data are retained here.+const readingStates = new Map<string, ReadingState>();+export function sessionReadingState(sessionId: string): ReadingState {+ let state = readingStates.get(sessionId);+ if (!state) {+ state = { disclosures: new Map() };+ readingStates.set(sessionId, state);+ }+ return state;+}+export function getTranscriptReadingPosition(sessionId: string | undefined) {+ return sessionId ? readingStates.get(sessionId)?.position : undefined;+}+export function forgetTranscriptReadingState(sessionId: string) {+ readingStates.delete(sessionId);+}++/** Sample only a visible layout; hidden panes must never replace a bookmark. */+export function captureTranscriptReadingPosition(+ scroller: HTMLElement,+ content: HTMLElement,+ pinned: boolean,+ windowSize: number,+): TranscriptReadingPosition | undefined {+ if (!transcriptHasLayout(scroller)) return;+ if (pinned) return { pinned, offset: 0, scrollTop: scroller.scrollTop, windowSize };+ const viewport = scroller.getBoundingClientRect();+ // Prefer the outer message/turn: its offset also describes reading inside an+ // expanded tool body, whose explicit disclosure choices survive eviction.+ for (const row of content.querySelectorAll<HTMLElement>("[data-minimap-id], [data-message-id]")) {+ const rect = row.getBoundingClientRect();+ if (rect.bottom <= viewport.top || rect.top >= viewport.bottom || rect.height === 0) continue;+ const messageId = row.dataset.minimapId ?? row.dataset.messageId;+ if (messageId) return { pinned, messageId, offset: rect.top - viewport.top,+ scrollTop: scroller.scrollTop, windowSize };+ }+}++/** Returns false until the bookmarked row is actually mounted. */+export function restoreTranscriptReadingPosition(+ scroller: HTMLElement,+ content: HTMLElement,+ position: TranscriptReadingPosition,+): boolean {+ if (!transcriptHasLayout(scroller) || !position.messageId) return false;+ const id = CSS.escape(position.messageId);+ const row = content.querySelector<HTMLElement>(`[data-minimap-id="${id}"], [data-message-id="${id}"]`);+ if (!row) return false;+ const rect = row.getBoundingClientRect();+ if (rect.height === 0) return false;+ scroller.scrollTop += rect.top - scroller.getBoundingClientRect().top - position.offset;+ return true;+}diff --git a/apps/desktop/src/lib/transcript-reading.ts b/apps/desktop/src/lib/transcript-reading.tsindex 1d24a3eef..eb23ff69d 100644--- a/apps/desktop/src/lib/transcript-reading.ts+++ b/apps/desktop/src/lib/transcript-reading.ts@@ -23,6 +23,8 @@ export type TranscriptView = {hasMoreAfter: boolean;parentMessage?: UiMessage;focus: TranscriptSearchTarget | null;+ /** A bookmarked historical range, without search navigation/highlighting. */+ restored?: boolean;loading: "target" | "before" | "after" | null;};@@ -107,7 +109,7 @@ export function transcriptViewMessages(live: UiMessage[], view?: TranscriptView)if (!view) return live;// Search deliberately holds its historical snapshot. Do not index or merge// the live transcript when it cannot contribute anything to this view.- if (view.focus) return withNavigationParent(view.messages, view.parentMessage);+ if (view.focus || view.restored) return withNavigationParent(view.messages, view.parentMessage);const normalized = dedupeSessionMessages(live);const source = getSessionMessageSnapshot(normalized);diff --git a/apps/desktop/src/stores/app-state.ts b/apps/desktop/src/stores/app-state.tsindex 026b8f9ec..9ab1bc174 100644--- a/apps/desktop/src/stores/app-state.ts+++ b/apps/desktop/src/stores/app-state.ts@@ -32,6 +32,7 @@ import type {} from "@pi-desktop/shared";import type { SettingsTabId } from "../lib/settings-search";import type { TranscriptSearchTarget, TranscriptView } from "../lib/transcript-reading";+import type { TranscriptReadingPosition } from "../lib/transcript-reading-position";import type {ProjectMeta,ProjectSort,@@ -202,6 +203,7 @@ export type AppState = {refreshSessions: (options?: RefreshSessionsOptions) => Promise<void>;prefetchSession: (id: string) => Promise<void>;navigateTranscript: (target: Omit<TranscriptSearchTarget, "requestId">) => Promise<void>;+ restoreTranscriptReading: (sessionId: string, position: TranscriptReadingPosition, signal: AbortSignal) => Promise<boolean>;loadTranscriptPage: (sessionId: string, direction: "before" | "after") => Promise<void>;returnToLatestTranscript: (sessionId: string) => void;selectSession: (diff --git a/apps/desktop/src/stores/runtime/transcript-reading-runtime.ts b/apps/desktop/src/stores/runtime/transcript-reading-runtime.tsindex ee3924e5f..cd4db240b 100644--- a/apps/desktop/src/stores/runtime/transcript-reading-runtime.ts+++ b/apps/desktop/src/stores/runtime/transcript-reading-runtime.ts@@ -21,7 +21,7 @@ type ReadSession = () => Promise<{ session: SessionDetail | null }>;type ReadingActions = Pick<AppState,- "navigateTranscript" | "loadTranscriptPage" | "returnToLatestTranscript"+ "navigateTranscript" | "loadTranscriptPage" | "returnToLatestTranscript" | "restoreTranscriptReading">;/** Read workflows publish renderer views and never write the runtime/model cache. */@@ -66,6 +66,51 @@ export function createTranscriptReadingRuntime({ get, set }: StoreAccess, read:const actions: ReadingActions = {returnToLatestTranscript,+ restoreTranscriptReading: async (sessionId, position, signal) => {+ if (signal.aborted || get().activeSessionId !== sessionId || !position.messageId) return false;+ const previous = get().transcriptViews[sessionId];+ const range = currentView(sessionId);+ if (get().selectingSessionId !== sessionId &&+ range.messages.some((message) => message.id === position.messageId)) return true;+ // A user navigation already in flight always wins over automatic restore.+ if (range.focus || range.loading) return false;+ const pending: TranscriptView = { ...range, restored: true, loading: "target" };+ const rollback = () => {+ if (get().transcriptViews[sessionId] !== pending) return;+ if (previous) publish(sessionId, previous);+ else returnToLatestTranscript(sessionId);+ };+ publish(sessionId, pending);+ signal.addEventListener("abort", rollback, { once: true });+ try {+ const { session } = await read(sessionId, {+ messageAround: position.messageId,+ messageLimit: TRANSCRIPT_SEARCH_PAGE_SIZE,+ contentLimit: TRANSCRIPT_CONTENT_LIMIT,+ });+ if (signal.aborted || get().transcriptViews[sessionId] !== pending) return false;+ if (get().activeSessionId !== sessionId) {+ rollback();+ return false;+ }+ const message = session?.messages.find((row) => row.id === position.messageId);+ if (!session || !message || (message.parentToolCallId && !session.navigationParent)) {+ rollback();+ return false;+ }+ publish(sessionId, { ...transcriptViewFromSession(session), restored: true });+ return true;+ } catch (error) {+ if (!signal.aborted && get().transcriptViews[sessionId] === pending) {+ rollback();+ if (get().activeSessionId === sessionId)+ get().showToast(error instanceof Error ? error.message : String(error), { variant: "error" });+ }+ return false;+ } finally {+ signal.removeEventListener("abort", rollback);+ }+ },navigateTranscript: async (input) => {const { sessionId } = input;if (get().activeSessionId !== sessionId) return;@@ -144,7 +189,7 @@ export function createTranscriptReadingRuntime({ get, set }: StoreAccess, read:for (const [id, view] of Object.entries(state.transcriptViews)) {const evicted = !state.retainedSessionIds.includes(id);const started =- (view.focus || view.loading === "target") &&+ (view.focus || view.restored || view.loading === "target") &&state.runningSessions[id] &&!previous.runningSessions[id];const rewritten =@@ -152,6 +197,7 @@ export function createTranscriptReadingRuntime({ get, set }: StoreAccess, read:previous.activeSessionId === id &&!state.runningSessions[id] &&!previous.runningSessions[id] &&+ !(view.restored && previous.selectingSessionId === id) &&state.messages !== previous.messages &&transcriptWasRewritten(previous.messages, state.messages);if (evicted || started || rewritten) returnToLatestTranscript(id);diff --git a/apps/desktop/src/stores/slices/project-slice.ts b/apps/desktop/src/stores/slices/project-slice.tsindex 3241c4abd..00ff55a72 100644--- a/apps/desktop/src/stores/slices/project-slice.ts+++ b/apps/desktop/src/stores/slices/project-slice.ts@@ -1,3 +1,4 @@+import { forgetTranscriptReadingState } from "../../lib/transcript-reading-position";import i18n from "i18next";import type { ProjectWorkspace } from "@pi-desktop/shared";import { api } from "../../lib/api";@@ -150,6 +151,7 @@ function clearLocalSessionState(>,id: string,): void {+ forgetTranscriptReadingState(id);runtime.pendingSessionConfigurations.delete(id);runtime.sessionTranscriptCache.delete(id);runtime.sessionHistoryCache.delete(id);diff --git a/apps/desktop/test/interaction-performance.test.mjs b/apps/desktop/test/interaction-performance.test.mjsindex 6d210d4e1..4517668c7 100644--- a/apps/desktop/test/interaction-performance.test.mjs+++ b/apps/desktop/test/interaction-performance.test.mjs@@ -164,7 +164,7 @@ test("layout clamps after send cannot release transcript follow as a gesture", (assert.match(transcript, /if \(gesturing && transition\.releasedFollow\) \{/);});-test("session activation pins the latest record before the first paint", () => {+test("session activation pins a first visit and honors a runtime reading bookmark", () => {assert.match(chatSurface,/const activeSessionId = useAppStore\(\(state\) => state\.activeSessionId\);/,@@ -173,17 +173,16 @@ test("session activation pins the latest record before the first paint", () => {assert.match(pane, /sessionId=\{sessionId\}/);assert.doesNotMatch(chatSurface, /SessionLoadingSkeleton/);- // A pane belongs to one session for its lifetime, so activation is its own- // first layout: settle at the newest turn with no cross-session state to- // unwind, before the first paint.+ // Cold first visits still settle before paint; an evicted reading bookmark+ // takes priority over initialization. Chromium covers the actual lifecycle.const activationEffect = transcript.match(- /useLayoutEffect\(\(\) => \{([\s\S]*?)\n \}, \[cancelFollowScroll, releaseDisclosureAnchor, scrollToBottom\]\);/,+ /useLayoutEffect\(\(\) => \{([\s\S]*?)\n \}, \[cancelFollowScroll, releaseDisclosureAnchor, savedReadingPosition, scrollToBottom\]\);/,)?.[1];assert.ok(activationEffect);assert.match(activationEffect, /cancelFollowScroll\(\)/);- assert.match(activationEffect, /pinnedRef\.current = true/);- assert.match(activationEffect, /setShowJump\(false\)/);- assert.match(activationEffect, /scrollToBottom\(\)/);+ assert.match(activationEffect, /pinnedRef\.current = savedReadingPosition\?\.pinned \?\? true/);+ assert.match(activationEffect, /setShowJump\(!pinnedRef\.current\)/);+ assert.match(activationEffect, /if \(pinnedRef\.current\) scrollToBottom\(\)/);assert.doesNotMatch(activationEffect, /smooth/);});diff --git a/apps/desktop/test/transcript-reading.test.mjs b/apps/desktop/test/transcript-reading.test.mjsindex 422572c6c..274f00d18 100644--- a/apps/desktop/test/transcript-reading.test.mjs+++ b/apps/desktop/test/transcript-reading.test.mjs@@ -497,3 +497,82 @@ test("ordinary parent context stays authoritative over tracked live changes", ()assert.equal(next, initial);assert.equal(next.find((row) => row.id === "task"), parent);});++const bookmark = { pinned: false, messageId: "old", offset: -35, scrollTop: 650, windowSize: 100 };+test("an evicted reading position loads its message without search focus or live-cache writes", async () => {+ const calls = [];+ const r = reader(async (...args) => { calls.push(args); return page([message("old")]); });+ const live = r.get().messages;+ assert.equal(await r.restoreTranscriptReading("s", bookmark, new AbortController().signal), true);+ assert.deepEqual(calls, [["s", { messageAround: "old", messageLimit: 60, contentLimit: 65536 }]]);+ assert.equal(r.view().focus, null);+ assert.equal(r.view().restored, true);+ assert.deepEqual(r.visible().map((row) => row.id), ["old"]);+ assert.equal(r.get().messages, live);+ await r.loadTranscriptPage("s", "after");+ assert.equal(r.view().restored, true);+ r.returnToLatestTranscript("s");+ assert.equal(r.view(), undefined);+});++test("a loaded reading anchor does not fetch or replace the existing reading range", async () => {+ const r = reader(async () => { throw new Error("unexpected read"); }, { messages: [message("old")] });+ assert.equal(await r.restoreTranscriptReading("s", bookmark, new AbortController().signal), true);+ assert.equal(r.view(), undefined);+});++test("input cancellation prevents a delayed restoration from replacing the current view", async () => {+ const pending = deferred();+ const r = reader(() => pending.promise);+ const controller = new AbortController();+ const request = r.restoreTranscriptReading("s", bookmark, controller.signal);+ controller.abort();+ assert.equal(r.view(), undefined);+ pending.resolve(page([message("old")]));+ assert.equal(await request, false);+ assert.equal(r.view(), undefined);+});++test("search navigation owns a delayed reading restoration", async () => {+ const pending = deferred();+ let calls = 0;+ const r = reader(() => ++calls === 1 ? pending.promise : Promise.resolve(page([message("hit")])));+ const request = r.restoreTranscriptReading("s", bookmark, new AbortController().signal);+ await r.navigateTranscript(target("hit"));+ pending.resolve(page([message("old")]));+ assert.equal(await request, false);+ assert.equal(r.view().focus.messageId, "hit");+});++test("session changes, eviction and new turns invalidate a delayed reading restoration", async () => {+ for (const patch of [+ { activeSessionId: "other" }, { retainedSessionIds: [] }, { runningSessions: { s: true } },+ ]) {+ const pending = deferred();+ const r = reader(() => pending.promise);+ const request = r.restoreTranscriptReading("s", bookmark, new AbortController().signal);+ r.set(patch);+ pending.resolve(page([message("old")]));+ assert.equal(await request, false);+ assert.equal(r.view(), undefined);+ }+});++test("missing reading anchors and IO failures fall back without a stuck loading view", async () => {+ for (const read of [async () => page([message("different")]), async () => { throw new Error("read failed"); }]) {+ const r = reader(read);+ assert.equal(await r.restoreTranscriptReading("s", bookmark, new AbortController().signal), false);+ assert.equal(r.view(), undefined);+ }+});++test("selection revalidation cannot remove a restored range, but an explicit rewrite can", async () => {+ const r = reader(async () => page([message("old")]), {+ messages: [message("stale-tail")], selectingSessionId: "s",+ });+ assert.equal(await r.restoreTranscriptReading("s", bookmark, new AbortController().signal), true);+ r.set({ messages: [message("tail")], selectingSessionId: undefined });+ assert.equal(r.view().restored, true);+ r.set({ messages: [message("tail", "edited")] });+ assert.equal(r.view(), undefined);+});diff --git a/docs/adr/0137-retained-session-panes.md b/docs/adr/0137-retained-session-panes.mdindex 4472bbb0b..d228e51da 100644--- a/docs/adr/0137-retained-session-panes.md+++ b/docs/adr/0137-retained-session-panes.md@@ -71,10 +71,14 @@ Three visible costs followed:6. A **cold switch** — no retained pane — keeps the currently visible paneshowing its own session until the destination commits. Only the thin progresstrack marks the wait. The opacity dim is removed entirely.-7. **Scroll retention is per pane.** A pane restores its own position when it- becomes visible again: a pane still pinned re-anchors to the bottom, a pane- the user had scrolled up in returns to that offset. First activation of a- session still settles at its newest turn.+7. **DOM retention is per pane; reading retention is per session.** A pane+ still pinned re-anchors to the bottom. Runtime bookmarks retain a message id,+ viewport offset, window budget, and explicit disclosure choices independently+ of pane eviction or project switches. A revisit restores that message, using+ the existing bounded history read when necessary without search focus.+ First visits still settle at the newest turn. Bookmarks hold no message+ bodies or DOM and are released on session deletion or renderer/app restart.+ Real input, explicit navigation, and a new turn cancel automatic restoration.8. The **first commit is per pane and local**. Because the component instancebelongs to one session, "the first commit of this pane" is plain mount state;the cross-session hydration spacer, its rAF expansion, and its re-anchor are@@ -122,9 +126,10 @@ are untouched; panes are a renderer-side presentation bound, not a second cache.expected to return to where the user left it. First activation is unchanged andstill settles at the newest turn, and no pane may ever show another session'soffset.-- An evicted session behaves like a cold open. This is intentional and must stay- indistinguishable from a first visit rather than surfacing an error or an empty- frame.+- An evicted session rebuilds a bounded pane but restores its runtime reading+ bookmark. Only a first visit, a pinned bookmark, or a missing anchor opens at+ latest. Small bookmark/disclosure records grow with visited sessions; mounted+ transcripts and historical views remain bounded by the three-pane budget.## Alternatives considereddiff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex edce529ca..7311437d3 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -117,7 +117,11 @@ Outer frame that positions Topbar, Sidebar, MainChat, and WorkPanel. Owns resizestay mounted but are hidden with `visibility: hidden` +`content-visibility: hidden` — never `display: none`, which would destroy thelayout box and its scroll offset — and are `aria-hidden` and non-interactive.- Evicting a pane makes its session behave like a cold open on the next visit.+ Eviction releases the DOM, not the renderer-lifetime reading bookmark. On+ return, restore the bookmarked message and its viewport offset, loading a+ bounded historical range when necessary without search focus/highlighting.+ 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 oneand its retained snapshot otherwise, so no pane can show another session's rows.While a session is running, or still holds live rows the durable page hasdiff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.mdindex c61d1c03d..178ad0a6c 100644--- a/docs/spec/04-ux/09-interaction-patterns.md+++ b/docs/spec/04-ux/09-interaction-patterns.md@@ -338,8 +338,17 @@ may be retained while exactly one workspace supplies the visible shell context.`aria-busy` mark the wait, the composer stays non-interactive so a prompt cannotreach the session being left, and the destination session id is never pairedwith another session's messages. The destination is then revealed at its final- record without a top-of-history or empty-home flash. An evicted session is- indistinguishable from a first visit.+ record without a top-of-history or empty-home flash on a first visit. An+ evicted session instead restores its runtime reading bookmark: message id,+ viewport offset, mounted-window budget, and explicit disclosure choices.+ Reading bookmarks outlive DOM eviction and project switches, but not a+ renderer/app restart; deleting the session releases them. If the bookmarked+ message is outside the loaded page, read a bounded range around it using the+ existing history API, without search focus or highlighting. Revalidation must+ not replace that reading range with the latest page. Real scroll input, search+ navigation, return-to-latest, and send/retry/regenerate take priority over+ restoration; obsolete reads cannot reclaim the viewport. A missing anchor+ falls back to latest, and read failures use the existing error notification.- New Task is not a cold switch. Creating a session reveals the empty home onthe first frame (the previous conversation and retained panes clear before`session.create`). Reusing the group's latest empty session commits that emptydiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex c2e5edbf1..649ad1e86 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -5856,10 +5856,12 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.- **Expected**: Only the visible pane and the two most recently visited ones areretained; visiting beyond that budget evicts the oldest pane. A warm returnpaints the retained frame and offset immediately. Returning to an evicted- session behaves exactly like a cold open: the visible pane stays on its own- session under the thin progress track, the composer is inert until the- destination commits, and the destination then paints at its newest turn with no- error, no empty frame, and no restored offset from before eviction. Nothing is+ session 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+ and composer fence remain unchanged. No search highlight is introduced, live+ model-input messages are unchanged, and real input or a new turn cancels+ automatic alignment. First visits and pinned revisits still follow latest. Nothing isdimmed at any point, hidden panes stay non-interactive and out of theaccessibility tree, and repeated cycling neither leaks a growing number ofmounted transcripts nor leaves a pane showing another session's rows.@@ -5867,7 +5869,9 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.`04-ux/09-interaction-patterns.md` §5, ADR 0130, ADR 0137- **Acceptance**: C (switch sessions), Quality- **Milestone**: M5-- **Status**: Draft+- **Status**: Renderer regression automated by+ `node scripts/e2e-transcript-reading-position.mjs` (isolated React/Electron,+ fixture IPC); live UI scenario Draft.#### E2E-071h: Reopening a session while its response is streamingdiff --git a/scripts/e2e-transcript-reading-position.mjs b/scripts/e2e-transcript-reading-position.mjsnew file mode 100644index 000000000..47bbf0cd6--- /dev/null+++ b/scripts/e2e-transcript-reading-position.mjs@@ -0,0 +1,76 @@+#!/usr/bin/env node+/** Isolated React/Chromium regression; no running Desktop, Host, or provider. */+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { createRequire } from "node:module";+import { cp, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { resolveElectronBinary } from "./e2e/boot.mjs";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");+const require = createRequire(join(root, "packages/agent-runtime/package.json"));+const { build } = require("esbuild");+const { electronBinary } = resolveElectronBinary(root);+const temp = await mkdtemp(join(process.env.PI_SCRATCH_DIR ?? root, "reading-position-"));+try {+ await build({+ entryPoints: [join(root, "scripts/e2e/transcript-reading-position.tsx")],+ outfile: join(temp, "renderer.js"), bundle: true, platform: "browser", format: "iife",+ jsx: "automatic", define: { "process.env.NODE_ENV": '"production"', "import.meta.env": JSON.stringify({ DEV: false, MODE: "production" }) },+ loader: { ".css": "empty" },+ alias: { react: join(root, "apps/desktop/node_modules/react"),+ "react-dom": join(root, "apps/desktop/node_modules/react-dom") },+ plugins: [{ name: "url-assets", setup(build) {+ build.onResolve({ filter: /\?url$/ }, ({ path, resolveDir }) => ({+ path: join(resolveDir, path.slice(0, -4)), namespace: "url-asset",+ }));+ build.onLoad({ filter: /.*/, namespace: "url-asset" }, async ({ path }) => ({+ contents: await readFile(path), loader: "file",+ }));+ } }],+ nodePaths: [join(root, "apps/desktop/node_modules")],+ });+ const renderer = join(root, "apps/desktop/out/renderer");+ const html = await readFile(join(renderer, "index.html"), "utf8");+ const css = [...html.matchAll(/href="([^" ]+\.css)"/g)].map((match) => match[1]);+ assert(css.length, "Build Desktop before running this check");+ await cp(join(renderer, "assets"), join(temp, "assets"), { recursive: true });+ await writeFile(join(temp, "index.html"), `<!doctype html><meta charset="utf-8">${css.map((path) =>+ `<link rel="stylesheet" href="${path}">`).join("")}<script src="renderer.js"></script>`);+ await writeFile(join(temp, "main.cjs"), `+const { app, BrowserWindow } = require("electron");+const path = require("node:path");+app.setPath("userData", path.join(__dirname, "profile"));+app.whenReady().then(async () => {+ const window = new BrowserWindow({ show: false, width: 1000, height: 600,+ webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });+ window.webContents.on("console-message", (event) => console.error(event.message));+ try {+ await window.loadFile(path.join(__dirname, "index.html"));+ const scrolling = await window.webContents.executeJavaScript("globalThis.transcriptReadingPositionProbe()");+ const session = scrolling.ok ? await window.webContents.executeJavaScript("globalThis.sessionReadingPositionProbe()") : null;+ const result = { ok: scrolling.ok && session?.ok, scrolling, session };+ console.log("READING_POSITION_PROBE " + JSON.stringify(result));+ app.exit(result.ok ? 0 : 1);+ } catch (error) { console.error(error); 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; });+ const timer = setTimeout(() => child.kill("SIGKILL"), 45_000);+ let code;+ try { code = await new Promise((resolve, reject) => {+ child.once("error", reject); child.once("close", resolve);+ }); } finally { clearTimeout(timer); }+ const line = output.split(/\r?\n/).find((line) => line.startsWith("READING_POSITION_PROBE "));+ assert(line, `No probe result (exit=${code}): ${output.slice(-4000)}`);+ const result = JSON.parse(line.slice("READING_POSITION_PROBE ".length));+ console.log(JSON.stringify(result));+ assert.equal(code, 0, result.scrolling?.error ?? result.session?.error ?? output.slice(-4000));+ assert.equal(result.ok, true);+} finally {+ await rm(temp, { recursive: true, force: true });+}diff --git a/scripts/e2e/session-reading-position.tsx b/scripts/e2e/session-reading-position.tsxnew file mode 100644index 000000000..fafa14b92--- /dev/null+++ b/scripts/e2e/session-reading-position.tsx@@ -0,0 +1,144 @@+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import i18n from "i18next";+import { I18nextProvider } from "react-i18next";+import { en } from "@pi-desktop/i18n";+import { IPC } from "@pi-desktop/shared/protocol";+import type { Result, SessionSummary, UiMessage } from "@pi-desktop/shared";+import { SessionPane } from "../../apps/desktop/src/components/SessionPane";+import { useAppStore } from "../../apps/desktop/src/stores/app-store";++const createdAt = "2026-09-01T00:00:00Z";+const messages: UiMessage[] = Array.from({ length: 140 }, (_, index) => ({+ id: `real-m${index}`, role: "user", content: `Message ${index}. ${"Synthetic reading content. ".repeat(30)}`,+ createdAt, status: "complete",+}));+const sessions: SessionSummary[] = ["A", "B", "C", "D", "E"].map((id) => ({+ id: `real-${id}`, title: id, mode: "agent", permissionMode: "ask", thinkingLevel: "off",+ providerId: "fixture", modelId: "fixture", createdAt, updatedAt: createdAt, messageCount: messages.length,+}));+const frame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+function assert(condition: unknown, label: string): asserts condition {+ if (!condition) throw new Error(label);+}+async function until(predicate: () => boolean, label: string) {+ for (let i = 0; i < 240; i++) {+ if (predicate()) return;+ await frame();+ }+ throw new Error(`Timed out: ${label}`);+}+function Panes() {+ const active = useAppStore((state) => state.activeSessionId);+ const retained = useAppStore((state) => state.retainedSessionIds);+ return <div className="session-panes">{retained.map((id) =>+ <SessionPane key={id} sessionId={id} visible={id === active} />)}</div>;+}++declare global { var sessionReadingPositionProbe: () => Promise<unknown>; }+globalThis.sessionReadingPositionProbe = async () => {+ await i18n.init({ lng: "en", resources: { en: { translation: en } } });+ const initial = useAppStore.getState();+ const bridge = window.piDesktop;+ let firstARead = true;+ const aroundReads: string[] = [];+ const unexpected: string[] = [];+ window.piDesktop = {+ channels: IPC, platform: "win32", on: () => () => {},+ invoke: async <T,>(channel: string, ...args: unknown[]): Promise<Result<T>> => {+ let data: unknown;+ if (channel === IPC.invoke.sessionGet) {+ const input = args[0];+ assert(input && typeof input === "object" && "id" in input, "invalid history request");+ const session = sessions.find((candidate) => candidate.id === input.id);+ assert(session, "unexpected session");+ const around = "messageAround" in input ? String(input.messageAround) : undefined;+ let start = 110;+ let end = messages.length;+ if (around) {+ aroundReads.push(around);+ const index = messages.findIndex((row) => row.id === around);+ assert(index >= 0, "missing anchor");+ start = Math.max(0, index - 20);+ end = Math.min(messages.length, index + 40);+ } else if (input.id === "real-A" && firstARead) {+ firstARead = false;+ start = 0;+ }+ data = { session: { ...session, messages: messages.slice(start, end), messageStart: start,+ messageEnd: end, hasMoreBefore: start > 0, hasMoreAfter: end < messages.length } };+ } else if (channel === IPC.invoke.sessionList) data = { sessions };+ else if (channel === IPC.invoke.plansPending) data = { plans: [], state: "inactive" };+ else if (channel === IPC.invoke.pendingInteractive) data = { permissions: [], asks: [] };+ else if (channel === IPC.invoke.agentQueueList) data = { entries: [] };+ else if (channel === IPC.invoke.notificationMarkRead || channel === IPC.invoke.notificationSetViewingSession) data = { ok: true };+ else {+ unexpected.push(channel);+ return { ok: false, error: { code: "FIXTURE_UNEXPECTED", message: `Unexpected IPC ${channel}` } };+ }+ // The only mock is the generic, typed IPC boundary; all renderer wiring is real.+ return { ok: true, data: data as T };+ },+ };+ const host = document.createElement("div");+ host.style.cssText = "position:fixed;inset:0;display:flex;flex-direction:column";+ document.body.append(host);+ const root = createRoot(host);+ const select = async (id: string) => {+ await useAppStore.getState().selectSession(`real-${id}`);+ await frame();+ };+ const scroller = () => host.querySelector<HTMLDivElement>('[data-visible="true"] .thread-scroll')!;+ const row = (id: string) => scroller().querySelector<HTMLElement>(`[data-message-id="${id}"]`);+ const offset = (id: string) => row(id)!.getBoundingClientRect().top - scroller().getBoundingClientRect().top;+ try {+ useAppStore.setState({+ sessions, messages: [], activeSessionId: undefined, selectingSessionId: undefined,+ retainedSessionIds: [], retainedTranscripts: {}, transcriptViews: {}, sessionHistory: {},+ sessionCompactions: {}, providers: [], providerModels: {}, pendingPlans: {}, pendingAsks: {},+ pendingPermissions: {}, planningStates: {}, runningSessions: {}, isRunning: false,+ workspace: undefined, queuedPrompts: {}, notifications: [], page: "chat",+ settings: { ...initial.settings, smoothStreaming: false },+ });+ flushSync(() => root.render(<I18nextProvider i18n={i18n}><Panes /></I18nextProvider>));+ await select("A");+ await until(() => !host.querySelector('[data-transcript-settling="true"]'), "cold transcript settles");+ const a = scroller();+ a.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -800 }));+ a.scrollTop = 650;+ a.dispatchEvent(new Event("scroll", { bubbles: true }));+ await frame();+ const anchor = [...a.querySelectorAll<HTMLElement>("[data-message-id]")].find((node) =>+ node.getBoundingClientRect().bottom > a.getBoundingClientRect().top)!;+ const id = anchor.dataset.messageId!;+ const expectedOffset = offset(id);+ await select("B");+ await select("A");+ await until(() => Boolean(row(id)) && Math.abs(offset(id) - expectedOffset) < 2,+ "warm production pane preserves reading through revalidation");+ for (const id of ["B", "C", "D", "E"]) await select(id);+ assert(!host.querySelector('[data-session-pane="real-A"]'), "A was not evicted");+ await select("A");+ await until(() => Boolean(row(id)) && Math.abs(offset(id) - expectedOffset) < 2,+ "evicted production pane restores historical anchor");+ assert(aroundReads.includes(id), "history restoration did not read around the bookmarked message");+ assert(!host.querySelector(".transcript-search-target"), "restore must not create search highlighting");+ assert(host.querySelectorAll("[data-session-pane]").length === 3, "pane count changed");+ assert(useAppStore.getState().messages[0]?.id === "real-m110", "restore changed canonical/live input");+ const restoredOffset = offset(id);+ const jump = host.querySelector<HTMLButtonElement>('[data-visible="true"] .jump-latest-btn')!;+ flushSync(() => jump.click());+ await until(() => !useAppStore.getState().transcriptViews["real-A"] &&+ Math.abs(scroller().scrollHeight - scroller().clientHeight - scroller().scrollTop) < 2,+ "return to latest exits history and resumes follow");+ assert(unexpected.length === 0, `unexpected IPC: ${unexpected}`);+ return { ok: true, anchor: id, restoredOffset, aroundReads, panes: 3 };+ } catch (error) {+ return { ok: false, error: error instanceof Error ? error.stack : String(error), unexpected, aroundReads };+ } finally {+ flushSync(() => root.unmount());+ host.remove();+ window.piDesktop = bridge;+ useAppStore.setState(initial);+ }+};diff --git a/scripts/e2e/transcript-reading-position.tsx b/scripts/e2e/transcript-reading-position.tsxnew file mode 100644index 000000000..98d3dca79--- /dev/null+++ b/scripts/e2e/transcript-reading-position.tsx@@ -0,0 +1,129 @@+import "./session-reading-position";+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 { TranscriptDisclosureProvider, useAutomaticDisclosure } from "../../apps/desktop/src/features/chat/transcript/disclosure";+import { DisclosureAnchorContext } from "../../apps/desktop/src/lib/disclosure-anchor-context";++const messages: UiMessage[] = Array.from({ length: 100 }, (_, index) => ({+ id: `m${index}`, role: "user", content: `Message ${index}`,+ createdAt: "2026-09-01T00:00:00Z", status: "complete",+}));+const frame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+function assert(condition: unknown, label: string): asserts condition {+ if (!condition) throw new Error(label);+}+async function until(predicate: () => boolean, label: string) {+ for (let i = 0; i < 180; i++) {+ if (predicate()) return;+ await frame();+ }+ throw new Error(`Timed out: ${label}`);+}++function Row({ message }: { message: UiMessage }) {+ const disclosure = useAutomaticDisclosure(false, undefined, message.id);+ return <div data-message-id={message.id} style={{ height: disclosure.open ? 500 : 100 }}>+ <button ref={disclosure.titleRef} onClick={disclosure.toggle}>{message.content}</button>+ {disclosure.open ? <div data-expanded="true" ref={disclosure.bodyRef}>Expanded reading content</div> : null}+ </div>;+}++function Pane({ id, visible, running }: { id: string; visible: boolean; running: boolean }) {+ const scroll = useTranscriptScroll({+ sessionId: id, messages, hasMoreBefore: false, isRunning: running,+ askPending: false, approvalPending: false, paneVisible: visible,+ searchTarget: null, readingWindow: false,+ });+ const rows = transcriptEntryMessages(scroll.tailEntry+ ? [...scroll.historyEntries, scroll.tailEntry] : scroll.historyEntries);+ return <div data-pane={id} style={visible+ ? { position: "absolute", inset: 0 }+ : { position: "absolute", inset: 0, visibility: "hidden", contentVisibility: "hidden" }}>+ <div ref={scroll.wrapRef} style={{ height: "100%" }}>+ <div ref={scroll.scrollRef} onScroll={scroll.handleScroll}+ style={{ height: "100%", overflowY: "auto", overflowAnchor: "none" }}>+ <div ref={scroll.contentRef}>+ <TranscriptDisclosureProvider sessionId={id}>+ <DisclosureAnchorContext.Provider value={scroll.disclosureAnchorNotifier}>+ {rows.map((message) => <Row key={message.id} message={message} />)}+ </DisclosureAnchorContext.Provider>+ </TranscriptDisclosureProvider>+ </div>+ </div>+ </div>+ </div>;+}++declare global { var transcriptReadingPositionProbe: () => Promise<unknown>; }+globalThis.transcriptReadingPositionProbe = async () => {+ const host = document.createElement("div");+ host.style.cssText = "position:fixed;inset:0";+ document.body.append(host);+ const root = createRoot(host);+ let panes: RetainedPanes = { retainedSessionIds: [], retainedTranscripts: {} };+ let running = false;+ const select = (id: string) => {+ panes = retainSessionPane(panes, id, messages);+ flushSync(() => root.render(<>{panes.retainedSessionIds.map((held) =>+ <Pane key={held} id={held} visible={held === id} running={running && held === id} />)}</>));+ };+ const scroller = (id: string) => host.querySelector(`[data-pane="${id}"]`)!.firstElementChild!+ .firstElementChild as HTMLDivElement;+ const bottom = (el: HTMLDivElement) => Math.abs(el.scrollTop - (el.scrollHeight - el.clientHeight)) < 2;+ try {+ select("A");+ await until(() => scroller("A").scrollHeight > 2000 && bottom(scroller("A")), "cold open follows latest");+ const a = scroller("A");+ a.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -500 }));+ a.scrollTop = 650;+ a.dispatchEvent(new Event("scroll", { bubbles: true }));+ await frame();+ const row = a.querySelector<HTMLElement>('[data-message-id="m47"]');+ assert(row, "reading row exists");+ select("B");+ await frame();+ select("A");+ assert(Math.abs(a.scrollTop - 650) < 2, `warm return lost offset: ${a.scrollTop}`);+ flushSync(() => row.querySelector<HTMLButtonElement>("button")!.click());+ await frame();+ a.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: 400 }));+ a.scrollTop = 1100;+ a.dispatchEvent(new Event("scroll", { bubbles: true }));+ await frame();+ const offset = row.getBoundingClientRect().top - a.getBoundingClientRect().top;+ select("B"); select("C"); select("D"); select("E");+ assert(!host.querySelector('[data-pane="A"]'), "A must really unmount");+ assert(host.querySelectorAll("[data-pane]").length === 3, "pane retention remains bounded");+ select("A");+ const restored = scroller("A");+ await until(() => Boolean(restored.querySelector('[data-message-id="m47"]')), "reading row remounts");+ await frame();+ const restoredRow = restored.querySelector<HTMLElement>('[data-message-id="m47"]')!;+ const restoredOffset = restoredRow.getBoundingClientRect().top - restored.getBoundingClientRect().top;+ assert(Math.abs(restoredOffset - offset) < 2,+ `evicted return lost reading row offset: ${restoredOffset} vs ${offset}`);+ assert(restoredRow.querySelector('[data-expanded="true"]'), "explicit expansion was lost on eviction");+ restored.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: 100 }));+ restored.scrollTop = 1200;+ restored.dispatchEvent(new Event("scroll", { bubbles: true }));+ await frame();+ assert(Math.abs(restored.scrollTop - 1200) < 2, "restoration stole the viewport back from real input");+ running = true;+ select("A");+ await until(() => bottom(restored), "starting a turn resumes follow");+ select("B"); select("C"); select("D"); select("E");+ running = false;+ select("A");+ await until(() => bottom(scroller("A")), "pinned revisit follows latest");+ 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) };+ } finally {+ flushSync(() => root.unmount());+ host.remove();+ }+};