Skip to content

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

fix(chat): smooth latest navigation and prefetch older history

new-Beginner3fcdcbbae837
diff --git a/apps/desktop/src/components/SessionPane.tsx b/apps/desktop/src/components/SessionPane.tsx
index 39428ad9d..a80d75484 100644
--- a/apps/desktop/src/components/SessionPane.tsx
+++ b/apps/desktop/src/components/SessionPane.tsx
@@ -30,6 +30,8 @@ export const SessionPane = memo(function SessionPane({
const transcript = useTranscriptView(sessionId);
const loadTranscriptPage = useAppStore((state) => state.loadTranscriptPage);
const returnToLatest = useAppStore((state) => state.returnToLatestTranscript);
+ const prepareReturnToLatest = useAppStore((state) => state.prepareReturnToLatestTranscript);
+ const prepareLatest = useCallback(() => prepareReturnToLatest(sessionId), [prepareReturnToLatest, sessionId]);
const restoreTranscriptReading = useAppStore((state) => state.restoreTranscriptReading);
const restoreReading = useCallback<RestoreTranscriptReading>(
(position, signal) => restoreTranscriptReading(sessionId, position, signal),
@@ -84,6 +86,7 @@ export const SessionPane = memo(function SessionPane({
hasMoreAfter={transcript.hasMoreAfter}
onLoadNewer={() => loadTranscriptPage(sessionId, "after")}
onReturnToLatest={() => returnToLatest(sessionId)}
+ onPrepareReturnToLatest={prepareLatest}
navigationLoading={transcript.loading}
isRunning={isRunning}
pendingPermission={transcript.liveTail ? pendingPermission : undefined}
diff --git a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx
index b5e919ada..2a3bc8853 100644
--- a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx
+++ b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx
@@ -1,4 +1,4 @@
-import { memo, useMemo, useRef, useState, type MouseEvent as ReactMouseEvent } from "react";
+import { memo, useCallback, useMemo, useRef, useState, type MouseEvent as ReactMouseEvent } from "react";
import { useTranslation } from "react-i18next";
import type { PlanningState, RadialMenuAction, UiMessage } from "@pi-desktop/shared";
import { proposalKindForMode } from "@pi-desktop/shared";
@@ -78,6 +78,7 @@ type ChatTranscriptProps = {
hasMoreAfter?: boolean;
onLoadNewer?: () => Promise<void>;
onReturnToLatest?: () => void;
+ onPrepareReturnToLatest?: () => (() => void);
navigationLoading?: boolean;
};
@@ -114,6 +115,7 @@ function TranscriptBody({
hasMoreAfter = false,
onLoadNewer,
onReturnToLatest,
+ onPrepareReturnToLatest,
navigationLoading = false,
}: ChatTranscriptProps) {
const { t } = useTranslation();
@@ -189,8 +191,8 @@ function TranscriptBody({
compactions,
hasMoreBefore,
onLoadOlder,
- // Rejoining live output is not a new turn: keep the reader's scroll owner.
- isRunning: isRunning && !readingWindow,
+ // Execution state is independent of the historical reading range.
+ isRunning,
pendingPermission,
askPending,
approvalPending,
@@ -200,6 +202,10 @@ function TranscriptBody({
readingWindow,
onRestoreReading,
});
+ const returnToLatest = useCallback(() => {
+ const arrive = onPrepareReturnToLatest?.() ?? onReturnToLatest;
+ jumpToLatest(arrive);
+ }, [jumpToLatest, onPrepareReturnToLatest, onReturnToLatest]);
const continuationCursor = useAppStore((state) =>
sessionId ? state.transcriptViews[sessionId]?.messageEnd : undefined,
@@ -351,10 +357,7 @@ function TranscriptBody({
id,
label,
icon: <IconArrowDown size={16} />,
- onSelect: () => {
- onReturnToLatest?.();
- jumpToLatest();
- },
+ onSelect: returnToLatest,
};
case "open-browser":
return {
@@ -416,10 +419,7 @@ function TranscriptBody({
scrollRef,
contentRef,
actions: { copyText, selectText },
- onReturnToLatest: () => {
- onReturnToLatest?.();
- jumpToLatest();
- },
+ onReturnToLatest: returnToLatest,
}),
});
};
@@ -557,10 +557,7 @@ function TranscriptBody({
className="jump-latest-btn"
ariaLabel={t("chat.scrollToBottom")}
tooltip={t("chat.scrollToBottom")}
- onClick={() => {
- onReturnToLatest?.();
- jumpToLatest();
- }}
+ onClick={returnToLatest}
>
<IconArrowDown size={14} />
</TooltipButton>
diff --git a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts
index 848619dfe..bd3380c4a 100644
--- a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts
+++ b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts
@@ -7,12 +7,30 @@ import {
import { readScrollInputContext, stopSmoothScroll } from "../../../../lib/scroll-input";
import { isScrollGestureInput, type ScrollInputType } from "../../../../lib/transcript-scroll";
-type Hold = { position: TranscriptReadingPosition; settled: boolean; stableFrames: number; page: boolean; sourceHead?: string; scroller: HTMLDivElement; overflowY: string };
+type Hold = {
+ position: TranscriptReadingPosition;
+ settled: boolean;
+ stableFrames: number;
+ page: boolean;
+ background: boolean;
+ windowSize: number;
+ sourceHead?: string;
+ alignedHead?: string;
+ height: number;
+ top: number;
+ viewport: number;
+ scroller: HTMLDivElement;
+ overflowY: string;
+};
-/** One owner for page IO, mounted-window growth and their pre-paint anchor.
- * Input during a prepend is discarded, never replayed against the new history.
- * A pending IO operation remains single-flight even if navigation cancels its
- * viewport hold; its late result cannot claim a new pane or navigation target. */
+const layoutChanged = (held: Hold, sourceHead: string | undefined) =>
+ held.height !== held.scroller.scrollHeight || held.viewport !== held.scroller.clientHeight ||
+ held.alignedHead !== sourceHead;
+
+/** Single-flight page IO and pre-paint anchoring. Ahead-loading follows the
+ * reader's newest position without blocking input. Only the hard-edge fallback
+ * discards scroll input until its prepend settles. Cancelled IO cannot acquire
+ * a newer navigation target. */
export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, sourceHead, onStart, onPosition, onSettled }: {
scrollRef: RefObject<HTMLDivElement | null>;
contentRef: RefObject<HTMLDivElement | null>;
@@ -36,7 +54,7 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, sou
const dropHold = useCallback(() => {
const held = holdRef.current;
- if (held) held.scroller.style.overflowY = held.overflowY;
+ if (held && !held.background) held.scroller.style.overflowY = held.overflowY;
holdRef.current = null;
cancelAnimationFrame(frameRef.current);
frameRef.current = 0;
@@ -46,29 +64,55 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, sou
setPhase("idle");
}, [dropHold]);
const isHeld = useCallback(() => holdRef.current !== null, []);
+ const isLocked = useCallback(() => Boolean(holdRef.current && !holdRef.current.background), []);
+ const track = useCallback(() => {
+ const held = holdRef.current;
+ const 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 {
+ const position = captureTranscriptReadingPosition(scroller, content, false, held.windowSize);
+ if (position) held.position = position;
+ }
+ held.top = scroller.scrollTop;
+ }, [contentRef, scrollRef]);
const restore = useCallback(() => {
const held = holdRef.current;
const scroller = scrollRef.current;
const content = contentRef.current;
if (!held || !scroller || !content) return false;
+ if (held.background) {
+ track();
+ if (!layoutChanged(held, sourceHeadRef.current)) return false;
+ }
const before = scroller.scrollTop;
restoreTranscriptReadingPosition(scroller, content, held.position);
+ held.height = scroller.scrollHeight;
+ held.viewport = scroller.clientHeight;
+ held.alignedHead = sourceHeadRef.current;
+ held.top = scroller.scrollTop;
if (Math.abs(scroller.scrollTop - before) > 1) held.stableFrames = 0;
callbacks.current.onPosition(scroller.scrollTop);
return true;
- }, [contentRef, scrollRef]);
+ }, [contentRef, scrollRef, track]);
- const run = useCallback((action: () => void | Promise<void>, windowSize: number, page = false) => {
+ const run = useCallback((action: () => void | Promise<void>, windowSize: number, page = false, background = false) => {
const scroller = scrollRef.current;
const content = contentRef.current;
if (holdRef.current || inFlightRef.current || autoBlockedRef.current || !scroller || !content) return;
- stopSmoothScroll(scroller);
+ if (!background) stopSmoothScroll(scroller);
const position = captureTranscriptReadingPosition(scroller, content, false, windowSize)
?? { pinned: false, offset: 0, scrollTop: scroller.scrollTop, windowSize };
- const hold: Hold = { position, settled: false, stableFrames: 0, page, sourceHead: sourceHeadRef.current,
+ const hold: Hold = { position, settled: false, stableFrames: 0, page, background, windowSize,
+ sourceHead: sourceHeadRef.current, alignedHead: sourceHeadRef.current,
+ height: scroller.scrollHeight, top: scroller.scrollTop, viewport: scroller.clientHeight,
scroller, overflowY: scroller.style.overflowY };
holdRef.current = hold; // Synchronous: two scroll events cannot start two pages.
- scroller.style.overflowY = "hidden";
+ if (!background) scroller.style.overflowY = "hidden";
inFlightRef.current = true;
callbacks.current.onStart();
setPhase(page ? "page" : "mount");
@@ -145,7 +189,7 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, sou
const scroller = scrollRef.current;
if (!scroller) return;
const block = (event: Event) => {
- if (!holdRef.current || (event instanceof WheelEvent && (event.ctrlKey || Math.abs(event.deltaX) > Math.abs(event.deltaY)))) return;
+ if (!isLocked() || (event instanceof WheelEvent && (event.ctrlKey || Math.abs(event.deltaX) > Math.abs(event.deltaY)))) return;
const input = readScrollInputContext(event, scroller, contentRef.current);
if (!isScrollGestureInput(event.type as ScrollInputType, input)) return;
// Do not interfere with fields, title activation, nested docks or zoom.
@@ -158,7 +202,7 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, sou
for (const type of ["wheel", "touchmove", "keydown"]) scroller.removeEventListener(type, block, true);
dropHold();
};
- }, [contentRef, dropHold, scrollRef]);
+ }, [contentRef, dropHold, isLocked, scrollRef]);
- return { loadingOlder: phase === "page", pending: phase !== "idle", run, restore, isHeld, cancel, retry };
+ return { loadingOlder: phase === "page", pending: phase !== "idle", run, restore, isHeld, isLocked, track, cancel, retry };
}
diff --git a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptLatestNavigation.ts b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptLatestNavigation.ts
new file mode 100644
index 000000000..c87fae4b6
--- /dev/null
+++ b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptLatestNavigation.ts
@@ -0,0 +1,29 @@
+import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from "react";
+import { createTranscriptLatestNavigation } from "../../../../lib/transcript-latest-navigation";
+
+export function useTranscriptLatestNavigation({ scrollRef, visible, onPosition }: {
+ scrollRef: RefObject<HTMLDivElement | null>;
+ visible: boolean;
+ onPosition: (top: number) => void;
+}) {
+ const position = useRef(onPosition);
+ position.current = onPosition;
+ const [navigation] = useState(() => createTranscriptLatestNavigation({
+ geometry: () => scrollRef.current ?? undefined,
+ move: top => {
+ const scroller = scrollRef.current;
+ if (!scroller) return;
+ scroller.scrollTo({ top, behavior: "instant" });
+ position.current(scroller.scrollTop);
+ },
+ request: frame => requestAnimationFrame(frame),
+ cancel: frame => cancelAnimationFrame(frame),
+ now: () => performance.now(),
+ reducedMotion: () => window.matchMedia("(prefers-reduced-motion: reduce)").matches,
+ }));
+ // The explicit latest intent survives an immediate pane hide or eviction.
+ // Reader input cancels without committing; it keeps the prepared history view.
+ useLayoutEffect(() => { if (!visible) navigation.cancel(true); }, [navigation, visible]);
+ useEffect(() => () => navigation.cancel(true), [navigation]);
+ return navigation;
+}
diff --git a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
index e0e4392de..af64c19a1 100644
--- a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
+++ b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
@@ -29,6 +29,7 @@ import {
import {
HISTORY_REVEAL_THRESHOLD_PX,
isHistoryRevealPosition,
+ isHistoryPrefetchPosition,
isRecentScrollGesture,
isScrollGestureInput,
reduceTranscriptScroll,
@@ -47,6 +48,7 @@ import {
import { useTranscriptReadingPosition, type RestoreTranscriptReading } from "../../../../hooks/use-transcript-reading-position";
import { useTurnCompletionScroll } from "./useTurnCompletionScroll";
import { useTranscriptHistoryPaging } from "./useTranscriptHistoryPaging";
+import { useTranscriptLatestNavigation } from "./useTranscriptLatestNavigation";
type UseTranscriptScrollOptions = {
sessionId: string | undefined;
@@ -103,8 +105,15 @@ export function useTranscriptScroll({
// 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);
+ const latestNavigation = useTranscriptLatestNavigation({
+ scrollRef, visible: paneVisible, onPosition: top => {
+ lastScrollTopRef.current = top;
+ lastLaidOutScrollTopRef.current = top;
+ },
+ });
const scrollToBottom = useCallback((behavior: ScrollBehavior = "auto") => {
+ if (latestNavigation.isActive()) return;
const el = scrollRef.current;
if (!el || !transcriptHasLayout(el)) return;
const targetTop = Math.max(0, el.scrollHeight - el.clientHeight);
@@ -118,7 +127,7 @@ export function useTranscriptScroll({
lastScrollTopRef.current = el.scrollTop;
lastLaidOutScrollTopRef.current = el.scrollTop;
}
- }, []);
+ }, [latestNavigation]);
const cancelFollowScroll = useCallback(() => {
cancelAnimationFrame(followFrameRef.current);
@@ -159,9 +168,10 @@ export function useTranscriptScroll({
the view one frame later and undoes the move.
*/
const releaseFollow = useCallback(() => {
+ latestNavigation.cancel();
stopSmoothScroll(scrollRef.current);
leaveFollow();
- }, [leaveFollow]);
+ }, [latestNavigation, leaveFollow]);
// A manual disclosure (a tool, thinking or activity title; #324) hands this
// scroller the very title it was toggled from, before the expansion state
@@ -187,7 +197,8 @@ export function useTranscriptScroll({
}, [releaseDisclosureAnchor, releaseFollow]);
const {
loadingOlder, pending: historyPending, run: preserveHistory, retry: retryHistoryPaging,
- restore: restoreHistoryAnchor, isHeld: isHistoryPaging, cancel: cancelHistoryPaging,
+ restore: restoreHistoryAnchor, isHeld: isHistoryPaging, isLocked: isHistoryLocked,
+ track: trackHistoryPosition, cancel: cancelHistoryPaging,
} = useTranscriptHistoryPaging({
scrollRef, contentRef, visible: paneVisible, sourceHead: messages[0]?.id, onStart: startHistoryReading,
onPosition: recordScrollPosition, onSettled: rememberReadingPosition,
@@ -211,13 +222,15 @@ export function useTranscriptScroll({
// consumes belongs to that dock.
const markScrollGesture = useCallback(
(event: Event) => {
- if (isHistoryPaging()) return;
+ if (isHistoryLocked()) return;
+ if (event instanceof WheelEvent && (event.ctrlKey || event.deltaY === 0 || Math.abs(event.deltaX) > Math.abs(event.deltaY))) return;
const input = readScrollInputContext(
event,
scrollRef.current,
contentRef.current,
);
if (!isScrollGestureInput(event.type as ScrollInputType, input)) return;
+ if (latestNavigation.isActive()) { latestNavigation.cancel(); leaveFollow(); }
if (!(event instanceof WheelEvent) || (!event.ctrlKey && event.deltaY !== 0)) retryHistoryPaging();
// Minimap / jump navigation runs in the browser, independently of our
// follow rAF. Real input must retire that animation at its current offset
@@ -228,7 +241,7 @@ export function useTranscriptScroll({
// Real input takes the viewport back from a held disclosure position.
releaseDisclosureAnchor();
},
- [cancelReadingPosition, isHistoryPaging, releaseDisclosureAnchor, retryHistoryPaging],
+ [cancelReadingPosition, isHistoryLocked, latestNavigation, leaveFollow, releaseDisclosureAnchor, retryHistoryPaging],
);
useEffect(() => {
@@ -321,6 +334,7 @@ export function useTranscriptScroll({
const paneVisibleRef = useRef(paneVisible);
paneVisibleRef.current = paneVisible;
const scheduleFollowScroll = useCallback(() => {
+ if (latestNavigation.isActive()) return;
if (isHistoryPaging()) return;
if (!paneVisibleRef.current) return;
// A held disclosure position wins over a queued follow frame: re-asserting
@@ -332,7 +346,7 @@ export function useTranscriptScroll({
followFrameRef.current = 0;
if (paneVisibleRef.current && pinnedRef.current) scrollToBottom();
});
- }, [isDisclosureAnchorHeld, isHistoryPaging, scrollToBottom]);
+ }, [isDisclosureAnchorHeld, isHistoryPaging, latestNavigation, scrollToBottom]);
// Re-pins before the browser paints. A ResizeObserver callback runs after
// layout and before paint, so a `requestAnimationFrame` requested from it
@@ -355,10 +369,10 @@ export function useTranscriptScroll({
useEffect(() => cancelFollowScroll, [cancelFollowScroll]);
- const loadOlder = useCallback(() => {
+ const loadOlder = useCallback((background = false) => {
if (!paneVisibleRef.current) return;
if (!hasMoreBefore || !onLoadOlder) return;
- preserveHistory(onLoadOlder, windowSize, true);
+ preserveHistory(onLoadOlder, windowSize, true, background);
}, [hasMoreBefore, onLoadOlder, preserveHistory, windowSize]);
/**
@@ -367,15 +381,15 @@ export function useTranscriptScroll({
* it. Both stages anchor the viewport the same way, because both change
* scrollHeight above the rows the user is reading.
*/
- const reachTop = useCallback(() => {
+ const reachTop = useCallback((background = false) => {
const el = scrollRef.current;
if (!el || isHistoryPaging()) return;
const grown = growTranscriptWindow(windowSize, historyLengthRef.current);
if (grown !== windowSize) {
- preserveHistory(() => setWindowSize(grown), windowSize);
+ preserveHistory(() => setWindowSize(grown), windowSize, false, background);
return;
}
- loadOlder();
+ loadOlder(background);
}, [isHistoryPaging, loadOlder, preserveHistory, windowSize]);
@@ -384,7 +398,9 @@ export function useTranscriptScroll({
const handleScroll = useCallback(() => {
const el = scrollRef.current;
if (!el) return;
- if (restoreHistoryAnchor()) return;
+ if (latestNavigation.isActive()) { recordScrollPosition(el.scrollTop); return; }
+ if (isHistoryLocked() && restoreHistoryAnchor()) return;
+ trackHistoryPosition();
if (paneVisibleRef.current && transcriptHasLayout(el)) {
lastLaidOutScrollTopRef.current = el.scrollTop;
}
@@ -408,6 +424,9 @@ export function useTranscriptScroll({
isHistoryRevealPosition(el, pinnedRef.current && !gesturing)
) {
reachTop();
+ } else if (paneVisibleRef.current && gesturing && el.scrollTop < lastScrollTopRef.current &&
+ isHistoryPrefetchPosition(el)) {
+ reachTop(true);
}
if (readingWindow) {
pinnedRef.current = false;
@@ -454,7 +473,7 @@ export function useTranscriptScroll({
setShowJump(transition.showJump);
}
rememberReadingPosition();
- }, [cancelFollowScroll, reachTop, readingPositionPendingRef, readingWindow, rememberReadingPosition, restoreHistoryAnchor, scheduleFollowScroll]);
+ }, [cancelFollowScroll, isHistoryLocked, latestNavigation, reachTop, readingPositionPendingRef, readingWindow, recordScrollPosition, rememberReadingPosition, restoreHistoryAnchor, scheduleFollowScroll, trackHistoryPosition]);
// 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.
@@ -464,7 +483,8 @@ export function useTranscriptScroll({
useLayoutEffect(() => {
const turnStarted = isRunning && !wasRunningRef.current;
wasRunningRef.current = isRunning;
- if (!turnStarted || !paneVisible) return;
+ if (!turnStarted || !paneVisible || readingWindow) return;
+ latestNavigation.cancel(true);
cancelHistoryPaging();
cancelReadingPosition();
releaseDisclosureAnchor();
@@ -479,6 +499,8 @@ export function useTranscriptScroll({
cancelHistoryPaging,
cancelReadingPosition,
isRunning,
+ latestNavigation,
+ readingWindow,
paneVisible,
releaseDisclosureAnchor,
rememberReadingPosition,
@@ -489,7 +511,7 @@ export function useTranscriptScroll({
// A completed turn the reader followed ends at its prompt, not its last line.
useTurnCompletionScroll({
isRunning, paneVisible, readingWindow, messages, scrollRef, contentRef,
- isFollowing: () => pinnedRef.current && !isDisclosureAnchorHeld() && !isHistoryPaging(),
+ isFollowing: () => pinnedRef.current && !latestNavigation.isActive() && !isDisclosureAnchorHeld() && !isHistoryPaging(),
onAnchored: leaveFollow,
});
@@ -620,6 +642,7 @@ export function useTranscriptScroll({
);
const releaseSearchFollow = useCallback((fresh: boolean) => {
+ latestNavigation.cancel();
stopSmoothScroll(scrollRef.current);
cancelReadingPosition();
if (fresh) cancelHistoryPaging();
@@ -627,9 +650,10 @@ export function useTranscriptScroll({
cancelFollowScroll();
pinnedRef.current = false;
setShowJump(true);
- }, [cancelFollowScroll, cancelHistoryPaging, cancelReadingPosition, releaseDisclosureAnchor]);
+ }, [cancelFollowScroll, cancelHistoryPaging, cancelReadingPosition, latestNavigation, releaseDisclosureAnchor]);
useTranscriptSearchFocus({
target: searchTarget,
+ suspended: latestNavigation.isActive(),
source: searchTarget
? messages.find((message) => message.id === searchTarget.messageId)?.content ?? ""
: "",
@@ -727,25 +751,22 @@ export function useTranscriptScroll({
});
}, [reachTop, releaseDisclosureAnchor, releaseFollow, retryHistoryPaging]);
- const jumpToLatest = useCallback(() => {
- // Explicit navigation supersedes the gesture that entered history. Its
- // queued scroll events must not start another page during the smooth jump.
+ const jumpToLatest = useCallback((arrive?: () => void) => {
+ // Retire the gesture and all competing owners before yielding any frames.
lastScrollGestureAtRef.current = -Infinity;
cancelReadingPosition();
cancelHistoryPaging();
+ cancelFollowScroll();
releaseDisclosureAnchor();
pinnedRef.current = true;
setShowJump(false);
- // Persist the explicit follow intent before smooth scrolling yields. A
- // session/project switch can hide or unmount this pane before its native
- // scroll event; leaving the old bookmark would restore history on return.
+ // A hide/eviction must still retain the accepted follow intent.
rememberReadingPosition();
- scrollToBottom(
- window.matchMedia("(prefers-reduced-motion: reduce)").matches
- ? "auto"
- : "smooth",
- );
- }, [cancelHistoryPaging, cancelReadingPosition, releaseDisclosureAnchor, rememberReadingPosition, scrollToBottom]);
+ latestNavigation.start(() => {
+ arrive?.();
+ scrollToBottom();
+ });
+ }, [cancelFollowScroll, cancelHistoryPaging, cancelReadingPosition, latestNavigation, releaseDisclosureAnchor, rememberReadingPosition, 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,
diff --git a/apps/desktop/src/hooks/use-transcript-search-focus.ts b/apps/desktop/src/hooks/use-transcript-search-focus.ts
index 759af96c8..308e93a0c 100644
--- a/apps/desktop/src/hooks/use-transcript-search-focus.ts
+++ b/apps/desktop/src/hooks/use-transcript-search-focus.ts
@@ -10,6 +10,7 @@ export function useTranscriptSearchFocus({
target,
source,
visible = true,
+ suspended = false,
scrollRef,
contentRef,
contentVersion,
@@ -18,6 +19,7 @@ export function useTranscriptSearchFocus({
}: {
target: TranscriptSearchTarget | null;
source: string;
+ suspended?: boolean;
visible?: boolean;
scrollRef: RefObject<HTMLDivElement | null>;
contentRef: RefObject<HTMLDivElement | null>;
@@ -30,6 +32,12 @@ export function useTranscriptSearchFocus({
const scroller = scrollRef.current;
const content = contentRef.current;
if (!visible || !target || !scroller || !content) return;
+ if (suspended && position.current.requestId === target.requestId) {
+ // Explicit latest navigation owns the viewport. Keep the range/highlight
+ // data, but do not restart an old alignment after reader interruption.
+ position.current.alignUntil = 0;
+ return;
+ }
return installTranscriptSearchFocus({
target,
source,
@@ -39,7 +47,7 @@ export function useTranscriptSearchFocus({
onNavigate,
onPosition,
});
- }, [contentRef, contentVersion, onNavigate, onPosition, scrollRef, source, target, visible]);
+ }, [contentRef, contentVersion, onNavigate, onPosition, scrollRef, source, suspended, target, visible]);
}
type SearchPosition = { current: { requestId: number; alignUntil: number } };
diff --git a/apps/desktop/src/lib/transcript-latest-navigation.ts b/apps/desktop/src/lib/transcript-latest-navigation.ts
new file mode 100644
index 000000000..722420d3b
--- /dev/null
+++ b/apps/desktop/src/lib/transcript-latest-navigation.ts
@@ -0,0 +1,54 @@
+type Geometry = { scrollTop: number; scrollHeight: number; clientHeight: number };
+type ScrollPort = {
+ geometry: () => Geometry | undefined;
+ move: (top: number) => void;
+ request: (frame: (now: number) => void) => number;
+ cancel: (frame: number) => void;
+ now: () => number;
+ reducedMotion: () => boolean;
+};
+type Navigation = { from: number; startedAt: number; duration: number; lastTop: number; arrive: () => void };
+
+/** One viewport owner for a short, interruptible trip through mounted content. */
+export function createTranscriptLatestNavigation(port: ScrollPort) {
+ let current: Navigation | undefined;
+ let frame = 0;
+ const cancel = (commit = false) => {
+ const previous = current;
+ current = undefined;
+ port.cancel(frame);
+ frame = 0;
+ if (commit) previous?.arrive();
+ };
+ const start = (arrive: () => void = () => {}) => {
+ cancel();
+ const geometry = port.geometry();
+ if (!geometry || geometry.clientHeight <= 0) { arrive(); return; }
+ const target = Math.max(0, geometry.scrollHeight - geometry.clientHeight);
+ const distance = Math.max(0, target - geometry.scrollTop);
+ if (port.reducedMotion() || distance <= 1) { port.move(target); arrive(); return; }
+ const navigation: Navigation = { from: geometry.scrollTop, lastTop: geometry.scrollTop,
+ startedAt: port.now(), duration: Math.min(420, Math.max(180, distance / 30)), arrive };
+ current = navigation;
+ const advance = (now: number) => {
+ frame = 0;
+ if (current !== navigation) return;
+ const box = port.geometry();
+ if (!box || box.clientHeight <= 0) { cancel(true); return; }
+ const bottom = Math.max(0, box.scrollHeight - box.clientHeight);
+ const progress = Math.min(1, Math.max(0, (now - navigation.startedAt) / navigation.duration));
+ const eased = 1 - (1 - progress) ** 3;
+ // Retarget late content growth without reversing the reader's movement.
+ const top = Math.min(bottom, Math.max(navigation.lastTop,
+ navigation.from + (bottom - navigation.from) * eased));
+ navigation.lastTop = top;
+ port.move(top);
+ if (progress === 1) {
+ current = undefined;
+ navigation.arrive();
+ } else frame = port.request(advance);
+ };
+ frame = port.request(advance);
+ };
+ return { start, cancel, isActive: () => current !== undefined };
+}
diff --git a/apps/desktop/src/lib/transcript-scroll.ts b/apps/desktop/src/lib/transcript-scroll.ts
index 93a988fd7..691cd902c 100644
--- a/apps/desktop/src/lib/transcript-scroll.ts
+++ b/apps/desktop/src/lib/transcript-scroll.ts
@@ -53,6 +53,15 @@ export function isHistoryRevealPosition(
return geometry.scrollTop <= HISTORY_REVEAL_THRESHOLD_PX;
}
+/** Ahead-loading is gesture-driven, never a reason to drain history at rest. */
+export function isHistoryPrefetchPosition(
+ geometry: TranscriptScrollerGeometry,
+ pinned = false,
+): boolean {
+ return !pinned && transcriptHasLayout(geometry) &&
+ geometry.scrollTop <= Math.min(2400, Math.max(HISTORY_REVEAL_THRESHOLD_PX, geometry.clientHeight * 3));
+}
+
export type TranscriptScrollInput = {
previousScrollTop: number;
scrollTop: number;
diff --git a/apps/desktop/src/stores/app-state.ts b/apps/desktop/src/stores/app-state.ts
index e5c9730ea..cc3761123 100644
--- a/apps/desktop/src/stores/app-state.ts
+++ b/apps/desktop/src/stores/app-state.ts
@@ -217,6 +217,7 @@ export type AppState = {
restoreTranscriptReading: (sessionId: string, position: TranscriptReadingPosition, signal: AbortSignal) => Promise<boolean>;
loadTranscriptPage: (sessionId: string, direction: "before" | "after") => Promise<void>;
returnToLatestTranscript: (sessionId: string) => void;
+ prepareReturnToLatestTranscript: (sessionId: string) => () => void;
selectSession: (
id: string,
opts?: { record?: boolean } & NavigationOptions,
diff --git a/apps/desktop/src/stores/runtime/transcript-reading-runtime.ts b/apps/desktop/src/stores/runtime/transcript-reading-runtime.ts
index da87c800f..91f01bf02 100644
--- a/apps/desktop/src/stores/runtime/transcript-reading-runtime.ts
+++ b/apps/desktop/src/stores/runtime/transcript-reading-runtime.ts
@@ -21,7 +21,11 @@ type ReadSession = (
) => Promise<{ session: SessionDetail | null }>;
type ReadingActions = Pick<
AppState,
- "navigateTranscript" | "loadTranscriptPage" | "returnToLatestTranscript" | "restoreTranscriptReading"
+ | "navigateTranscript"
+ | "loadTranscriptPage"
+ | "returnToLatestTranscript"
+ | "prepareReturnToLatestTranscript"
+ | "restoreTranscriptReading"
>;
/** Read workflows publish renderer views and never write the runtime/model cache. */
@@ -57,6 +61,20 @@ export function createTranscriptReadingRuntime({ get, set }: StoreAccess, read:
});
}
+ function prepareReturnToLatestTranscript(sessionId: string): () => void {
+ const current = get().transcriptViews[sessionId];
+ if (!current) return () => {};
+ const prepared: TranscriptView = { ...current, loading: null };
+ publish(sessionId, prepared);
+ return () => {
+ set((state) => {
+ if (state.transcriptViews[sessionId] !== prepared) return {};
+ const { [sessionId]: _released, ...transcriptViews } = state.transcriptViews;
+ return { transcriptViews };
+ });
+ };
+ }
+
function reportError(sessionId: string, pending: TranscriptView, error: unknown) {
if (get().transcriptViews[sessionId] !== pending) return;
publish(sessionId, { ...pending, loading: null });
@@ -66,6 +84,7 @@ export function createTranscriptReadingRuntime({ get, set }: StoreAccess, read:
const actions: ReadingActions = {
returnToLatestTranscript,
+ prepareReturnToLatestTranscript,
restoreTranscriptReading: async (sessionId, position, signal) => {
if (signal.aborted || get().activeSessionId !== sessionId || !position.messageId) return false;
const previous = get().transcriptViews[sessionId];
diff --git a/apps/desktop/test/session-switch-performance.test.mjs b/apps/desktop/test/session-switch-performance.test.mjs
index 0e309bde3..6c925c109 100644
--- a/apps/desktop/test/session-switch-performance.test.mjs
+++ b/apps/desktop/test/session-switch-performance.test.mjs
@@ -162,7 +162,7 @@ test("a hidden pane does no reading work off screen", () => {
assert.match(transcript, /if \(!paneVisible\) return;\n\s*let frame = 0;/);
assert.match(
transcript,
- /const loadOlder = useCallback\(\(\) => \{[\s\S]*?if \(!paneVisibleRef\.current\) return;/,
+ /const loadOlder = useCallback\(\(background = false\) => \{[\s\S]*?if \(!paneVisibleRef\.current\) return;/,
);
assert.match(transcript, /\{paneVisible && !veilCovering \? \(\s*<ConversationMinimap/);
});
diff --git a/apps/desktop/test/transcript-disclosure-reading.test.mjs b/apps/desktop/test/transcript-disclosure-reading.test.mjs
index ee84451be..d33004bf7 100644
--- a/apps/desktop/test/transcript-disclosure-reading.test.mjs
+++ b/apps/desktop/test/transcript-disclosure-reading.test.mjs
@@ -104,7 +104,7 @@ test("holding a disclosure leaves follow without a delayed grab-back", () => {
/const leaveFollow = useCallback\(\(\) => \{\s*cancelReadingPosition\(\);\s*cancelFollowScroll\(\);\s*pinnedRef\.current = false;\s*setShowJump\(true\);/,
);
assert.match(transcript,
- /const releaseFollow = useCallback\(\(\) => \{\s*stopSmoothScroll\(scrollRef\.current\);\s*leaveFollow\(\);/);
+ /const releaseFollow = useCallback\(\(\) => \{\s*latestNavigation\.cancel\(\);\s*stopSmoothScroll\(scrollRef\.current\);\s*leaveFollow\(\);/);
assert.match(transcript, /onAnchored: leaveFollow/);
assert.match(
transcript,
@@ -130,7 +130,7 @@ test("real input, a new turn and every navigation drop the held position", () =>
);
assert.match(
transcript,
- /const jumpToLatest = useCallback\(\(\) => \{\s*(?:\/\/[^\n]*\n\s*)*lastScrollGestureAtRef\.current = -Infinity;\s*cancelReadingPosition\(\);\s*cancelHistoryPaging\(\);\s*releaseDisclosureAnchor\(\);\s*pinnedRef\.current = true;/,
+ /const jumpToLatest = useCallback\(\(arrive\?: \(\) => void\) => \{\s*(?:\/\/[^\n]*\n\s*)*lastScrollGestureAtRef\.current = -Infinity;\s*cancelReadingPosition\(\);\s*cancelHistoryPaging\(\);\s*cancelFollowScroll\(\);\s*releaseDisclosureAnchor\(\);\s*pinnedRef\.current = true;/,
);
assert.match(
transcript,
diff --git a/apps/desktop/test/transcript-latest-navigation.test.mjs b/apps/desktop/test/transcript-latest-navigation.test.mjs
new file mode 100644
index 000000000..2c9b283f4
--- /dev/null
+++ b/apps/desktop/test/transcript-latest-navigation.test.mjs
@@ -0,0 +1,88 @@
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { createTranscriptLatestNavigation } = await import("../src/lib/transcript-latest-navigation.ts");
+
+function fixture(reduced = false) {
+ const box = { scrollTop: 80, scrollHeight: 8000, clientHeight: 600 };
+ const frames = new Map();
+ const positions = [];
+ let now = 0;
+ let id = 0;
+ let arrivals = 0;
+ const navigation = createTranscriptLatestNavigation({
+ geometry: () => box,
+ move: top => { box.scrollTop = top; positions.push(top); },
+ request: callback => { frames.set(++id, callback); return id; },
+ cancel: id => frames.delete(id),
+ now: () => now,
+ reducedMotion: () => reduced,
+ });
+ const advance = () => {
+ now += 16;
+ const batch = [...frames.values()];
+ frames.clear();
+ for (const frame of batch) frame(now);
+ };
+ const finish = () => { for (let n = 0; navigation.isActive() && n < 60; n++) advance(); };
+ return { box, navigation, positions, frames, advance, finish,
+ start: () => navigation.start(() => arrivals++), arrivals: () => arrivals };
+}
+
+test("latest moves continuously to bottom before committing the new view", () => {
+ const f = fixture();
+ f.start();
+ assert.equal(f.box.scrollTop, 80);
+ f.advance();
+ assert(f.box.scrollTop > 80 && f.box.scrollTop < 7400);
+ assert.equal(f.arrivals(), 0);
+ f.finish();
+ assert(f.positions.length >= 8);
+ assert(f.positions.every((top, i) => i === 0 || top >= f.positions[i - 1]));
+ assert.equal(f.box.scrollTop, 7400);
+ assert.equal(f.arrivals(), 1);
+ assert.equal(f.frames.size, 0);
+});
+
+test("late stream growth retargets the trip without reversing or losing bottom", () => {
+ const f = fixture();
+ f.start(); f.advance();
+ f.box.scrollHeight += 800;
+ f.finish();
+ assert(f.positions.every((top, i) => i === 0 || top >= f.positions[i - 1]));
+ assert.equal(f.box.scrollTop, 8200);
+ assert.equal(f.arrivals(), 1);
+});
+
+test("reader interruption retires every queued frame without committing latest", () => {
+ const f = fixture();
+ f.start(); f.advance();
+ const top = f.box.scrollTop;
+ f.navigation.cancel(); f.advance();
+ assert.equal(f.box.scrollTop, top);
+ assert.equal(f.arrivals(), 0);
+ assert.equal(f.navigation.isActive(), false);
+ assert.equal(f.frames.size, 0);
+});
+
+test("pane hide commits accepted latest intent once without finishing an invisible animation", () => {
+ const f = fixture();
+ f.start(); f.advance(); f.navigation.cancel(true); f.navigation.cancel(true); f.advance();
+ assert.equal(f.arrivals(), 1);
+ assert.equal(f.frames.size, 0);
+});
+
+test("repeated navigation cannot commit an obsolete trip", () => {
+ const f = fixture();
+ f.start(); f.advance(); f.start(); f.finish();
+ assert.equal(f.arrivals(), 1);
+});
+
+test("reduced motion reaches bottom synchronously", () => {
+ const f = fixture(true);
+ f.start();
+ assert.equal(f.box.scrollTop, 7400);
+ assert.equal(f.arrivals(), 1);
+ assert.equal(f.frames.size, 0);
+});
diff --git a/apps/desktop/test/transcript-reading.test.mjs b/apps/desktop/test/transcript-reading.test.mjs
index bb9926e5f..4d9c7bd74 100644
--- a/apps/desktop/test/transcript-reading.test.mjs
+++ b/apps/desktop/test/transcript-reading.test.mjs
@@ -674,3 +674,133 @@ test("a saved anchor does not supersede in-flight navigation when both rows are
assert.equal(await r.restoreTranscriptReading("s", bookmark, new AbortController().signal), false);
assert.equal(r.view(), focused, "explicit navigation keeps ownership of the reading view");
});
+
+test("prepareReturnToLatestTranscript invalidates pending read while keeping messages visible until completion", async () => {
+ const pendingPage = deferred();
+ const r = reader(() => pendingPage.promise, {
+ transcriptViews: {
+ s: {
+ messages: [message("hist-1"), message("hist-2")],
+ messageStart: 20,
+ messageEnd: 40,
+ hasMoreBefore: true,
+ hasMoreAfter: true,
+ focus: null,
+ restored: true,
+ loading: null,
+ },
+ },
+ });
+ assert.equal(r.view().loading, null);
+ assert.deepEqual(
+ r.visible().map((m) => m.id),
+ ["hist-1", "hist-2"],
+ );
+
+ const load = r.loadTranscriptPage("s", "before");
+ assert.equal(r.view().loading, "before");
+
+ const complete = r.prepareReturnToLatestTranscript("s");
+ assert.equal(r.view().loading, null, "loading cleared synchronously");
+ assert.deepEqual(
+ r.visible().map((m) => m.id),
+ ["hist-1", "hist-2"],
+ "messages stay visible",
+ );
+ assert.equal(r.view().restored, true);
+ assert.equal(r.view().hasMoreBefore, true);
+
+ pendingPage.resolve(page([message("stale-page")]));
+ await load;
+
+ assert.deepEqual(
+ r.visible().map((m) => m.id),
+ ["hist-1", "hist-2"],
+ "pending read stale completion ignored",
+ );
+ assert.equal(r.view().loading, null);
+
+ complete();
+ assert.equal(r.view(), undefined, "completion clears prepared view");
+ assert.deepEqual(
+ r.visible().map((m) => m.id),
+ ["tail"],
+ );
+});
+
+test("subsequent navigation survives stale completion from prepareReturnToLatestTranscript", async () => {
+ const r = reader(async () => page([message("search-hit")]), {
+ transcriptViews: {
+ s: {
+ messages: [message("hist-1")],
+ messageStart: 20,
+ messageEnd: 40,
+ hasMoreBefore: true,
+ hasMoreAfter: true,
+ focus: null,
+ loading: null,
+ },
+ },
+ });
+ const complete = r.prepareReturnToLatestTranscript("s");
+ assert.notEqual(r.view(), undefined);
+
+ await r.navigateTranscript(target("search-hit"));
+ assert.deepEqual(
+ r.visible().map((m) => m.id),
+ ["search-hit"],
+ );
+ assert.equal(r.view().focus.messageId, "search-hit");
+
+ complete();
+ assert.deepEqual(
+ r.visible().map((m) => m.id),
+ ["search-hit"],
+ "navigation view survived stale completion",
+ );
+ assert.equal(r.view().focus.messageId, "search-hit");
+});
+
+test("repeated preparation retires previous completion closure", () => {
+ const r = reader(async () => page([]), {
+ transcriptViews: {
+ s: {
+ messages: [message("hist-1")],
+ messageStart: 20,
+ messageEnd: 40,
+ hasMoreBefore: true,
+ hasMoreAfter: true,
+ focus: null,
+ loading: null,
+ },
+ },
+ });
+ const complete1 = r.prepareReturnToLatestTranscript("s");
+ const view1 = r.view();
+ const complete2 = r.prepareReturnToLatestTranscript("s");
+ const view2 = r.view();
+
+ assert.notEqual(view1, view2, "view identity replaced on each preparation");
+
+ complete1();
+ assert.equal(r.view(), view2, "previous completion is retired");
+
+ complete2();
+ assert.equal(r.view(), undefined, "current completion clears prepared view");
+});
+
+test("prepareReturnToLatestTranscript is a no-op when no historical view exists", () => {
+ const r = reader(async () => page([]));
+ assert.equal(r.view(), undefined);
+
+ const complete = r.prepareReturnToLatestTranscript("s");
+ assert.equal(typeof complete, "function");
+ assert.equal(r.view(), undefined, "did not create a transcript view");
+
+ complete();
+ assert.equal(r.view(), undefined, "completion is a no-op");
+ assert.deepEqual(
+ r.visible().map((m) => m.id),
+ ["tail"],
+ );
+});
diff --git a/apps/desktop/test/transcript-scroll.test.mjs b/apps/desktop/test/transcript-scroll.test.mjs
index ddb41246e..96bda49a5 100644
--- a/apps/desktop/test/transcript-scroll.test.mjs
+++ b/apps/desktop/test/transcript-scroll.test.mjs
@@ -5,6 +5,7 @@ import {
TRANSCRIPT_REPIN_THRESHOLD_PX,
TRANSCRIPT_SCROLL_GESTURE_WINDOW_MS,
isHistoryRevealPosition,
+ isHistoryPrefetchPosition,
isRecentScrollGesture,
reduceTranscriptScroll,
transcriptHasLayout,
@@ -208,3 +209,12 @@ test("a pinned overflowing transcript is suppressed anywhere in the band", () =>
false,
);
});
+
+test("history prefetch begins within three viewports but stays bounded", () => {
+ const box = { scrollTop: 1600, scrollHeight: 10000, clientHeight: 800 };
+ assert.equal(isHistoryPrefetchPosition(box), true);
+ assert.equal(isHistoryPrefetchPosition({ ...box, scrollTop: 2401 }), false);
+ assert.equal(isHistoryPrefetchPosition({ ...box, clientHeight: 2000, scrollTop: 2401 }), false);
+ assert.equal(isHistoryPrefetchPosition(box, true), false);
+ assert.equal(isHistoryPrefetchPosition({ ...box, clientHeight: 0 }), false);
+});
diff --git a/apps/desktop/test/transcript-window.test.mjs b/apps/desktop/test/transcript-window.test.mjs
index 66fcd0be8..07616805a 100644
--- a/apps/desktop/test/transcript-window.test.mjs
+++ b/apps/desktop/test/transcript-window.test.mjs
@@ -213,19 +213,19 @@ test("the transcript bounds mounted history and escalates at the top", () => {
/isHistoryRevealPosition\(el, pinnedRef\.current && !gesturing\)/,
);
const reachTop = transcript.match(
- /const reachTop = useCallback\(\(\) => \{([\s\S]*?)\n \}, \[[^\]]*\]\);/,
+ /const reachTop = useCallback\(\(background = false\) => \{([\s\S]*?)\n \}, \[[^\]]*\]\);/,
)?.[1];
assert.ok(reachTop, "reachTop must exist with a stable identity");
assert.match(reachTop, /growTranscriptWindow\(windowSize, historyLengthRef\.current\)/);
- assert.match(reachTop, /preserveHistory\(\(\) => setWindowSize\(grown\), windowSize\)/);
+ assert.match(reachTop, /preserveHistory\(\(\) => setWindowSize\(grown\), windowSize, false, background\)/);
assert.match(reachTop, /setWindowSize\(grown\)/);
- assert.match(reachTop, /loadOlder\(\)/);
+ assert.match(reachTop, /loadOlder\(background\)/);
});
test("mounting rows above the viewport is anchored like a fetched page", () => {
// Both transitions use one viewport owner; the real DOM/native-wheel
// behavior is exercised by e2e-transcript-history-loading.mjs.
- assert.match(transcript, /preserveHistory\(onLoadOlder, windowSize, true\)/);
+ assert.match(transcript, /preserveHistory\(onLoadOlder, windowSize, true, background\)/);
assert.match(transcript, /useTranscriptHistoryPaging\(\{/);
assert.doesNotMatch(transcript, /prependHeightRef|el\.scrollTop \+= delta/);
});
diff --git a/docs/adr/0130-bounded-mounted-transcript-window.md b/docs/adr/0130-bounded-mounted-transcript-window.md
index cafdef617..a4f5b8f12 100644
--- a/docs/adr/0130-bounded-mounted-transcript-window.md
+++ b/docs/adr/0130-bounded-mounted-transcript-window.md
@@ -45,16 +45,18 @@ reference-equal, and that runs on every streamed token.
window covers all loaded history does the transcript call `loadOlder` and
fetch an older page. Mounting what is already loaded is strictly cheaper than
an IPC round trip, so it goes first.
-3. Window growth and a fetched page take the **same pre-paint scroll anchor**.
- The pane-local history paging hook captures the visible message's viewport
- offset for both. It holds input during the transaction and restores that
- anchor before paint, through committed projection and late row layout.
- Reading bookmarks prefer a visible message node to an answer-group marker;
- prepending the earlier half of an answer can replace the group's first id.
- Explicit latest navigation clears the preceding gesture as well as the hold,
- so queued near-top scroll events cannot initiate another history transaction.
+3. Window growth and a fetched page take the **same pre-paint message anchor**.
+ The pane-local history paging hook captures the actual visible message's
+ viewport offset (preferring a message node over an answer-group marker whose
+ first id can change on prepend) and restores it before paint across committed
+ projection and late row layout. Ahead-loading during upward scroll tracks the
+ newest visible message anchor without hiding overflow or discarding input;
+ only the hard-edge (`<= 120px`), explicit continuation, and underfilled
+ top-boundary fallback briefly locks transcript scroll input and `overflow-y`
+ through IO and three stable layout frames. Explicit latest navigation retires
+ the prior gesture and hold so queued scroll events cannot start another read.
This replaces the old `prependHeightRef` total-height delta: deferred DOM,
- tail updates and intrinsic-size estimates made that delta unreliable.
+ tail updates, and intrinsic-size estimates made that delta unreliable.
4. The window **resets per session** and is clamped to the loaded history, so a
grown budget inherited from the previous session for one frame cannot
over-mount.
@@ -72,12 +74,13 @@ reference-equal, and that runs on every streamed token.
than two message markers or does not overflow one viewport. The continuation
runs the same two-stage escalation as clause 2, so it is always actionable;
D108's two-marker-plus-overflow rule resumes once no earlier history remains.
-6b. **Amended by D269.** Escalation is driven by the visibility of the
- transcript's top loading boundary as well as by the near-top scroll check,
- using one shared threshold. An underfilled tail page, a fetched page whose rows
- all fall outside the mounted window, and a window transition can each leave
- `scrollTop` unchanged; without an observed boundary those states stalled
- upward travel and left the outline hidden.
+6b. **Amended by D269.** Hard-edge escalation is driven by the visibility of the
+ transcript's top loading boundary as well as by the `120px` near-top check;
+ there is no early-threshold observer and no eager page draining at rest. An
+ underfilled tail page, a fetched page whose rows all fall outside the mounted
+ window, and a window transition can each leave `scrollTop` unchanged; without
+ that `120px` observed boundary those states stalled upward travel and left
+ the outline hidden.
7. The entry projection arrays are memoized on `entries`, so a re-render that
changed no message hands `TranscriptHistory` a reference-equal array and its
comparator bails on identity instead of deep-walking the mounted rows.
@@ -125,3 +128,36 @@ and the `session.get` window contract are untouched.
before their real size is known, so the scrollbar thumb settles as they enter
view. This is the pre-existing `content-visibility` behavior, unchanged in kind
by windowing.
+
+## Implementation notes
+
+- **Gesture-driven ahead-loading vs. hard-edge lock:** A real upward scroll
+ gesture within `min(2400px, max(120px, 3 * clientHeight))` starts single-flight
+ escalation in the background, still mounting cached withheld rows before
+ requesting a Host page. Background escalation leaves `overflow-y` and main
+ scroll input unlocked, updates its actual-message reading anchor as the user
+ continues scrolling, and subtracts observed scroll displacement from its
+ viewport offset before correcting geometry changes. This preserves compositor
+ movement even when lazy rows lay out before their scroll event. Reaching `<= 120px`,
+ invoking the earlier-history continuation, or intersecting the `120px` top
+ boundary retains the brief input/`overflow-y: hidden` lock through IO and
+ three consecutive stable layout frames. Failed or empty reads release any lock
+ and wait for a new scroll gesture or explicit earlier-history action.
+- **Interruptible return-to-latest:** Returning to latest uses one custom
+ viewport animation (`180–420ms` cubic ease-out, monotonic retargeting across
+ late stream growth; immediate under `prefers-reduced-motion: reduce`) instead
+ of browser smooth scroll, suppressing competing follow, layout, previous
+ search-alignment, and turn-completion scroll owners while active. A new search
+ request still cancels the trip. Genuine main-scroller input
+ cancels the animation in place without committing arrival; horizontal,
+ zero-delta, or `Ctrl`+wheel input and nested scrollers, editable fields, or
+ row controls do not. Preparing return-to-latest from a historical
+ `transcriptViews` slice replaces its identity with `loading: null` while
+ keeping current messages mounted, clears that exact prepared view only on
+ arrival, and commits on pane hide or unmount; disjoint search/history ranges
+ join the canonical live tail on arrival without fetching or animating unloaded
+ intermediate ranges. Runtime `isRunning` state passed to scroll hooks stays
+ real rather than faked stopped by a historical view.
+- **Cache invariants:** Existing message, page, mounted-window, recent snapshot,
+ and retained session-pane caches are unchanged; no idle TTL or memory
+ reclamation is introduced.
diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.md
index 093e787b9..e5e08f006 100644
--- a/docs/spec/04-ux/09-interaction-patterns.md
+++ b/docs/spec/04-ux/09-interaction-patterns.md
@@ -819,26 +819,38 @@ may be retained while exactly one workspace supplies the visible shell context.
- The first upward manual scroll movement pauses auto-scroll immediately and
cancels any pending follow frame; small trackpad deltas must not snap back to
the bottom
-- Scroll input owned by the transcript also cancels an in-flight browser smooth
- navigation at its current offset. A previous minimap or jump navigation must
- not resume after the reader takes over; nested-scroll input and ordinary row
- controls do not cancel the transcript's navigation.
+- Scroll input owned by the transcript cancels an in-flight browser smooth
+ navigation or custom return-to-latest animation at its current offset. A
+ previous minimap or return-to-latest move must not resume after the reader
+ takes over; horizontal, zero-delta, or `Ctrl`+wheel input, nested-scroll
+ input, editable fields, and ordinary row controls do not cancel it.
Space on a button activates that button, and selection keys inside a select
belong to the select. The same ownership and cancellation rules apply to
delegated transcript scrollers. Releasing follow after a completed turn's
prompt navigation does not cancel that newly started navigation.
- A manual disclosure or history navigation also cancels the prior browser
- navigation before taking ownership; completion's state-only follow release
- is separate from these reader-driven moves.
+ A manual disclosure or search/history navigation also cancels any active
+ return-to-latest or browser smooth navigation before taking ownership;
+ completion's state-only follow release is separate from these reader-driven moves.
- Sending a new prompt, retrying, or regenerating always re-pins follow mode and jumps to the bottom before the turn continues, even if the user had scrolled up
- "Scroll to bottom" floating button appears as soon as manual upward scrolling
releases follow mode
-- Click "Scroll to bottom" button: resumes auto-scroll and snaps to bottom.
- Record the pinned bookmark synchronously, before any smooth-scroll event:
- immediately switching sessions or projects must preserve this follow intent
- even if the original pane is hidden or unmounted before scrolling finishes.
- Returning follows the latest output rather than restoring the old reading
- offset. Manual upward reading without that click still retains its position.
+- Return-to-latest ("Scroll to bottom" button, context menu, radial menu) runs
+ one custom interruptible viewport animation (`180–420ms` cubic ease-out,
+ monotonic retargeting across late stream growth without reversing; immediate
+ when `prefers-reduced-motion: reduce` is active) instead of browser smooth
+ scroll, suppressing competing follow, layout, previous search alignment, and turn-completion scroll
+ owners until it settles or is cancelled. Record the pinned bookmark
+ synchronously and prepare any active historical `transcriptViews` slice by
+ replacing its identity with `loading: null` while keeping visible messages
+ mounted; only that exact prepared view's arrival closure clears the historical
+ view, while pane hide or unmount commits the accepted latest intent once
+ without continuing an invisible animation. Explicit disjoint search or history
+ views animate across currently mounted rows and join the canonical live tail
+ on arrival without fetching or animating unloaded intermediate ranges.
+ Returning to a switched session follows the latest output rather than
+ restoring the old reading offset; manual upward reading without return-to-latest
+ retains its position, and reader interruption cancels the animation in place
+ without committing arrival.
- Stream completion (D676): if the user was following a turn that completes,
its prompt scrolls to 16px below the titlebar band at the top of the
viewport so the answer reads from its start, follow mode is released, and
@@ -867,12 +879,15 @@ may be retained while exactly one workspace supplies the visible shell context.
transitions to preserve.
- A restored reading range that has reached the canonical live tail presents
the session's running phase, elapsed time, and interaction waits normally.
- Keeping its reading bookmark does not mean the turn has finished. Rejoining
- live output preserves the viewport rather than acting like a new turn.
- Explicit search, unread later pages, and disjoint snapshots remain historical.
- Reading ranges require a non-empty canonical message identity, compared by
- message id across history object copies. The ordinary canonical surface still
- shows the first-event wait before its first message arrives.
+ Runtime `isRunning` state remains real rather than being faked stopped by a
+ historical reading view; keeping a reading bookmark does not mean the turn has
+ finished, and `turnStarted` re-pin skips an active historical reading window
+ so rejoining live output or browsing history preserves the viewport rather
+ than acting like a new turn. Explicit search, unread later pages, and disjoint
+ snapshots remain historical. Reading ranges require a non-empty canonical
+ message identity, compared by message id across history object copies. The
+ ordinary canonical surface still shows the first-event wait before its first
+ message arrives.
### 2.5 Turn outcome closure
@@ -1611,23 +1626,33 @@ Project drag/drop follows these patterns:
### 9.1 Transcript scrolling
- Default: auto-scroll to bottom on new content during stream while pinned
-- Loading earlier messages is one pane-local viewport transaction: capture the
- visible message and its viewport offset before either mounting more cached
- rows or requesting a page. Keep that anchor through the committed projection
- and late row layout; total scroll-height growth is not an anchor because it
- can include tail updates and offscreen intrinsic-size estimates. Prefer the
- actual visible message node over its enclosing answer/minimap group: loading
- the preceding part of a continuous answer can change the group's identity.
-- While that transaction owns the viewport, discard wheel/trackpad, touch-scroll
- and scrolling-key input addressed to the transcript. Do not queue input for
- replay after loading. Nested scroll owners, editable fields, title activation
- and Ctrl+wheel zoom retain their own input. The loading label keeps identical
- layout space when hidden, and ordinary scrolling resumes after settlement.
-- Search/minimap navigation, return-to-latest, manual disclosure, a new turn,
- pane hide and unmount retire the hold. A late page cannot reclaim that
- navigation. A failed or empty page releases input and does not auto-retry at
- the unchanged boundary; a new reader gesture or earlier-history action may
- retry. Requests remain single-flight even after their viewport hold ends.
+- Loading earlier messages uses two-stage single-flight escalation — mounting
+ cached withheld rows before requesting a Host page — anchored to the actual
+ visible message node and its viewport offset rather than total scroll-height
+ growth or an enclosing answer/minimap group whose first id can change when
+ earlier fragments prepend. Existing message, page, mounted-window, snapshot,
+ and retained session-pane caches remain unchanged, with no idle TTL or memory
+ reclamation.
+- A real upward scroll gesture within `min(2400px, max(120px, 3 * clientHeight))`
+ starts background ahead-loading: it mounts cached history before Host IO,
+ stays single-flight, leaves `overflow-y` and transcript scroll input unlocked,
+ tracks the reader's newest visible message anchor across ongoing scroll
+ movement, and restores that anchor before paint only when prepended rows or
+ layout measurements change geometry or the head message.
+- Reaching the `<= 120px` hard edge, activating the earlier-history continuation,
+ or intersecting the underfilled `120px` top boundary retains the brief
+ `overflow-y: hidden` and transcript scroll-input lock through IO and three
+ consecutive stable layout frames, discarding (never queueing) main-scroller
+ vertical wheel/trackpad, touch-scroll, and scrolling-key input until
+ settlement. Horizontal, zero-delta, and `Ctrl`+wheel input, nested scroll
+ owners, editable fields, and title activation retain their own input. The
+ loading label keeps identical layout space when hidden, and there is no
+ early-threshold observer or eager page draining at rest.
+- Search/minimap navigation, return-to-latest, manual disclosure, a new turn
+ outside a historical reading window, pane hide, and unmount retire the hold;
+ a late page cannot reclaim that navigation. A failed or empty page releases
+ any lock and waits for a new scroll gesture or explicit earlier-history action
+ before retrying. Requests remain single-flight even after their hold ends.
- The first upward scroll **gesture** (wheel / trackpad / touch / scrollbar /
keyboard) pauses auto-scroll and shows the "↓ Scroll to bottom" button;
queued stream or resize follow work must not reverse that movement
@@ -1663,9 +1688,12 @@ Project drag/drop follows these patterns:
- User send / retry / regenerate: re-pins, hides the jump control, and positions the latest content in the layout phase so the new turn is visible without a top-of-history flash; subsequent persisted and streamed rows continue to follow the bottom
- Scroll-to-bottom button: position fixed at bottom-right of transcript area, offset 12px
- Button appears as soon as upward scrolling releases follow mode
-- Click button: scrolls to bottom, resumes auto-scroll and retires the prior
- scroll gesture before navigation. Queued scroll events or a pending page must
- not reopen historical reading or fetch another page during that jump.
+- Click button: retires the prior scroll gesture and history hold, prepares any
+ historical view without removing visible messages until arrival (or commits on
+ hide/unmount), and drives the custom `180–420ms` cubic ease-out animation to
+ bottom (immediate under reduced motion) while suppressing competing scroll
+ owners. Queued scroll events or a pending page cannot reopen historical
+ reading or start another page read during that trip.
- Button disappears when at bottom
- A delegation tab uses the same single-body scroll owner as the work panel.
It renders the delegate's conversation — each `Task` call's prompt as a user
@@ -1854,8 +1882,10 @@ This does not prevent state changes — it makes them instant.
- Session activation uses an immediate layout-phase bottom position so the
first visible frame is already stable at the latest record.
-- Jump-to-latest and minimap navigation use smooth scrolling only when the OS
- has not requested reduced motion.
+- Return-to-latest runs its `180–420ms` cubic ease-out viewport animation and
+ minimap navigation uses browser smooth scrolling only when the OS has not
+ requested reduced motion; under `prefers-reduced-motion: reduce` both position
+ immediately.
- Turn-start following uses an immediate layout-phase update and then a
frame-coalesced instant follow; it does not start overlapping smooth-scroll
animations for token groups.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 7305a8911..8184fc154 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -2368,9 +2368,9 @@ identify the platform validation still needed.
output; switch away and reveal the running pane; inspect an unread history
range and an explicit search at the tail; settle and abort the turn. While
reading above the live tail, click return-to-latest and switch away in the
- same task, before a native smooth-scroll event. Return first with the pane
- retained, then repeat while a project switch actually unmounts the pane and
- output continues in the background.
+ same task, before the return-to-latest animation advances a frame. Return
+ first with the pane retained, then repeat while a project switch actually
+ unmounts the pane and output continues in the background.
- **Expected**: The restored live tail keeps a running process header while
Stop is available. Content updates and pane reveal do not falsely show
Finished. The restored range and scroll offset remain owned by the reader.
@@ -2379,10 +2379,11 @@ identify the platform validation still needed.
An empty restored range stays historical, an ordinary empty canonical range
shows the initial wait, and a restored navigation-parent copy with the same
message id keeps the running presentation.
- Return-to-latest synchronously records a pinned bookmark; both a retained
- reveal and a fresh project remount follow the newest output without a second
- click. The running header and Stop control stay consistent. Readers who did
- not choose return-to-latest keep their existing historical reading position.
+ Return-to-latest synchronously records a pinned bookmark and commits any
+ prepared latest view on hide or unmount; both a retained reveal and a fresh
+ project remount follow the newest output without a second click. The running
+ header and Stop control stay consistent. Readers who did not choose
+ return-to-latest keep their existing historical reading position.
- **Automation**: `node scripts/e2e-transcript-reading-position.mjs`
(`transcriptLiveTailProbe`).
- **Specs linked**: `04-ux/09-interaction-patterns.md` §2.3 / §2.4
@@ -13516,35 +13517,60 @@ This test plan spec is accepted when:
- **Preconditions**: A built Desktop checkout and existing compatible Electron
dependencies. Use the isolated synthetic fixture, never a live user profile.
- **Steps**:
- 1. Start `node scripts/e2e-transcript-history-loading.mjs --manual` and click
- **Load earlier (hold)**. Note the visible turn and its viewport offset.
- 2. Continuously roll the wheel upward, then downward while the page is held.
- Click **Complete page**. Repeat without scrolling during the held interval.
- 3. Repeat with **Fail page**. Confirm the indicator ends and new input can
- scroll or retry, without an automatic loop at the unchanged boundary.
- 4. While loading, return to latest; complete the old page and confirm it does
- not pull the viewport back. Verify nested scrolling, editable keys, title
- activation and zoom still belong to their original controls.
-- **Expected**: The visible message remains at its viewport offset during
- loading, committed projection, delayed row measurements and label removal.
- Transcript-directed wheel/touch/scroll-key input is discarded, not queued;
- ordinary scrolling resumes on settlement. Page IO remains single-flight;
- explicit navigation, hide and unmount release the hold and restore styles.
+ 1. Scroll upward into the ahead-loading band (`min(2400px, max(120px, 3 *
+ clientHeight))`, above the `120px` hard edge) while holding Host page IO;
+ continue scrolling upward during IO, then complete the page.
+ 2. Start `node scripts/e2e-transcript-history-loading.mjs --manual` and click
+ **Load earlier (hold)** (or reach `<= 120px`). Note the visible turn and
+ its viewport offset, continuously roll the wheel upward and downward while
+ the page is held, then click **Complete page**. Repeat without scrolling.
+ 3. Repeat with **Fail page** and an empty page. Confirm the indicator ends and
+ new input can scroll or retry, without an automatic loop at rest.
+ 4. From both an ordinary tail and a paginated historical view (idle and
+ running), trigger return-to-latest with normal and reduced motion, and
+ interrupt an active trip with genuine main-scroller input vs horizontal,
+ zero-delta, or `Ctrl`+wheel input and nested/editable/row controls. While a
+ page is pending, return to latest, complete the old page, and also test
+ hiding/unmounting mid-trip.
+- **Expected**: Ahead-loading mounts cached withheld history before Host IO,
+ stays single-flight, does not set `overflow-y: hidden` or discard main scroll
+ input, tracks the newest actual message anchor across ongoing upward movement,
+ and keeps that message within `2px` when the page prepends; there is no
+ early-threshold observer or eager draining at rest. Only the `<= 120px` hard
+ edge, explicit earlier-history action, and underfilled `120px` observer briefly
+ lock `overflow-y` and discard main-scroller vertical wheel/touch/scroll-key
+ input through IO and three stable layout frames while preserving horizontal,
+ zero-delta, and `Ctrl`+wheel input, nested scrolling, editable fields, and
+ title activation. Return-to-latest runs one `180–420ms` cubic ease-out
+ viewport animation (immediate under reduced motion) while suppressing
+ competing follow/layout/turn-completion owners; preparing a historical view
+ clears `loading` on a new view identity while keeping current messages visible
+ until exact-identity arrival, commits on hide/unmount, cancels in place only
+ on genuine main-scroller input, and may skip unloaded intermediate ranges when
+ a disjoint search/history view joins the live tail. Runtime `isRunning` stays
+ real, and existing message/page/mounted-window/retained-pane caches remain
+ unchanged without idle TTL or memory reclamation.
- **Automation**: `node scripts/e2e-transcript-history-loading.mjs`, also run by
- `e2e-transcript-render.mjs`. Production React and styles, native Electron wheel
- bursts, per-frame anchor samples with 2 CSS-pixel rounding tolerance, tail
- updates, delayed row geometry, rejection, hide/reveal and latest navigation.
- The production `SessionPane` and real store path additionally paginate a small
- tail across continuous assistant-answer boundaries, sample actual message
- positions, and click the real latest button during/after Host reads for both
- standalone rows and grouped answers. Only external Host IPC is controlled.
- Run with normal animation; do not force reduced motion to hide smooth-scroll
- races. Assert latest navigation stays at bottom without opening another page.
- Manual procedures: `tests/history-loading-scroll-test-cases.md`.
-- **Specs linked**: `04-ux/09-interaction-patterns.md` §9.1, ADR 0130.
+ `e2e-transcript-render.mjs`, plus `transcript-latest-navigation.test.mjs`,
+ `transcript-reading.test.mjs`, and `transcript-scroll.test.mjs`. The direct
+ fixture retains hard-edge native Electron wheel bursts, quiet loading, tail
+ updates, six delayed layout changes, rejection, empty pages, cached-window
+ growth, hide/reveal, input ownership, return-to-latest during IO, and native
+ wheel movement during unlocked ahead-loading. The `SessionPane` + real store
+ probe (`scripts/e2e/transcript-history-navigation.tsx`) adds four paired
+ return-to-latest motion cases (ordinary tail vs paginated history × idle vs
+ running, asserting `>= 3` intermediate frames, no reverse `> 2px`, and zero
+ empty visible-message frames) and ahead-read cases (standalone user rows and
+ mixed grouped answers moving the same visible message `100px` during pending
+ IO and keeping drift `<= 2px` after prepend) alongside the retained quiet
+ stability and pending/settled latest-button cases. Only external Host IPC is
+ controlled; run with normal motion enabled. Manual procedures:
+ `tests/history-loading-scroll-test-cases.md`.
+- **Specs linked**: `04-ux/09-interaction-patterns.md` §2.2 / §9.1 / §10.4, ADR 0130.
- **Acceptance**: C (conversation), Quality.
-- **Status**: Isolated Windows Electron regression covered; other OS/hardware
- combinations and the user's existing conversations require manual validation.
+- **Status**: Automated Electron fixture and unit regressions implemented; run
+ the candidate Electron gate per `AGENTS.md` §16 before landing, and validate
+ additional OS/hardware combinations and real conversations manually.
#### E2E-160: Dragging the window across displays keeps the dropped position
diff --git a/scripts/README.md b/scripts/README.md
index a382349fb..3ce18d7e1 100644
--- a/scripts/README.md
+++ b/scripts/README.md
@@ -62,7 +62,7 @@ The scenarios are specified in
| `e2e-provider-recovery.mjs` | `node scripts/e2e-provider-recovery.mjs` | Isolated desktop with a localhost fault-injection provider: socket failures, interrupted streams, Responses recovery, exhausted retries, Continue, and recovery across eleven real Read calls. Requires a built desktop/runtime and host binary (`PI_DESKTOP_HOST_BIN` when outside the checkout); retains screenshots and JSON under `.artifacts/issue-699/` |
| `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 with controlled slow paging, native wheel input, per-frame reading-anchor checks and error/navigation recovery; included by the transcript render suite. `--manual` opens a disposable synthetic conversation with page-complete/fail controls; see [manual cases](../tests/history-loading-scroll-test-cases.md) |
+| `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), hard-edge input-lock 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 synthetic conversation with page-complete/fail controls; see [manual cases](../tests/history-loading-scroll-test-cases.md) |
| `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 |
| `e2e-config-sync-multidevice.mjs` | `pnpm test:e2e:config-sync` | Four isolated host-core processes against a SigV4-validating local S3 fixture; covers credential opt-out, approvals, concurrent edits/conflict resolution, mapped skill resources, deletion, sync/backup restore, restart, password rewrap, encrypted storage and cleanup |
diff --git a/scripts/e2e-transcript-history-loading.mjs b/scripts/e2e-transcript-history-loading.mjs
index 56ab5bead..cd2eda2a0 100644
--- a/scripts/e2e-transcript-history-loading.mjs
+++ b/scripts/e2e-transcript-history-loading.mjs
@@ -74,6 +74,22 @@ app.whenReady().then(async () => {
const free = await call('inspect()');
assert(Math.abs(free.top - after.top) > 2 || free.calls > after.calls, name + ': scrolling/retry remained locked after completion');
}
+ await call('reset()');
+ await call('beginAhead()');
+ await call('frames()');
+ const ahead = await call('inspect()');
+ assert.equal(ahead.locked, false, 'ahead-loading blocked main input');
+ await call('armNativeInput()');
+ await wheel(ahead, 180);
+ const moved = await call('finishNativeInput()');
+ console.log('HISTORY_AHEAD_INPUT ' + JSON.stringify({ ahead, moved }));
+ assert(moved.offset > ahead.offset + 20, 'native wheel could not move text while ahead-loading');
+ assert.equal(moved.calls, 1, 'native wheel duplicated the pending read');
+ await call('track()');
+ const aheadAfter = await call('release(false,true)');
+ assert(aheadAfter.maxDrift <= 2, 'ahead-loaded prepend moved the new reading point');
+ assert.equal(aheadAfter.locked, false, 'ahead-loading left input blocked');
+ console.log('HISTORY_AHEAD_NATIVE ' + JSON.stringify({ ahead, moved, after: aheadAfter }));
await call('reset()'); await call('begin()'); await call('release()');
const cached = await call('growMountedWindow()');
assert(cached.after.maxDrift <= 2 && Math.abs(cached.after.offset - cached.before.offset) <= 2,
@@ -87,6 +103,14 @@ app.whenReady().then(async () => {
assert(Math.abs(navigation.distanceFromBottom) <= 2, 'late page stole explicit latest navigation');
const realNavigation = await js('globalThis.transcriptHistoryNavigationProbe()');
console.log('REAL_HISTORY_NAVIGATION_PROBE ' + JSON.stringify(realNavigation));
+ win.webContents.debugger.attach('1.3');
+ try {
+ await win.webContents.debugger.sendCommand('Emulation.setEmulatedMedia', {
+ features: [{ name: 'prefers-reduced-motion', value: 'reduce' }],
+ });
+ const reduced = await js('globalThis.transcriptHistoryNavigationProbe(true)');
+ console.log('LATEST_REDUCED_MOTION ' + JSON.stringify(reduced));
+ } finally { win.webContents.debugger.detach(); }
console.log('HISTORY_LOADING_PROBE ' + JSON.stringify({ ok: true, cases: results.length, cachedWindow: true, inputOwnership: true, latestNavigation: true }));
app.exit(0);
} catch(e) { console.error(e.stack || String(e)); app.exit(1); }
diff --git a/scripts/e2e/transcript-history-loading.tsx b/scripts/e2e/transcript-history-loading.tsx
index 150b36131..87b62d33b 100644
--- a/scripts/e2e/transcript-history-loading.tsx
+++ b/scripts/e2e/transcript-history-loading.tsx
@@ -36,6 +36,15 @@ let baseline = 0;
let samples: number[] = [];
let sampling = 0;
let scenario = 0;
+let nativeInputEnded = false;
+function armNativeInput() {
+ nativeInputEnded = false;
+ scroller().addEventListener("scrollend", () => { nativeInputEnded = true; }, { once: true });
+}
+async function finishNativeInput() {
+ await until(() => nativeInputEnded, "native wheel did not finish");
+ return inspect();
+}
const scroller = () => host.querySelector<HTMLElement>(".thread-scroll")!;
const busy = () => host.querySelector('.transcript-history-loading[aria-hidden="false"]') !== null;
const offset = () => anchor!.getBoundingClientRect().top - scroller().getBoundingClientRect().top;
@@ -65,16 +74,17 @@ async function reset() {
await until(() => !host.querySelector('[data-transcript-settling="true"]'), "first paint did not settle");
await frame(); await frame();
}
-async function begin() {
+async function begin(top = 80) {
const el = scroller();
// Enter from the user's ordinary scroll route; native wheel is exercised by
// the Electron driver while the real asynchronous page is held below.
el.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -120 }));
- el.scrollTo({ top: 80, behavior: "instant" });
+ el.scrollTo({ top, behavior: "instant" });
el.dispatchEvent(new Event("scroll", { bubbles: true }));
await until(busy, "page did not start");
return track();
}
+const beginAhead = () => begin(scroller().clientHeight * 2);
async function release(failed = false, lateLayout = false, empty = false) {
if (!finish) throw new Error("No pending page");
const resolve = finish; finish = undefined;
@@ -136,6 +146,7 @@ async function jumpWhileLoading() {
await frame();
await release();
const el = scroller();
+ await until(() => Math.abs(el.scrollHeight - el.clientHeight - el.scrollTop) <= 2, "latest navigation did not arrive");
return { ...inspect(), distanceFromBottom: el.scrollHeight - el.clientHeight - el.scrollTop };
}
function track() {
@@ -164,12 +175,13 @@ async function growMountedWindow() {
}
declare global { var historyLoadingFixture: { reset: typeof reset; begin: typeof begin; release: typeof release;
inspect: typeof inspect; growTail: typeof growTail; hideAndReveal: typeof hideAndReveal;
- inputOwnership: typeof inputOwnership; jumpWhileLoading: typeof jumpWhileLoading;
- growMountedWindow: typeof growMountedWindow; frames: () => Promise<void> }; }
+ inputOwnership: typeof inputOwnership; jumpWhileLoading: typeof jumpWhileLoading; beginAhead: typeof beginAhead; track: typeof track;
+ growMountedWindow: typeof growMountedWindow; armNativeInput: typeof armNativeInput;
+ finishNativeInput: typeof finishNativeInput; frames: () => Promise<void> }; }
await i18n.init({ lng: "en", resources: { en: { translation: en } } });
useAppStore.setState({ activeSessionId: "history-fixture", messages: [], sessions: [], runningSessions: {},
pendingPlans: {}, pendingAsks: {}, pendingPermissions: {}, planningStates: {}, latestTurnResults: {},
settings: { ...useAppStore.getState().settings, smoothStreaming: false } });
-globalThis.historyLoadingFixture = { reset, begin, release, inspect, growTail, hideAndReveal, inputOwnership, jumpWhileLoading, growMountedWindow,
+globalThis.historyLoadingFixture = { reset, begin, beginAhead, track, release, inspect, growTail, hideAndReveal, inputOwnership, jumpWhileLoading, growMountedWindow, armNativeInput, finishNativeInput,
frames: async () => { for (let n = 0; n < 4; n++) await frame(); } };
await reset();
diff --git a/scripts/e2e/transcript-history-navigation.tsx b/scripts/e2e/transcript-history-navigation.tsx
index 1f0b1fced..ead6dfc38 100644
--- a/scripts/e2e/transcript-history-navigation.tsx
+++ b/scripts/e2e/transcript-history-navigation.tsx
@@ -20,8 +20,8 @@ function assert(value: unknown, label: string): asserts value {
if (!value) throw new Error(`Real history navigation: ${label}`);
}
-declare global { var transcriptHistoryNavigationProbe: () => Promise<unknown>; }
-globalThis.transcriptHistoryNavigationProbe = async () => {
+declare global { var transcriptHistoryNavigationProbe: (reducedOnly?: boolean) => Promise<unknown>; }
+globalThis.transcriptHistoryNavigationProbe = async (reducedOnly = false) => {
const i18n = createInstance();
await i18n.init({ lng: "en", resources: { en: { translation: en } } });
const originalState = useAppStore.getState();
@@ -65,33 +65,34 @@ globalThis.transcriptHistoryNavigationProbe = async () => {
const scroller = () => host.querySelector<HTMLDivElement>(".thread-scroll")!;
const busy = () => host.querySelector('.transcript-history-loading[aria-hidden="false"]') !== null;
const bottom = () => Math.abs(scroller().scrollHeight - scroller().clientHeight - scroller().scrollTop) <= 2;
- const render = () => flushSync(() => root.render(<I18nextProvider i18n={i18n}>
- <div className="session-panes"><SessionPane key={id} sessionId={id} visible /></div>
+ const render = (visible = true) => flushSync(() => root.render(<I18nextProvider i18n={i18n}>
+ <div className="session-panes"><SessionPane key={id} sessionId={id} visible={visible} /></div>
</I18nextProvider>));
- const reset = async (name: string, role: "user" | "mixed" = "user") => {
+ const reset = async (name: string, role: "user" | "mixed" = "user", running = false, tailOnly = false) => {
flushSync(() => root.render(null));
for (const item of pending.splice(0)) item.resolve(item.response);
id = `navigation-${name}`;
- data = Array.from({ length: 280 }, (_, index) => ({ id: `${id}-${index}`,
+ const count = tailOnly ? 35 : 280;
+ data = Array.from({ length: count }, (_, index) => ({ id: `${id}-${index}`,
role: role === "user" || index % 30 === 0 ? "user" : "assistant",
content: `Message ${index}\n\n${"Stationary visible reading paragraph. ".repeat(80)}`,
- createdAt, status: "complete" }));
+ createdAt, status: running && index === count - 1 ? "streaming" : "complete" }));
summary = { id, title: id, mode: "agent", permissionMode: "ask", thinkingLevel: "off",
providerId: "fixture", modelId: "fixture", createdAt, updatedAt: createdAt, messageCount: data.length };
useAppStore.setState({ sessions: [summary], 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",
+ runningSessions: running ? { [id]: true } : {}, isRunning: running, workspace: undefined, queuedPrompts: {}, notifications: [], page: "chat",
settings: { ...originalState.settings, smoothStreaming: false } });
await useAppStore.getState().selectSession(id);
render();
await until(() => Boolean(scroller()) && !host.querySelector('[data-transcript-settling="true"]') && bottom(), "cold pane follows latest");
await frame();
};
- const begin = () => {
+ const begin = (top = 80) => {
const el = scroller();
el.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -400 }));
- el.scrollTo({ top: 80, behavior: "instant" });
+ el.scrollTo({ top, behavior: "instant" });
const viewport = el.getBoundingClientRect();
const row = [...el.querySelectorAll<HTMLElement>("[data-message-id]")].find(node => {
const r = node.getBoundingClientRect(); return r.height > 0 && r.bottom > viewport.top + 20 && r.top < viewport.bottom;
@@ -120,6 +121,166 @@ globalThis.transcriptHistoryNavigationProbe = async () => {
const results: unknown[] = [];
const failures: string[] = [];
try {
+ for (const tailOnly of [true, false]) for (const running of [false, true]) {
+ await reset(`motion-${tailOnly ? "tail" : "history"}-${running ? "running" : "idle"}`, "mixed", running, tailOnly);
+ const el = scroller();
+ const anchor = begin(tailOnly ? Math.max(121, (el.scrollHeight - el.clientHeight) / 2) : 80);
+ try {
+ if (!tailOnly) {
+ await until(() => pending.length === 1, "motion setup did not page");
+ await finish();
+ }
+ await until(() => Boolean(host.querySelector(".jump-latest-btn")), "latest control did not appear");
+ let blankFrames = 0;
+ const distance = () => Math.max(0, el.scrollHeight - el.clientHeight - el.scrollTop);
+ const start = distance();
+ const samples: number[] = [start];
+ let sampling = true;
+ const observers = new Set<ResizeObserver>();
+ const sample = () => {
+ if (!sampling) return;
+ samples.push(distance());
+ // rAF runs before auto content-visibility has laid out the new viewport.
+ // Inspect eligibility after that layout, still before this frame paints.
+ const observer = new ResizeObserver(() => {
+ observer.disconnect(); observers.delete(observer);
+ if (!sampling) return;
+ const viewport = el.getBoundingClientRect();
+ const painted = [...el.querySelectorAll<HTMLElement>("[data-message-id]")].some(node => {
+ const rect = node.getBoundingClientRect();
+ return rect.height > 0 && rect.bottom > viewport.top && rect.top < viewport.bottom &&
+ node.checkVisibility({ contentVisibilityAuto: true, opacityProperty: true, visibilityProperty: true });
+ });
+ if (!painted) blankFrames++;
+ });
+ observers.add(observer); observer.observe(el);
+ requestAnimationFrame(sample);
+ };
+ requestAnimationFrame(sample);
+ host.querySelector<HTMLButtonElement>(".jump-latest-btn")!.click();
+ try {
+ await until(() => !useAppStore.getState().transcriptViews[id] && bottom(), "smooth latest did not finish");
+ for (let n = 0; n < 5; n++) await frame();
+ } finally { sampling = false; for (const observer of observers) observer.disconnect(); }
+ const intermediateFrames = samples.filter(value => value > 2 && value < start - 2).length;
+ const reversal = Math.max(0, ...samples.slice(1).map((value, i) => value - samples[i]));
+ const result = { tailOnly, running, start, intermediateFrames, reversal, blankFrames, firstDistances: samples.slice(0, 8) };
+ console.log("LATEST_MOTION " + JSON.stringify(result));
+ assert(matchMedia("(prefers-reduced-motion: reduce)").matches || intermediateFrames >= 3,
+ `latest snapped instead of scrolling: ${JSON.stringify(result)}`);
+ assert(reversal <= 2, `latest moved away from bottom: ${JSON.stringify(result)}`);
+ assert(blankFrames === 0, `latest painted an empty viewport: ${JSON.stringify(result)}`);
+ results.push(result);
+ } catch (error) { failures.push(String(error)); console.log("LATEST_MOTION_ERROR " + String(error)); }
+ finally { anchor.stop(); }
+ }
+ if (reducedOnly) {
+ assert(matchMedia("(prefers-reduced-motion: reduce)").matches, "reduced motion emulation missing");
+ assert(failures.length === 0 && unexpected.length === 0, failures.join("\n"));
+ return { ok: true, reducedMotion: true, cases: results };
+ }
+ for (const action of ["interrupt", "growth", "complete", "hide", "unmount", "new-search"] as const) {
+ await reset(`lifecycle-${action}`, "mixed", action === "growth" || action === "complete");
+ const anchor = begin();
+ try {
+ await until(() => pending.length === 1, "lifecycle setup did not page");
+ await finish();
+ const el = scroller();
+ const oldTop = el.scrollTop;
+ host.querySelector<HTMLButtonElement>(".jump-latest-btn")!.click();
+ await until(() => el.scrollTop > oldTop + 20 && !bottom(), "trip did not enter an intermediate position");
+ if (action === "new-search") {
+ await useAppStore.getState().navigateTranscript({ sessionId: id, messageId: data[270].id, query: "Message 270" });
+ await until(() => useAppStore.getState().transcriptViews[id]?.focus?.messageId === data[270].id,
+ "new search did not replace latest intent");
+ for (let n = 0; n < 50; n++) await frame();
+ assert(useAppStore.getState().transcriptViews[id]?.focus?.messageId === data[270].id && !bottom(),
+ "obsolete latest arrival overrode the new search");
+ } else if (action === "interrupt") {
+ el.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -100 }));
+ el.scrollTo({ top: el.scrollTop - 100, behavior: "instant" });
+ el.dispatchEvent(new Event("scroll", { bubbles: true }));
+ const stopped = el.scrollTop;
+ for (let n = 0; n < 50; n++) await frame();
+ assert(Math.abs(el.scrollTop - stopped) <= 2 && !bottom(), "reader input did not retire the trip");
+ assert(Boolean(useAppStore.getState().transcriptViews[id]), "interruption committed latest");
+ } else {
+ if (action === "growth") {
+ const live = useAppStore.getState().messages.map(message => ({ ...message, status: "complete" as const }));
+ useAppStore.setState({ messages: [...live, { ...data.at(-1)!, id: `${id}-new`,
+ content: "New live output. ".repeat(300), status: "streaming" }] });
+ } else if (action === "complete") {
+ useAppStore.setState({ isRunning: false, runningSessions: {},
+ messages: useAppStore.getState().messages.map(message => ({ ...message, status: "complete" })) });
+ } else if (action === "hide") {
+ render(false);
+ await until(() => !useAppStore.getState().transcriptViews[id], "hide did not commit accepted latest intent");
+ render();
+ } else if (action === "unmount") {
+ flushSync(() => root.render(null));
+ assert(!useAppStore.getState().transcriptViews[id], "unmount did not commit accepted latest intent");
+ render();
+ }
+ await until(() => !useAppStore.getState().transcriptViews[id] && bottom(), `${action} lost latest`);
+ for (let n = 0; n < 15; n++) { await frame(); assert(bottom(), `${action} reversed accepted latest`); }
+ }
+ results.push({ lifecycle: action, ok: true });
+ console.log("LATEST_LIFECYCLE " + JSON.stringify({ action, ok: true }));
+ } catch (error) { failures.push(String(error)); console.log("LATEST_LIFECYCLE_ERROR " + action + " " + String(error)); }
+ finally { anchor.stop(); }
+ }
+ await reset("focused-disjoint", "mixed");
+ useAppStore.setState({ transcriptViews: { [id]: { messages: data.slice(0, 35), messageStart: 0,
+ messageEnd: 35, hasMoreBefore: false, hasMoreAfter: true, loading: null,
+ focus: { sessionId: id, messageId: data[0].id, query: "Message 0", requestId: 991 } } } });
+ await until(() => Boolean(host.querySelector(".transcript-search-target")), "search target did not mount");
+ {
+ const el = scroller();
+ const positions: number[] = [];
+ let sampling = true;
+ const sample = () => {
+ if (!sampling || !useAppStore.getState().transcriptViews[id]) return;
+ positions.push(el.scrollTop); requestAnimationFrame(sample);
+ };
+ requestAnimationFrame(sample);
+ const beforeReads = reads.length;
+ host.querySelector<HTMLButtonElement>(".jump-latest-btn")!.click();
+ try {
+ await until(() => !useAppStore.getState().transcriptViews[id] && bottom(), "disjoint search failed to join live tail");
+ const reversal = Math.max(0, ...positions.slice(1).map((top, n) => positions[n] - top));
+ assert(reversal <= 2, `old search alignment reversed latest: ${reversal}`);
+ assert(reads.length === beforeReads, "explicit latest read unloaded intermediate history");
+ results.push({ focusedDisjoint: true, reversal });
+ console.log("LATEST_FOCUSED_DISJOINT " + JSON.stringify({ reversal }));
+ } catch (error) { failures.push(String(error)); console.log("LATEST_FOCUSED_DISJOINT_ERROR " + String(error)); }
+ finally { sampling = false; }
+ }
+ for (const role of ["user", "mixed"] as const) {
+ await reset(`prefetch-${role}`, 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");
+ 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();
+ await frame();
+ assert(Math.abs(anchor.measure() - offsetBeforeScroll - 100) <= 2,
+ `prefetch undid a newer reading point: before=${offsetBeforeScroll}, now=${anchor.measure()}`);
+ anchor.stop();
+ const offset = anchor.measure();
+ await finish();
+ const drift = Math.abs(anchor.measure() - offset);
+ const result = { role, 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);
+ } catch (error) { failures.push(String(error)); console.log("EARLY_HISTORY_ERROR " + String(error)); }
+ finally { anchor.stop(); }
+ }
for (const role of ["user", "mixed"] as const) {
await reset(`quiet-${role}`, role);
const anchor = begin();
diff --git a/tests/history-loading-scroll-test-cases.md b/tests/history-loading-scroll-test-cases.md
index fc9f466b3..dcf9badb1 100644
--- a/tests/history-loading-scroll-test-cases.md
+++ b/tests/history-loading-scroll-test-cases.md
@@ -2,9 +2,16 @@
## Scope and prerequisites
-- Requirements: discard transcript scrolling while earlier messages load; keep
- the current visible turn stationary through paging and late layout; restore
- normal input afterwards without changing other navigation.
+- Requirements: request earlier history ahead of the top edge on upward scroll
+ (`min(2400px, max(120px, 3 * clientHeight))`) without hiding overflow or
+ blocking scroll input while tracking the newest actual message anchor; retain
+ the brief scroll-input and `overflow-y: hidden` lock only for the `<= 120px`
+ hard edge, explicit earlier-history actions, and underfilled top-boundary
+ observer through IO and three stable layout frames; and drive return-to-latest
+ through one custom interruptible `180–420ms` cubic ease-out viewport animation
+ (immediate under reduced motion) that keeps visible messages mounted until
+ arrival. Existing message, page, mounted-window, and retained-pane caches stay
+ unchanged, with no idle TTL or memory reclamation.
- Follow-up integration base: official `vastsa/PI-Desktop` main,
`14b928f3171e9e00b6d2851d67c832812ff61fc7`, including merged PR #2080.
The continuous-answer jump and pending-page latest-button race both fail on
@@ -28,19 +35,22 @@ is clicked. This makes the loading interval reproducible even on fast disks.
The actual production `ChatTranscript`, scroll hooks, Markdown and stylesheet
are used. It is not a mock implementation of scrolling.
-### TC-F-001: continuous wheel input during a slow page
+### TC-F-001: continuous wheel input during a slow hard-edge / explicit page
-- Priority: High. Requirement: no jump to the beginning during loading.
+- Priority: High. Requirement: hard-edge fallback prevents jumping to the top.
- Preconditions: start the fixture and click **Reset conversation**.
- Steps:
- 1. Click **Load earlier (hold)**. Note the turn label and its position.
+ 1. Click **Load earlier (hold)** (hard-edge / explicit fallback). Note the
+ turn label and its position.
2. Keep the pointer over the transcript and continuously roll upward for at
least five seconds. Repeat downward and with trackpad momentum if present.
3. Click **Complete page** and immediately try scrolling again.
-- Expected: while loading, the same turn remains at the same screen position;
- no input accumulates for replay. The page lands above that turn without a
- visible jump. After loading ends, new wheel input scrolls normally through
- older messages; it must not drain to the oldest message on its own.
+- Expected: while the hard-edge/explicit lock is active through IO and three
+ stable layout frames, the same turn remains at the same screen position and
+ main-scroller vertical wheel/touch/scroll-key input is discarded rather than
+ queued; horizontal, zero-delta, and `Ctrl`+wheel input remain unaffected. The
+ page lands above that turn without a visible jump. After settlement, new wheel
+ input scrolls normally without draining to the oldest message at rest.
- Postcondition: earlier messages are available; the viewport is unlocked.
### TC-F-002: no-input loading has no vertical jitter
@@ -72,39 +82,61 @@ are used. It is not a mock implementation of scrolling.
released. A new upward reading gesture or earlier-history action can retry;
only one page request is in flight at a time.
-### TC-ST-001: explicit return-to-latest overrides the pending page
+### TC-ST-001: explicit return-to-latest animates smoothly and overrides pending IO
-- Priority: High. Requirement: existing navigation retains ownership.
+- Priority: High. Requirement: one interruptible latest owner without blank frames.
- Steps: reset, start a held page, click the transcript's return-to-latest
- button, then click **Complete page**.
-- Expected: navigation reaches and stays at the latest turn. The old page must
- not pull the viewport back to its former reading anchor or keep input locked.
- Repeat via the real session/store paging path, both immediately after the
- upward gesture while a page is pending and after the page settles, using
- standalone rows and a continuous grouped answer. Keep normal motion enabled.
- No queued scroll event may reopen history or start another older-page read.
-
-### TC-E-001: verify the real application paths
+ button, then click **Complete page**. Repeat from an ordinary tail and from a
+ paginated historical view in both idle and running states, with normal motion
+ and `prefers-reduced-motion: reduce`, and test interrupting mid-flight with
+ main-scroller vertical wheel vs horizontal/zero/`Ctrl` wheel or nested/editable
+ controls, plus hiding/switching panes mid-trip.
+- Expected: with normal motion, the viewport animates smoothly (`180–420ms`
+ cubic ease-out, monotonic without reversing, no empty message viewport frame)
+ while suppressing competing follow, layout, and turn-completion owners;
+ reduced motion reaches the bottom immediately. Preparing a historical view
+ invalidates any pending page's `TranscriptView` identity (`loading: null`)
+ without removing visible messages and clears that exact view only on arrival,
+ while pane hide or unmount commits the accepted latest intent once. Genuine
+ main-scroller input cancels the trip at its current offset without committing
+ arrival; horizontal, zero-delta, and `Ctrl`+wheel input and nested/editable/row
+ controls do not. Disjoint search or history views switch to the canonical live
+ tail on arrival and may skip unloaded intermediate ranges without fetching or
+ animating them. No queued scroll event reopens history or starts another read.
+
+### TC-E-001: verify ahead-loading and real application paths
- Priority: High. Use an application built from this checkout with a long local
conversation containing several historical pages, tool output and code.
- Steps:
- 1. Repeat TC-F-001 and TC-F-002 while entering earlier turns normally by
- scrolling upward, including already-loaded window growth and fetched pages.
- 2. While a page loads, scroll a nested tool/delegate panel; use an editable
- field and activate a focused title with Space. Try horizontal code scrolling.
+ 1. Scroll upward into the ahead-loading band (`min(2400px, max(120px, 3 *
+ clientHeight))`) and continue reading upward while cached rows mount first
+ and Host pages load in the background; then scroll all the way into the
+ `<= 120px` hard edge. Leave the viewport at rest in the ahead-loading band.
+ 2. During both ahead-loading and a hard-edge load, scroll a nested
+ tool/delegate panel, type in an editable field, activate a focused title
+ with Space, and try horizontal code scrolling and `Ctrl`+wheel zoom.
3. Navigate with minimap/search, expand a tool, or return to latest. Switch to
another conversation and back. Repeat at a narrower window width.
- 4. Send a new prompt, scroll up while it streams, return to latest and stop.
-- Expected: only the main transcript's loading-period scroll input is held.
- Nested input, editable keys, title activation and zoom still work. Explicit
- navigation, session reading positions, streaming follow and Stop are unchanged.
+ 4. Send a new prompt, scroll up into history while it streams, verify runtime
+ running state stays real without re-pinning the historical view, then
+ return to latest and stop.
+- Expected: ahead-loading stays single-flight, leaves `overflow-y` and main
+ scroll input unlocked, tracks the newest actual message anchor as the user
+ keeps scrolling, corrects insertions/layout before paint without visible jump,
+ and never eagerly drains pages at rest (no early-threshold observer; failed or
+ empty reads wait for a new gesture or explicit action). Only the `<= 120px`
+ hard edge, explicit earlier-history continuation, or underfilled `120px`
+ observer briefly holds main-scroller scroll input. Nested input, editable
+ keys, title activation, horizontal/zero/`Ctrl` wheel, explicit navigation,
+ session reading positions, streaming follow, and Stop remain intact.
- Note: use local historical data; a paid/live-provider turn is a user opt-in,
not required by the deterministic automated fixture.
## Automated coverage
```bash
+node --test apps/desktop/test/transcript-latest-navigation.test.mjs apps/desktop/test/transcript-reading.test.mjs apps/desktop/test/transcript-scroll.test.mjs
node scripts/e2e-transcript-history-loading.mjs
node scripts/e2e-transcript-reading-position.mjs
node scripts/e2e-transcript-minimap-jump.mjs
@@ -115,22 +147,27 @@ node scripts/e2e-transcript-turn-completion.mjs
The history-loading script is also included in `e2e-transcript-render.mjs`.
It sends real Electron wheel events, uses an explicit page completion boundary,
checks single-flight IO, samples the visible anchor each frame (2 CSS-pixel
-rounding tolerance), and checks normal input after completion. Cases include
-quiet loading, native wheel bursts, tail updates, six successive delayed row
-height changes, rejection, empty pages, cached-window growth, hide/reveal, input
-ownership and return-to-latest. Its additional `transcript-history-navigation`
-journey uses production `SessionPane`, the real store and delayed external Host
-IPC reads: two message-stability cases (standalone/grouped) plus four real
-latest-button cases (pending/settled page × standalone/grouped). It checks the
-historical view is cleared, the bottom remains reached and no extra page starts.
+rounding tolerance), and checks normal input after completion. Direct fixture
+cases retain quiet hard-edge loading, native wheel bursts, tail updates, six
+successive delayed row height changes, rejection, empty pages, cached-window
+growth, hide/reveal, input ownership, and return-to-latest during IO, plus
+unlocked ahead-loading with native wheel movement (`beginAhead`). Its
+`transcript-history-navigation` probe uses production `SessionPane`, the real
+store, and delayed external Host IPC reads: four paired return-to-latest motion
+cases (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
+latest-button cases.
| Requirement | Cases | Evidence level |
| --- | --- | --- |
-| Loading input does not move the reading point | TC-F-001 | Native Electron wheel + manual |
-| Loading/rendering does not jitter | TC-F-002 | Frame samples + delayed geometry |
-| Failure releases input without a retry loop | TC-ERR-001 | Real rejected promise + native input |
-| Explicit navigation wins over a late page | TC-ST-001 | Production return-to-latest action |
-| Existing paths remain usable | TC-E-001 | Targeted suites + user application check |
+| Ahead-loading keeps scrolling unlocked and anchors prepends | TC-E-001 | Native wheel + `SessionPane` `100px` mid-IO / `<= 2px` prepend checks |
+| Hard-edge fallback locks input without moving the reading point | TC-F-001, TC-F-002, TC-F-003 | Native Electron wheel + frame samples + delayed geometry |
+| Failure or empty page releases lock without a retry loop | TC-ERR-001 | Real rejected/empty promises + native input |
+| Smooth interruptible return-to-latest wins over pending IO | TC-ST-001 | Paired tail/paginated × idle/running `SessionPane` + unit tests |
+| Existing controls and runtime state remain usable | TC-E-001 | Targeted suites + user application check |
Automated Windows results do not establish every hardware/OS combination.
Record the source revision, OS, display scaling and any remaining failing step