Skip to content

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

fix(chat): hold the reading viewport while loading history

new-Beginner2192d31df83d
diff --git a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx
index bd71a0f76..b5e919ada 100644
--- a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx
+++ b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx
@@ -465,8 +465,9 @@ function TranscriptBody({
role="status"
aria-live="polite"
aria-hidden={!loadingOlder}
+ style={{ visibility: loadingOlder ? "visible" : "hidden" }}
>
- {loadingOlder ? t("chat.loadingEarlierMessages") : null}
+ {t("chat.loadingEarlierMessages")}
</div>
{hydrationBounded ? (
// One viewport of slack, not a per-entry estimate. The spacer exists
diff --git a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts
new file mode 100644
index 000000000..848619dfe
--- /dev/null
+++ b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts
@@ -0,0 +1,164 @@
+import { useCallback, useLayoutEffect, useRef, useState, type RefObject } from "react";
+import {
+ captureTranscriptReadingPosition,
+ restoreTranscriptReadingPosition,
+ type TranscriptReadingPosition,
+} from "../../../../lib/transcript-reading-position";
+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 };
+
+/** 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. */
+export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, sourceHead, onStart, onPosition, onSettled }: {
+ scrollRef: RefObject<HTMLDivElement | null>;
+ contentRef: RefObject<HTMLDivElement | null>;
+ visible: boolean;
+ sourceHead: string | undefined;
+ onStart: () => void;
+ onPosition: (top: number) => void;
+ onSettled: () => void;
+}) {
+ const holdRef = useRef<Hold | null>(null);
+ const inFlightRef = useRef(false);
+ const frameRef = useRef(0);
+ const autoBlockedRef = useRef(false);
+ const sourceHeadRef = useRef(sourceHead);
+ sourceHeadRef.current = sourceHead;
+ const retry = useCallback(() => { autoBlockedRef.current = false; }, []);
+ const [phase, setPhase] = useState<"idle" | "mount" | "page">("idle");
+ const [, refresh] = useState(0);
+ const callbacks = useRef({ onStart, onPosition, onSettled });
+ callbacks.current = { onStart, onPosition, onSettled };
+
+ const dropHold = useCallback(() => {
+ const held = holdRef.current;
+ if (held) held.scroller.style.overflowY = held.overflowY;
+ holdRef.current = null;
+ cancelAnimationFrame(frameRef.current);
+ frameRef.current = 0;
+ }, []);
+ const cancel = useCallback(() => {
+ dropHold();
+ setPhase("idle");
+ }, [dropHold]);
+ const isHeld = useCallback(() => holdRef.current !== null, []);
+ const restore = useCallback(() => {
+ const held = holdRef.current;
+ const scroller = scrollRef.current;
+ const content = contentRef.current;
+ if (!held || !scroller || !content) return false;
+ const before = scroller.scrollTop;
+ restoreTranscriptReadingPosition(scroller, content, held.position);
+ if (Math.abs(scroller.scrollTop - before) > 1) held.stableFrames = 0;
+ callbacks.current.onPosition(scroller.scrollTop);
+ return true;
+ }, [contentRef, scrollRef]);
+
+ const run = useCallback((action: () => void | Promise<void>, windowSize: number, page = false) => {
+ const scroller = scrollRef.current;
+ const content = contentRef.current;
+ if (holdRef.current || inFlightRef.current || autoBlockedRef.current || !scroller || !content) return;
+ 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,
+ scroller, overflowY: scroller.style.overflowY };
+ holdRef.current = hold; // Synchronous: two scroll events cannot start two pages.
+ scroller.style.overflowY = "hidden";
+ inFlightRef.current = true;
+ callbacks.current.onStart();
+ setPhase(page ? "page" : "mount");
+ const finish = () => {
+ inFlightRef.current = false;
+ if (holdRef.current !== hold) return;
+ hold.settled = true;
+ // IO resolution is not a DOM commit. Render current history rather than
+ // consuming an anchor on messages.length while deferred rows are stale.
+ refresh(value => value + 1);
+ };
+ try {
+ const result = action();
+ void Promise.resolve(result).then(finish, (error: unknown) => {
+ if (holdRef.current === hold) autoBlockedRef.current = true;
+ finish();
+ console.error("Transcript history page failed", error);
+ });
+ } catch (error) {
+ if (holdRef.current === hold) autoBlockedRef.current = true;
+ finish();
+ console.error("Transcript history page failed", error);
+ }
+ }, [contentRef, scrollRef]);
+
+ // Correct React commits synchronously, before paint, not on raw source length.
+ useLayoutEffect(() => {
+ if (!visible) { cancel(); return; }
+ const hold = holdRef.current;
+ if (!hold) return;
+ restore();
+ if (frameRef.current) return;
+ const align = () => {
+ frameRef.current = 0;
+ if (holdRef.current !== hold) return;
+ const scroller = scrollRef.current;
+ if (!scroller) return;
+ const before = scroller.scrollTop;
+ restore();
+ const changed = Math.abs(scroller.scrollTop - before) > 1;
+ hold.stableFrames = hold.settled && !changed ? hold.stableFrames + 1 : 0;
+ if (hold.stableFrames >= 3) {
+ // A failed/empty read must not loop at an unchanged visible boundary.
+ if (hold.page && hold.sourceHead === sourceHeadRef.current) autoBlockedRef.current = true;
+ dropHold();
+ setPhase("idle");
+ callbacks.current.onSettled();
+ return;
+ }
+ frameRef.current = requestAnimationFrame(align);
+ };
+ frameRef.current = requestAnimationFrame(align);
+ });
+
+ // content-visibility estimates and late row measurements can change after a
+ // layout effect. ResizeObserver runs before paint; a queued rAF alone is late.
+ useLayoutEffect(() => {
+ const content = contentRef.current;
+ const scroller = scrollRef.current;
+ if (!content || !scroller) return;
+ const observer = new ResizeObserver(() => {
+ const held = holdRef.current;
+ if (!held) return;
+ const before = scroller.scrollTop;
+ restore();
+ if (Math.abs(scroller.scrollTop - before) > 1) held.stableFrames = 0;
+ });
+ observer.observe(content, { box: "border-box" });
+ observer.observe(scroller, { box: "border-box" });
+ return () => observer.disconnect();
+ }, [contentRef, restore, scrollRef]);
+
+ useLayoutEffect(() => {
+ 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;
+ 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.
+ event.preventDefault();
+ event.stopPropagation();
+ };
+ const options = { capture: true, passive: false };
+ for (const type of ["wheel", "touchmove", "keydown"]) scroller.addEventListener(type, block, options);
+ return () => {
+ for (const type of ["wheel", "touchmove", "keydown"]) scroller.removeEventListener(type, block, true);
+ dropHold();
+ };
+ }, [contentRef, dropHold, scrollRef]);
+
+ return { loadingOlder: phase === "page", pending: phase !== "idle", run, restore, isHeld, cancel, retry };
+}
diff --git a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
index e9f925e5f..407ff5b53 100644
--- a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
+++ b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
@@ -46,6 +46,7 @@ import {
} from "../../../../lib/transcript-reading-position";
import { useTranscriptReadingPosition, type RestoreTranscriptReading } from "../../../../hooks/use-transcript-reading-position";
import { useTurnCompletionScroll } from "./useTurnCompletionScroll";
+import { useTranscriptHistoryPaging } from "./useTranscriptHistoryPaging";
type UseTranscriptScrollOptions = {
sessionId: string | undefined;
@@ -94,8 +95,6 @@ export function useTranscriptScroll({
const lastScrollGestureAtRef = useRef(-Infinity);
const wasRunningRef = useRef(isRunning);
const followFrameRef = useRef(0);
- const prependHeightRef = useRef<number | null>(null);
- const [loadingOlder, setLoadingOlder] = useState(false);
const [showJump, setShowJump] = useState(false);
// Steady-state cap on mounted history rows (D261). Grows when the user
@@ -182,6 +181,25 @@ export function useTranscriptScroll({
enterDisclosureReading,
recordScrollPosition,
);
+ const startHistoryReading = useCallback(() => {
+ releaseDisclosureAnchor();
+ releaseFollow();
+ }, [releaseDisclosureAnchor, releaseFollow]);
+ const {
+ loadingOlder, pending: historyPending, run: preserveHistory, retry: retryHistoryPaging,
+ restore: restoreHistoryAnchor, isHeld: isHistoryPaging, cancel: cancelHistoryPaging,
+ } = useTranscriptHistoryPaging({
+ scrollRef, contentRef, visible: paneVisible, sourceHead: messages[0]?.id, onStart: startHistoryReading,
+ onPosition: recordScrollPosition, onSettled: rememberReadingPosition,
+ });
+ const releaseNavigationFollow = useCallback(() => {
+ cancelHistoryPaging();
+ releaseFollow();
+ }, [cancelHistoryPaging, releaseFollow]);
+ const notifyDisclosure = useCallback<typeof disclosureAnchorNotifier>((title) => {
+ cancelHistoryPaging();
+ disclosureAnchorNotifier(title);
+ }, [cancelHistoryPaging, disclosureAnchorNotifier]);
// A user scroll-up gesture always emits input before its scroll events;
// programmatic follow scrolling and layout clamps (composer collapse on
@@ -193,12 +211,14 @@ export function useTranscriptScroll({
// consumes belongs to that dock.
const markScrollGesture = useCallback(
(event: Event) => {
+ if (isHistoryPaging()) return;
const input = readScrollInputContext(
event,
scrollRef.current,
contentRef.current,
);
if (!isScrollGestureInput(event.type as ScrollInputType, input)) return;
+ 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
// before its queued frames can overwrite the reader's next movement.
@@ -208,7 +228,7 @@ export function useTranscriptScroll({
// Real input takes the viewport back from a held disclosure position.
releaseDisclosureAnchor();
},
- [cancelReadingPosition, releaseDisclosureAnchor],
+ [cancelReadingPosition, isHistoryPaging, releaseDisclosureAnchor, retryHistoryPaging],
);
useEffect(() => {
@@ -301,6 +321,7 @@ export function useTranscriptScroll({
const paneVisibleRef = useRef(paneVisible);
paneVisibleRef.current = paneVisible;
const scheduleFollowScroll = useCallback(() => {
+ if (isHistoryPaging()) return;
if (!paneVisibleRef.current) return;
// A held disclosure position wins over a queued follow frame: re-asserting
// the bottom here would move the title the reader just toggled even though
@@ -311,7 +332,7 @@ export function useTranscriptScroll({
followFrameRef.current = 0;
if (paneVisibleRef.current && pinnedRef.current) scrollToBottom();
});
- }, [isDisclosureAnchorHeld, scrollToBottom]);
+ }, [isDisclosureAnchorHeld, isHistoryPaging, scrollToBottom]);
// Re-pins before the browser paints. A ResizeObserver callback runs after
// layout and before paint, so a `requestAnimationFrame` requested from it
@@ -325,27 +346,19 @@ export function useTranscriptScroll({
// restored first: its height can keep changing for several frames, and
// re-pinning on any one of them is what dragged that title out of view.
const followScrollNow = useCallback(() => {
+ if (paneVisibleRef.current && restoreHistoryAnchor()) return;
if (paneVisibleRef.current && restoreDisclosureAnchor()) return;
if (!paneVisibleRef.current || !pinnedRef.current) return;
cancelFollowScroll();
scrollToBottom();
- }, [cancelFollowScroll, restoreDisclosureAnchor, scrollToBottom]);
+ }, [cancelFollowScroll, restoreDisclosureAnchor, restoreHistoryAnchor, scrollToBottom]);
useEffect(() => cancelFollowScroll, [cancelFollowScroll]);
const loadOlder = useCallback(() => {
- const el = scrollRef.current;
- // Paging is a reading gesture, so a hidden pane never initiates one.
- if (!paneVisibleRef.current) return;
- if (!el || !hasMoreBefore || loadingOlder || !onLoadOlder) {
- return;
- }
- // Prepending rows changes scrollHeight. Capture the old height so the
- // user's viewport stays anchored to the same message after the page lands.
- prependHeightRef.current = el.scrollHeight;
- setLoadingOlder(true);
- void onLoadOlder().finally(() => setLoadingOlder(false));
- }, [hasMoreBefore, loadingOlder, onLoadOlder]);
+ if (!paneVisibleRef.current || !hasMoreBefore || !onLoadOlder) return;
+ preserveHistory(onLoadOlder, windowSize, true);
+ }, [hasMoreBefore, onLoadOlder, preserveHistory, windowSize]);
/**
* Reaching the top escalates in two stages (D261): mount more of what is
@@ -355,34 +368,14 @@ export function useTranscriptScroll({
*/
const reachTop = useCallback(() => {
const el = scrollRef.current;
- if (!el) return;
+ if (!el || isHistoryPaging()) return;
const grown = growTranscriptWindow(windowSize, historyLengthRef.current);
if (grown !== windowSize) {
- // Mounting rows above the viewport changes scrollHeight exactly the way a
- // fetched page does, so it takes the same anchor.
- prependHeightRef.current = el.scrollHeight;
- setWindowSize(grown);
+ preserveHistory(() => setWindowSize(grown), windowSize);
return;
}
loadOlder();
- }, [loadOlder, windowSize]);
-
- // Anchors the viewport whenever rows appear above it — a fetched older page
- // (`messages.length`) or a grown mounted window (`windowSize`, D261). Both add
- // height above the reading position, so both are corrected here before paint.
- useLayoutEffect(() => {
- const previousHeight = prependHeightRef.current;
- if (previousHeight === null) return;
- const el = scrollRef.current;
- prependHeightRef.current = null;
- if (!el) return;
- const delta = el.scrollHeight - previousHeight;
- if (delta <= 0) return;
- el.scrollTop += delta;
- lastScrollTopRef.current = el.scrollTop;
- if (transcriptHasLayout(el)) lastLaidOutScrollTopRef.current = el.scrollTop;
- }, [messages.length, windowSize]);
-
+ }, [isHistoryPaging, loadOlder, preserveHistory, windowSize]);
// Follow the stream only while the user is pinned to the bottom; a manual
@@ -390,6 +383,7 @@ export function useTranscriptScroll({
const handleScroll = useCallback(() => {
const el = scrollRef.current;
if (!el) return;
+ if (restoreHistoryAnchor()) return;
if (paneVisibleRef.current && transcriptHasLayout(el)) {
lastLaidOutScrollTopRef.current = el.scrollTop;
}
@@ -459,7 +453,7 @@ export function useTranscriptScroll({
setShowJump(transition.showJump);
}
rememberReadingPosition();
- }, [cancelFollowScroll, reachTop, readingPositionPendingRef, readingWindow, rememberReadingPosition, scheduleFollowScroll]);
+ }, [cancelFollowScroll, reachTop, readingPositionPendingRef, readingWindow, rememberReadingPosition, restoreHistoryAnchor, scheduleFollowScroll]);
// Send / retry / regenerate always re-pins follow mode so the new prompt and
// its stream stay in view, even if the user had scrolled up through history.
@@ -470,6 +464,7 @@ export function useTranscriptScroll({
const turnStarted = isRunning && !wasRunningRef.current;
wasRunningRef.current = isRunning;
if (!turnStarted || !paneVisible) return;
+ cancelHistoryPaging();
cancelReadingPosition();
releaseDisclosureAnchor();
cancelFollowScroll();
@@ -480,6 +475,7 @@ export function useTranscriptScroll({
scheduleFollowScroll();
}, [
cancelFollowScroll,
+ cancelHistoryPaging,
cancelReadingPosition,
isRunning,
paneVisible,
@@ -492,7 +488,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(),
+ isFollowing: () => pinnedRef.current && !isDisclosureAnchorHeld() && !isHistoryPaging(),
onAnchored: leaveFollow,
});
@@ -537,7 +533,7 @@ export function useTranscriptScroll({
);
const deferredProjection = useDeferredValue(projection);
const renderedProjection =
- readingWindow || firstCommit || paneRevealed ? projection : deferredProjection;
+ readingWindow || historyPending || firstCommit || paneRevealed ? projection : deferredProjection;
const { entries, visible, history: allHistoryEntries } = renderedProjection;
const tailEntry = entries.at(-1);
// Published for `reachTop`, which is declared above this projection but only
@@ -625,12 +621,12 @@ export function useTranscriptScroll({
const releaseSearchFollow = useCallback((fresh: boolean) => {
stopSmoothScroll(scrollRef.current);
cancelReadingPosition();
- if (fresh) prependHeightRef.current = null;
+ if (fresh) cancelHistoryPaging();
releaseDisclosureAnchor();
cancelFollowScroll();
pinnedRef.current = false;
setShowJump(true);
- }, [cancelFollowScroll, cancelReadingPosition, releaseDisclosureAnchor]);
+ }, [cancelFollowScroll, cancelHistoryPaging, cancelReadingPosition, releaseDisclosureAnchor]);
useTranscriptSearchFocus({
target: searchTarget,
source: searchTarget
@@ -714,6 +710,7 @@ export function useTranscriptScroll({
const revealEarlierHistory = useCallback(() => {
const el = scrollRef.current;
if (!el) return;
+ retryHistoryPaging();
if (isHistoryRevealPosition(el)) {
reachTop();
return;
@@ -727,10 +724,11 @@ export function useTranscriptScroll({
top: 0,
behavior: reduceMotion ? "auto" : "smooth",
});
- }, [reachTop, releaseDisclosureAnchor, releaseFollow]);
+ }, [reachTop, releaseDisclosureAnchor, releaseFollow, retryHistoryPaging]);
const jumpToLatest = useCallback(() => {
cancelReadingPosition();
+ cancelHistoryPaging();
releaseDisclosureAnchor();
pinnedRef.current = true;
setShowJump(false);
@@ -743,7 +741,7 @@ export function useTranscriptScroll({
? "auto"
: "smooth",
);
- }, [cancelReadingPosition, releaseDisclosureAnchor, rememberReadingPosition, scrollToBottom]);
+ }, [cancelHistoryPaging, cancelReadingPosition, 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,
@@ -833,7 +831,7 @@ export function useTranscriptScroll({
revealEarlierHistory,
scrollToBottom,
jumpToLatest,
- releaseFollow,
- disclosureAnchorNotifier,
+ releaseFollow: releaseNavigationFollow,
+ disclosureAnchorNotifier: notifyDisclosure,
};
}
diff --git a/apps/desktop/test/interaction-performance.test.mjs b/apps/desktop/test/interaction-performance.test.mjs
index 37bbce3a8..7d25f14c5 100644
--- a/apps/desktop/test/interaction-performance.test.mjs
+++ b/apps/desktop/test/interaction-performance.test.mjs
@@ -71,7 +71,7 @@ test("stream rendering avoids duplicate frame state and coalesces following", ()
// commit that reveals it, or the reveal shows one empty frame (ADR 0137).
assert.match(
transcript,
- /const renderedProjection =\s*readingWindow \|\| firstCommit \|\| paneRevealed \? projection : deferredProjection/,
+ /const renderedProjection =\s*readingWindow \|\| historyPending \|\| firstCommit \|\| paneRevealed \? projection : deferredProjection/,
);
assert.match(transcript, /getTranscriptProjection\(messages, compactions\)/);
assert.match(transcript, /useDeferredValue\(projection\)/);
diff --git a/apps/desktop/test/transcript-disclosure-reading.test.mjs b/apps/desktop/test/transcript-disclosure-reading.test.mjs
index e6563891d..c57705f1e 100644
--- a/apps/desktop/test/transcript-disclosure-reading.test.mjs
+++ b/apps/desktop/test/transcript-disclosure-reading.test.mjs
@@ -89,7 +89,7 @@ test("the transcript restores the held title inside its resize observer", () =>
// so the correction has to run from the observer, before follow.
assert.match(
transcript,
- /const followScrollNow = useCallback\(\(\) => \{\s*if \(paneVisibleRef\.current && restoreDisclosureAnchor\(\)\) return;\s*if \(!paneVisibleRef\.current \|\| !pinnedRef\.current\) return;\s*cancelFollowScroll\(\);\s*scrollToBottom\(\);/,
+ /const followScrollNow = useCallback\(\(\) => \{\s*if \(paneVisibleRef\.current && restoreHistoryAnchor\(\)\) return;\s*if \(paneVisibleRef\.current && restoreDisclosureAnchor\(\)\) return;\s*if \(!paneVisibleRef\.current \|\| !pinnedRef\.current\) return;\s*cancelFollowScroll\(\);\s*scrollToBottom\(\);/,
);
assert.match(transcript, /new ResizeObserver\(followScrollNow\)/);
assert.match(transcript, /ro\.observe\(content, \{ box: "border-box" \}\)/);
@@ -130,7 +130,7 @@ test("real input, a new turn and every navigation drop the held position", () =>
);
assert.match(
transcript,
- /const jumpToLatest = useCallback\(\(\) => \{\s*cancelReadingPosition\(\);\s*releaseDisclosureAnchor\(\);\s*pinnedRef\.current = true;/,
+ /const jumpToLatest = useCallback\(\(\) => \{\s*cancelReadingPosition\(\);\s*cancelHistoryPaging\(\);\s*releaseDisclosureAnchor\(\);\s*pinnedRef\.current = true;/,
);
assert.match(
transcript,
diff --git a/apps/desktop/test/transcript-window.test.mjs b/apps/desktop/test/transcript-window.test.mjs
index 94b072d73..66fcd0be8 100644
--- a/apps/desktop/test/transcript-window.test.mjs
+++ b/apps/desktop/test/transcript-window.test.mjs
@@ -213,23 +213,21 @@ 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 \}, \[loadOlder, windowSize\]\);/,
+ /const reachTop = useCallback\(\(\) => \{([\s\S]*?)\n \}, \[[^\]]*\]\);/,
)?.[1];
assert.ok(reachTop, "reachTop must exist with a stable identity");
assert.match(reachTop, /growTranscriptWindow\(windowSize, historyLengthRef\.current\)/);
- assert.match(reachTop, /prependHeightRef\.current = el\.scrollHeight/);
+ assert.match(reachTop, /preserveHistory\(\(\) => setWindowSize\(grown\), windowSize\)/);
assert.match(reachTop, /setWindowSize\(grown\)/);
assert.match(reachTop, /loadOlder\(\)/);
});
test("mounting rows above the viewport is anchored like a fetched page", () => {
- // Both add height above the reading position, so both take the same
- // pre-paint correction; without `windowSize` here, growing the window would
- // shove the rows the user is reading down the screen.
- assert.match(
- transcript,
- /const delta = el\.scrollHeight - previousHeight;[\s\S]*?\}, \[messages\.length, windowSize\]\)/,
- );
+ // 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, /useTranscriptHistoryPaging\(\{/);
+ assert.doesNotMatch(transcript, /prependHeightRef|el\.scrollTop \+= delta/);
});
test("the window is owned per session pane, so no switch can inherit a budget", () => {
diff --git a/docs/adr/0130-bounded-mounted-transcript-window.md b/docs/adr/0130-bounded-mounted-transcript-window.md
index adde02870..93ca2bd7d 100644
--- a/docs/adr/0130-bounded-mounted-transcript-window.md
+++ b/docs/adr/0130-bounded-mounted-transcript-window.md
@@ -46,8 +46,11 @@ reference-equal, and that runs on every streamed token.
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**.
- Both add height above the reading position, so `prependHeightRef` is captured
- for both and corrected in the same layout effect.
+ 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.
+ This replaces the old `prependHeightRef` total-height delta: deferred DOM,
+ 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.
diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.md
index 7a75caa64..01402a394 100644
--- a/docs/spec/04-ux/09-interaction-patterns.md
+++ b/docs/spec/04-ux/09-interaction-patterns.md
@@ -1567,6 +1567,21 @@ 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.
+- 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.
- 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
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index cfb1086fb..dab9e568f 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -13474,6 +13474,35 @@ This test plan spec is accepted when:
`conversation-minimap.test.mjs`, `interaction-performance.test.mjs`); rendered
desktop journey and the low-memory Windows measurement pending
+#### E2E-CHAT-history-loading-holds-viewport
+
+- **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.
+- **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.
+ Manual procedures: `tests/history-loading-scroll-test-cases.md`.
+- **Specs linked**: `04-ux/09-interaction-patterns.md` §9.1, 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.
+
#### E2E-160: Dragging the window across displays keeps the dropped position
- **Preconditions**: PI-Desktop is open on a machine with two displays arranged
diff --git a/scripts/README.md b/scripts/README.md
index bcbdf1e35..a382349fb 100644
--- a/scripts/README.md
+++ b/scripts/README.md
@@ -62,6 +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-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
new file mode 100644
index 000000000..78a0d1dba
--- /dev/null
+++ b/scripts/e2e-transcript-history-loading.mjs
@@ -0,0 +1,102 @@
+#!/usr/bin/env node
+/** Native wheel + production ChatTranscript, isolated synthetic history only. */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { cp, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { resolveElectronBinary } from "./e2e/boot.mjs";
+const root = fileURLToPath(new URL("..", import.meta.url));
+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");
+const { electronBinary } = resolveElectronBinary(root);
+const manual = process.argv.includes("--manual");
+const temp = await mkdtemp(join(process.env.PI_SCRATCH_DIR ?? root, "history-loading-"));
+try {
+ await build({ entryPoints: [join(root, "scripts/e2e/transcript-history-loading.tsx")],
+ outfile: join(temp, "renderer.js"), bundle: true, platform: "browser", format: "esm", jsx: "automatic",
+ define: { "process.env.NODE_ENV": '"production"', "import.meta.env": JSON.stringify({ DEV: false, MODE: "production" }) },
+ loader: { ".css": "empty" }, alias: {
+ "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),
+ react: join(root, "apps/desktop/node_modules/react"), "react-dom": join(root, "apps/desktop/node_modules/react-dom") },
+ nodePaths: [join(root, "apps/desktop/node_modules")], plugins: [{ name: "assets", setup(b) {
+ b.onResolve({ filter: /\?url$/ }, ({ path, resolveDir }) => ({ path: join(resolveDir, path.slice(0, -4)), namespace: "asset" }));
+ b.onLoad({ filter: /.*/, namespace: "asset" }, async ({ path }) => ({ contents: await readFile(path), loader: "file" }));
+ } }],
+ });
+ const renderer = join(root, "apps/desktop/out/renderer");
+ const html = await readFile(join(renderer, "index.html"), "utf8");
+ const css = [...html.matchAll(/href="([^" ]+\.css)"/g)].map(m => m[1]);
+ assert(css.length, "Build Desktop before running this test");
+ await cp(join(renderer, "assets"), join(temp, "assets"), { recursive: true });
+ await writeFile(join(temp, "index.html"), `<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data:"><title>History loading scroll regression</title>${css.map(p => `<link rel="stylesheet" href="${p}">`).join("")}<script type="module" src="renderer.js"></script>`);
+ await writeFile(join(temp, "main.cjs"), `
+const { app, BrowserWindow } = require('electron');
+const assert = require('node:assert/strict');
+app.setPath('userData', require('node:path').join(__dirname, 'profile'));
+app.commandLine.appendSwitch('force-prefers-reduced-motion');
+app.disableHardwareAcceleration();
+app.on('window-all-closed', () => app.quit());
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({ show: true, width: 1100, height: 720, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
+ win.webContents.on('console-message', e => console.error(e.message));
+ const js = expression => win.webContents.executeJavaScript(expression);
+ const call = expression => js('globalThis.historyLoadingFixture.' + expression);
+ const wheel = async (point, deltaY) => {
+ win.webContents.sendInputEvent({ type: 'mouseMove', x: point.x, y: point.y });
+ win.webContents.sendInputEvent({ type: 'mouseWheel', x: point.x, y: point.y, deltaY, deltaX: 0, canScroll: true });
+ await call('frames()');
+ };
+ win.focus();
+ try {
+ await win.loadFile(require('node:path').join(__dirname, 'index.html'));
+ await js('new Promise((resolve,reject)=>{const end=performance.now()+10000;const check=()=>{if(globalThis.historyLoadingFixture)resolve();else if(performance.now()>end)reject(new Error("fixture did not initialize"));else requestAnimationFrame(check)};check()})');
+ if (${manual}) return;
+ const results = [];
+ for (const name of ['wheel', 'quiet', 'tail', 'late-layout', 'failure', 'empty', 'hide']) {
+ await call('reset()');
+ const before = await call('begin()');
+ if (name === 'wheel') assert.deepEqual(await call('inputOwnership()'),
+ { wheel: true, key: true, touch: true, field: false, activation: false, nested: false, zoom: false });
+ if (name === 'wheel') for (let n = 0; n < 6; n++) await wheel(before, n % 2 ? 80 : -240);
+ if (name === 'tail') await call('growTail()');
+ const during = await call('inspect()');
+ const after = await call(name === 'hide' ? 'hideAndReveal()' : 'release(' + (name === 'failure') + ',' + (name === 'late-layout') + ',' + (name === 'empty') + ')');
+ const result = { name, before, during, after };
+ results.push(result);
+ console.log('HISTORY_LOADING_CASE ' + JSON.stringify(result));
+ assert(Math.abs(during.offset - before.offset) <= 2, name + ': loading input/layout moved the visible row');
+ assert(after.maxDrift <= 2, name + ': a painted frame moved the reading anchor by ' + after.maxDrift);
+ assert(Math.abs(after.offset - before.offset) <= 2, name + ': page changed the reading position');
+ assert.equal(after.calls, 1, name + ': duplicate page request');
+ assert.equal(after.locked, false, name + ': input remained blocked');
+ for (let n = 0; n < 4; n++) await wheel(after, -120);
+ 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('begin()'); await call('release()');
+ const cached = await call('growMountedWindow()');
+ assert(cached.after.maxDrift <= 2 && Math.abs(cached.after.offset - cached.before.offset) <= 2,
+ 'mounting cached history moved the reading anchor');
+ assert.equal(cached.after.calls, 1, 'cached window growth made another page request');
+ assert.equal(cached.after.locked, false, 'cached window growth left input blocked');
+ await call('reset()');
+ await call('begin()');
+ const navigation = await call('jumpWhileLoading()');
+ assert.equal(navigation.locked, false, 'return-to-latest did not cancel the old hold');
+ assert(Math.abs(navigation.distanceFromBottom) <= 2, 'late page stole explicit latest navigation');
+ 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); }
+});`);
+ const env = { ...process.env }; delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(electronBinary, [join(temp, "main.cjs")], { env, stdio: ["ignore", "pipe", "pipe"] });
+ let output = "";
+ for (const stream of [child.stdout, child.stderr]) stream.on("data", data => { output += data; process.stdout.write(data); });
+ const timer = manual ? undefined : setTimeout(() => child.kill("SIGKILL"), 90_000);
+ let code;
+ try { code = await new Promise((resolve, reject) => { child.once("error", reject); child.once("close", resolve); }); }
+ finally { clearTimeout(timer); }
+ assert.equal(code, 0, output.slice(-6000));
+ if (!manual) assert.match(output, /HISTORY_LOADING_PROBE .*"ok":true/);
+} finally { await rm(temp, { recursive: true, force: true }); }
diff --git a/scripts/e2e-transcript-render.mjs b/scripts/e2e-transcript-render.mjs
index 29ece4099..40c1de575 100644
--- a/scripts/e2e-transcript-render.mjs
+++ b/scripts/e2e-transcript-render.mjs
@@ -293,3 +293,6 @@ app.whenReady().then(async () => {
} finally {
await rm(temp, { recursive: true, force: true });
}
+
+// Keep history paging's real native-input regression in the existing CI suite.
+await import("./e2e-transcript-history-loading.mjs");
diff --git a/scripts/e2e/transcript-history-loading.tsx b/scripts/e2e/transcript-history-loading.tsx
new file mode 100644
index 000000000..19b9d8836
--- /dev/null
+++ b/scripts/e2e/transcript-history-loading.tsx
@@ -0,0 +1,174 @@
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import i18n from "i18next";
+import { I18nextProvider } from "react-i18next";
+import { en } from "@pi-desktop/i18n";
+import type { UiMessage } from "@pi-desktop/shared";
+import { ChatTranscript } from "../../apps/desktop/src/features/chat/transcript/ChatTranscript";
+import { useAppStore } from "../../apps/desktop/src/stores/app-store";
+
+const frame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+async function until(test: () => boolean, label: string) {
+ const deadline = performance.now() + 6000;
+ while (!test()) {
+ if (performance.now() > deadline) throw new Error(`History loading: ${label}`);
+ await frame();
+ }
+}
+const messages = (start: number, end: number): UiMessage[] => Array.from({ length: end - start }, (_, n) => ({
+ id: `history-${start + n}`, role: n % 2 ? "assistant" : "user", status: "complete",
+ createdAt: "2026-11-01T00:00:00Z",
+ content: `Turn ${start + n}\n\n${"Reading anchor content. ".repeat(35)}`,
+}));
+const host = document.createElement("div");
+host.style.cssText = "position:fixed;inset:0;display:flex;flex-direction:column";
+document.body.append(host);
+const root = createRoot(host);
+let current = messages(60, 100);
+let visible = true;
+let more = true;
+let calls = 0;
+let finish: (() => void) | undefined;
+let fail: (() => void) | undefined;
+let anchor: HTMLElement | undefined;
+let baseline = 0;
+let samples: number[] = [];
+let sampling = 0;
+let scenario = 0;
+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;
+const onLoadOlder = () => new Promise<void>((resolve, reject) => {
+ calls++; finish = resolve; fail = () => reject(new Error("Synthetic history read failed"));
+});
+function render() {
+ flushSync(() => root.render(<I18nextProvider i18n={i18n}>
+ <nav style={{ display: "flex", gap: 12, padding: 8 }}>
+ <button onClick={() => void reset()}>Reset conversation</button>
+ <button onClick={() => void begin()}>Load earlier (hold)</button>
+ <button onClick={() => void release()}>Complete page</button>
+ <button onClick={() => void release(true)}>Fail page</button>
+ <span>Scroll continuously while loading; the visible turn must stay still.</span>
+ </nav>
+ <div style={{ display: "flex", flexDirection: "column", flex: 1, minWidth: 0, minHeight: 0, position: "relative", visibility: visible ? "visible" : "hidden" }}>
+ <ChatTranscript key={scenario} sessionId={`history-loading-${scenario}`} messages={current}
+ hasMoreBefore={more} onLoadOlder={onLoadOlder} isRunning={false} paneVisible={visible} />
+ </div>
+ </I18nextProvider>));
+}
+async function reset() {
+ finish?.(); finish = undefined;
+ scenario++; calls = 0; more = true; visible = true; current = messages(60, 100);
+ anchor = undefined; cancelAnimationFrame(sampling); samples = [];
+ render();
+ await until(() => !host.querySelector('[data-transcript-settling="true"]'), "first paint did not settle");
+ await frame(); await frame();
+}
+async function begin() {
+ 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.dispatchEvent(new Event("scroll", { bubbles: true }));
+ await until(busy, "page did not start");
+ return track();
+}
+async function release(failed = false, lateLayout = false, empty = false) {
+ if (!finish) throw new Error("No pending page");
+ const resolve = finish; finish = undefined;
+ if (!failed && !empty) { current = [...messages(0, 60), ...current]; more = false; render(); }
+ if (failed) fail?.(); else resolve();
+ fail = undefined;
+ if (lateLayout) {
+ const row = scroller().querySelector<HTMLElement>("[data-minimap-id]")!;
+ row.style.contentVisibility = "visible";
+ for (let n = 1; n <= 6; n++) { await frame(); row.style.paddingBottom = `${n * 20}px`; }
+ }
+ await until(() => !busy(), "loading did not finish");
+ // Include multiple paints and lazy content-visibility layout after prepend.
+ for (let n = 0; n < 12; n++) await frame();
+ cancelAnimationFrame(sampling);
+ return inspect();
+}
+function inspect() {
+ const el = scroller(); const r = el.getBoundingClientRect();
+ const probe = new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: 0 });
+ el.dispatchEvent(probe);
+ return { busy: busy(), locked: probe.defaultPrevented, calls, top: el.scrollTop, height: el.scrollHeight, viewport: el.clientHeight, anchorId: anchor?.dataset.minimapId,
+ offset: anchor ? offset() : null, baseline, maxDrift: samples.length ? Math.max(...samples.map(x => Math.abs(x - baseline))) : 0,
+ x: Math.round(r.left + r.width / 2), y: Math.round(r.top + Math.min(180, r.height / 2)) };
+}
+async function growTail() {
+ current = [...current, ...messages(100, 104)]; render();
+ for (let n = 0; n < 4; n++) await frame();
+ return inspect();
+}
+async function hideAndReveal() {
+ visible = false; render(); await frame();
+ finish?.(); finish = undefined;
+ visible = true; render();
+ await until(() => !busy(), "hidden load did not release");
+ return inspect();
+}
+function inputOwnership() {
+ const el = scroller();
+ const field = document.createElement("textarea");
+ const title = document.createElement("button");
+ const nested = document.createElement("div");
+ nested.dataset.scrollOwner = "fixture-dock";
+ nested.style.cssText = "height:40px;overflow:auto";
+ nested.innerHTML = '<div style="height:400px">Nested scroll content</div>';
+ el.append(field, title, nested);
+ const blocked = (target: HTMLElement, event: Event) => { target.dispatchEvent(event); return event.defaultPrevented; };
+ const key = (value: string) => new KeyboardEvent("keydown", { bubbles: true, cancelable: true, key: value });
+ const wheel = (ctrlKey = false) => new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: -120, ctrlKey });
+ try {
+ return { wheel: blocked(el, wheel()), key: blocked(el, key("PageUp")),
+ touch: blocked(el, new Event("touchmove", { bubbles: true, cancelable: true })),
+ field: blocked(field, key("ArrowUp")), activation: blocked(title, key(" ")),
+ nested: blocked(nested, wheel()), zoom: blocked(el, wheel(true)) };
+ } finally { field.remove(); title.remove(); nested.remove(); }
+}
+async function jumpWhileLoading() {
+ host.querySelector<HTMLButtonElement>(".jump-latest-btn")!.click();
+ await frame();
+ await release();
+ const el = scroller();
+ return { ...inspect(), distanceFromBottom: el.scrollHeight - el.clientHeight - el.scrollTop };
+}
+function track() {
+ cancelAnimationFrame(sampling);
+ const el = scroller();
+ anchor = [...el.querySelectorAll<HTMLElement>("[data-minimap-id]")].find(row => {
+ const r = row.getBoundingClientRect(); return r.bottom > el.getBoundingClientRect().top && r.height > 0;
+ });
+ if (!anchor) throw new Error("Missing visible reading anchor");
+ baseline = offset(); samples = [];
+ const sample = () => { if (visible) samples.push(offset()); sampling = requestAnimationFrame(sample); };
+ sampling = requestAnimationFrame(sample);
+ return inspect();
+}
+async function growMountedWindow() {
+ const el = scroller();
+ const count = el.querySelectorAll("[data-minimap-id]").length;
+ el.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -120 }));
+ el.scrollTo({ top: 80, behavior: "instant" });
+ const before = track();
+ el.dispatchEvent(new Event("scroll", { bubbles: true }));
+ await until(() => el.querySelectorAll("[data-minimap-id]").length > count, "cached history did not mount");
+ for (let n = 0; n < 12; n++) await frame();
+ cancelAnimationFrame(sampling);
+ return { before, after: inspect() };
+}
+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> }; }
+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,
+ frames: async () => { for (let n = 0; n < 4; n++) await frame(); } };
+await reset();
diff --git a/scripts/e2e/transcript-live-tail.tsx b/scripts/e2e/transcript-live-tail.tsx
index 7e755c3fd..77493c076 100644
--- a/scripts/e2e/transcript-live-tail.tsx
+++ b/scripts/e2e/transcript-live-tail.tsx
@@ -198,6 +198,9 @@ globalThis.transcriptLiveTailProbe = async () => {
set({ messages });
set({ transcriptViews: { "live-tail": view }, runningSessions: {}, isRunning: false });
await frame();
+ assert(label()?.textContent === i18n.t("chat.processUnsettled") && !activeLabel(), "an unsettled streaming row has no completed outcome");
+ set({ messages: [user, tool, { ...answer, status: "complete" }] });
+ await frame();
assert(label()?.textContent === i18n.t("chat.processCompleted") && !activeLabel(), "only settled run state shows Finished");
set({ messages: [user, tool, { ...answer, status: "aborted" }] });
await frame();
diff --git a/scripts/e2e/transcript-status.tsx b/scripts/e2e/transcript-status.tsx
index 43488871d..fbd47164a 100644
--- a/scripts/e2e/transcript-status.tsx
+++ b/scripts/e2e/transcript-status.tsx
@@ -20,6 +20,9 @@ export async function transcriptStatusProbe() {
const root = createRoot(host);
const failures: string[] = [];
const checks: string[] = [];
+ // Layout boxes are rounded at fractional display scales. Keep the target
+ // spacing exact while allowing at most one physical pixel of quantization.
+ const pixelTolerance = 1 / window.devicePixelRatio;
const check = (value: unknown, label: string) => {
checks.push(label);
if (!value) failures.push(label);
@@ -134,7 +137,7 @@ export async function transcriptStatusProbe() {
const initialGap = userBubble && waitingLabel
? waitingLabel.getBoundingClientRect().top - userBubble.getBoundingClientRect().bottom
: Number.NaN;
- check(Math.abs(initialGap - 52) <= 0.01,
+ check(Math.abs(initialGap - 52) <= pixelTolerance,
`${mode}: initial wait retains the user action row (${initialGap}px)`);
await render({ messages: [{ ...user, revisionCount: 3, activeRevision: 2 }] });
@@ -194,7 +197,7 @@ export async function transcriptStatusProbe() {
fragment.getBoundingClientRect().bottom
: Number.NaN;
check(
- Math.abs(gap - 24) <= 0.01,
+ Math.abs(gap - 24) <= pixelTolerance,
`${mode}: status stays adjacent to partial answer (${gap}px)`,
);
await render({
@@ -291,6 +294,11 @@ export async function transcriptStatusProbe() {
],
isRunning: false,
});
+ const errorDeadline = performance.now() + 3000;
+ while (!host.textContent?.includes("Fixture error")) {
+ if (performance.now() >= errorDeadline) throw new Error("Failed turn did not commit its error text");
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+ }
check(
!host.querySelector(".message-row.assistant .message-actions"),
`${mode}: failed turn has no empty toolbar`,
diff --git a/tests/history-loading-scroll-test-cases.md b/tests/history-loading-scroll-test-cases.md
new file mode 100644
index 000000000..ec2edd121
--- /dev/null
+++ b/tests/history-loading-scroll-test-cases.md
@@ -0,0 +1,117 @@
+# Test cases: history loading keeps the reading viewport
+
+## 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.
+- Integration base: official `vastsa/PI-Desktop` main,
+ `9d86fc95b17780a820fec1890fabcabb1d0fa788`.
+- The original failing reproduction was verified on official main
+ `3f8c02c63e6ca6ed9ff0c9c570cfc4aeadea92cd`.
+- Run from this request checkout, not another installed Desktop build. Existing
+ compatible dependencies and a fresh Desktop build are required. The fixture
+ opens a separate Electron window, uses temporary data and synthetic messages,
+ and never reads real sessions or contacts a provider.
+- Close the fixture window to exit and remove its temporary profile.
+
+## Start the controlled manual fixture
+
+```bash
+node scripts/e2e-transcript-history-loading.mjs --manual
+```
+
+The toolbar deliberately holds a page until **Complete page** or **Fail page**
+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
+
+- Priority: High. Requirement: no jump to the beginning during loading.
+- Preconditions: start the fixture and click **Reset conversation**.
+- Steps:
+ 1. Click **Load earlier (hold)**. 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.
+- Postcondition: earlier messages are available; the viewport is unlocked.
+
+### TC-F-002: no-input loading has no vertical jitter
+
+- Priority: High. Requirement: no up/down movement without input.
+- Steps: reset, start a held page, leave the mouse still for five seconds, note
+ the visible turn, then click **Complete page** without using the wheel.
+- Expected: the turn does not move when the loading label appears, while the
+ page is pending, when rows mount, or when the label disappears. Repeating the
+ case must not produce alternating small jumps.
+
+### TC-ERR-001: a failed page releases input
+
+- Priority: High. Requirement: failure recovery does not leave a locked viewport.
+- Steps: reset, start a held page, click **Fail page**, then scroll downward.
+ Start another held page and click **Complete page**.
+- Expected: loading ends without an immediate automatic retry loop. Input is
+ 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
+
+- Priority: High. Requirement: existing navigation retains ownership.
+- 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.
+
+### TC-E-001: verify the 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.
+ 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.
+- 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 scripts/e2e-transcript-history-loading.mjs
+node scripts/e2e-transcript-reading-position.mjs
+node scripts/e2e-transcript-minimap-jump.mjs
+node scripts/e2e-transcript-disclosure-anchor.mjs
+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.
+
+| 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 |
+
+Automated Windows results do not establish every hardware/OS combination.
+Record the source revision, OS, display scaling and any remaining failing step
+when reporting a manual result. Do not substitute scrollbar-thumb movement for
+message stability: prepending legitimately changes the total scroll range.