Skip to content

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

fix(chat): stabilize transcript navigation and adaptive history loading

new-Beginner9eb23cb2b7e3
diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx
index cc773ce29..27fb46792 100644
--- a/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx
+++ b/apps/desktop/src/features/chat/transcript/AssistantTurnParts.tsx
@@ -3,7 +3,7 @@ import type { AgentActivity, UiMessage } from "@pi-desktop/shared";
import type { AssistantTurnPart } from "../../../lib/assistant-turns";
import type { SubagentOutcome, SubagentTiming } from "../../../lib/subagent-topology";
import { useAppStore } from "../../../stores/app-store";
-import { Markdown } from "../../../components/Markdown";
+import { TranscriptProse } from "./TranscriptProse";
import { useSmoothText } from "../../../hooks/useSmoothText";
import { useSlotSessionId } from "../../../plugins/renderer-slots/use-slots";
import { GenUiCards } from "../gen-ui/GenUiCard";
@@ -37,7 +37,7 @@ const SmoothMessageBubble = memo(function SmoothMessageBubble({ message, streami
className={`message-bubble assistant-turn-fragment${streaming ? " streaming" : ""}${showCursor ? " smooth-cursor" : ""}`}
data-message-id={message.id}
>
- {genUi.content ? <div className="prose-chat"><Markdown source={genUi.content} streaming={streaming} /></div> : null}
+ {genUi.content ? <TranscriptProse source={genUi.content} streaming={streaming} /> : null}
<GenUiCards references={genUi.references} sessionId={sessionId} remote={remote} />
{message.error ? <AssistantErrorMessage message={message} /> : null}
</div>
diff --git a/apps/desktop/src/features/chat/transcript/TranscriptProse.tsx b/apps/desktop/src/features/chat/transcript/TranscriptProse.tsx
new file mode 100644
index 000000000..fff1c986f
--- /dev/null
+++ b/apps/desktop/src/features/chat/transcript/TranscriptProse.tsx
@@ -0,0 +1,59 @@
+import { memo, useContext, useLayoutEffect, useRef, useState } from "react";
+import { Markdown } from "../../../components/Markdown";
+import { observeTranscriptContent } from "../../../lib/transcript-content-observer";
+import { shouldMountTranscriptContent } from "../../../lib/transcript-content-window";
+import { ScopeContext } from "./disclosure-scope";
+
+/** Keep the existing prose shell and message anchors while releasing its renderer. */
+export const TranscriptProse = memo(function TranscriptProse({ source, streaming }: {
+ source: string;
+ streaming: boolean;
+}) {
+ const elementRef = useRef<HTMLDivElement>(null);
+ const { visible } = useContext(ScopeContext);
+ const [window, setWindow] = useState({ source, mounted: true, height: 0 });
+ const mounted = visible && (streaming || window.source !== source || window.mounted);
+ const mountedRef = useRef(mounted);
+ useLayoutEffect(() => { mountedRef.current = mounted; });
+ useLayoutEffect(() => {
+ const element = elementRef.current;
+ const viewport = element?.closest<HTMLElement>(".thread-scroll");
+ if (!element || !viewport || streaming || !visible) return;
+ let measuredHeight: number | null = null;
+ let measuredWidth: number | null = null;
+ return observeTranscriptContent(element, () => {
+ if (!element.isConnected || viewport.clientHeight === 0) return;
+ const rect = element.getBoundingClientRect();
+ const viewportRect = viewport.getBoundingClientRect();
+ if (mountedRef.current && rect.height > 0) {
+ measuredHeight = rect.height;
+ measuredWidth = rect.width;
+ }
+ const selection = element.ownerDocument.getSelection();
+ const protectedContent = element.contains(element.ownerDocument.activeElement) ||
+ Boolean(selection && !selection.isCollapsed && selection.containsNode(element, true)) ||
+ Boolean(element.closest(".transcript-search-target"));
+ const next = shouldMountTranscriptContent({
+ top: rect.top - viewportRect.top,
+ bottom: rect.bottom - viewportRect.top,
+ viewportHeight: viewport.clientHeight,
+ width: rect.width,
+ measuredHeight,
+ measuredWidth,
+ mounted: mountedRef.current,
+ protected: protectedContent,
+ });
+ if (next !== mountedRef.current) {
+ setWindow({ source, mounted: next, height: measuredHeight ?? 0 });
+ }
+ });
+ }, [source, streaming, visible]);
+ return <div
+ ref={elementRef}
+ className="prose-chat"
+ data-transcript-content={mounted ? "mounted" : "placeholder"}
+ style={mounted ? undefined : { height: window.height }}
+ >
+ {mounted ? <Markdown source={source} streaming={streaming} /> : null}
+ </div>;
+});
diff --git a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts
index 81137a769..f8d314dc1 100644
--- a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts
+++ b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptHistoryPaging.ts
@@ -5,15 +5,12 @@ import {
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;
- background: boolean;
windowSize: number;
sourceHead?: string;
alignedHead?: string;
@@ -21,23 +18,20 @@ type Hold = {
top: number;
viewport: number;
scroller: HTMLDivElement;
- overflowY: string;
};
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. */
+/** Single-flight page IO and pre-paint anchoring follow the reader's newest
+ * position without blocking input. Cancelled IO cannot acquire a newer 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: (background: boolean) => void;
+ onStart: () => void;
onPosition: (top: number) => void;
onSettled: () => void;
}) {
@@ -45,6 +39,8 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, sou
const inFlightRef = useRef(false);
const frameRef = useRef(0);
const autoBlockedRef = useRef(false);
+ const latencyRef = useRef(250);
+ const readLatency = useCallback(() => latencyRef.current, []);
const sourceHeadRef = useRef(sourceHead);
sourceHeadRef.current = sourceHead;
const retry = useCallback(() => { autoBlockedRef.current = false; }, []);
@@ -54,8 +50,6 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, sou
callbacks.current = { onStart, onPosition, onSettled };
const dropHold = useCallback(() => {
- const held = holdRef.current;
- if (held && !held.background) held.scroller.style.overflowY = held.overflowY;
holdRef.current = null;
cancelAnimationFrame(frameRef.current);
frameRef.current = 0;
@@ -65,12 +59,11 @@ 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 (!held || !scroller || !content) return;
// Retain the same readable message across a gesture. Switching immediately
// to a newly exposed, estimated row lets its late layout move the text away.
held.position = { ...held.position, offset: held.position.offset - (scroller.scrollTop - held.top),
@@ -87,10 +80,8 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, sou
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;
- }
+ track();
+ if (!layoutChanged(held, sourceHeadRef.current)) return false;
const before = scroller.scrollTop;
restoreTranscriptReadingPosition(scroller, content, held.position);
held.height = scroller.scrollHeight;
@@ -102,25 +93,25 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, sou
return true;
}, [contentRef, scrollRef, track]);
- const run = useCallback((action: () => void | Promise<void>, windowSize: number, page = false, background = false) => {
+ 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;
- 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, background, windowSize,
+ const hold: Hold = { position, settled: false, stableFrames: 0, page, windowSize,
sourceHead: sourceHeadRef.current, alignedHead: sourceHeadRef.current,
height: scroller.scrollHeight, top: scroller.scrollTop, viewport: scroller.clientHeight,
- scroller, overflowY: scroller.style.overflowY };
+ scroller };
holdRef.current = hold; // Synchronous: two scroll events cannot start two pages.
- if (!background) scroller.style.overflowY = "hidden";
inFlightRef.current = true;
- callbacks.current.onStart(background);
+ callbacks.current.onStart();
setPhase(page ? "page" : "mount");
+ const startedAt = performance.now();
const finish = () => {
inFlightRef.current = false;
if (holdRef.current !== hold) return;
+ if (page) latencyRef.current = Math.min(2000, Math.max(latencyRef.current * 0.75, performance.now() - startedAt));
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.
@@ -187,24 +178,7 @@ export function useTranscriptHistoryPaging({ scrollRef, contentRef, visible, sou
return () => observer.disconnect();
}, [contentRef, restore, scrollRef]);
- useLayoutEffect(() => {
- const scroller = scrollRef.current;
- if (!scroller) return;
- const block = (event: Event) => {
- 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.
- 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, isLocked, scrollRef]);
+ useLayoutEffect(() => () => dropHold(), [dropHold]);
- return { loadingOlder: phase === "page", pending: phase !== "idle", run, restore, isHeld, isLocked, track, cancel, retry };
+ return { loadingOlder: phase === "page", pending: phase !== "idle", run, restore, isHeld, track, cancel, retry, readLatency };
}
diff --git a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
index 438a92883..2bacea480 100644
--- a/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
+++ b/apps/desktop/src/features/chat/transcript/hooks/useTranscriptScroll.ts
@@ -92,6 +92,7 @@ export function useTranscriptScroll({
const [savedReadingPosition] = useState(() => getTranscriptReadingPosition(sessionId));
const pinnedRef = useRef(savedReadingPosition?.pinned ?? true);
const lastScrollTopRef = useRef(0);
+ const lastScrollAtRef = useRef(-Infinity);
// Last offset sampled while the scroller had a real layout box. A hidden
// pane's `content-visibility: hidden` box reports `scrollTop === 0`, so the
// hide transition must restore this rather than the collapsed value.
@@ -193,14 +194,14 @@ export function useTranscriptScroll({
enterDisclosureReading,
recordScrollPosition,
);
- const startHistoryReading = useCallback((background: boolean) => {
+ const startHistoryReading = useCallback(() => {
releaseDisclosureAnchor();
- if (background) leaveFollow(); else releaseFollow();
- }, [leaveFollow, releaseDisclosureAnchor, releaseFollow]);
+ leaveFollow();
+ }, [leaveFollow, releaseDisclosureAnchor]);
const {
loadingOlder, pending: historyPending, run: preserveHistory, retry: retryHistoryPaging,
- restore: restoreHistoryAnchor, isHeld: isHistoryPaging, isLocked: isHistoryLocked,
- track: trackHistoryPosition, cancel: cancelHistoryPaging,
+ restore: restoreHistoryAnchor, isHeld: isHistoryPaging,
+ track: trackHistoryPosition, cancel: cancelHistoryPaging, readLatency: historyReadLatency,
} = useTranscriptHistoryPaging({
scrollRef, contentRef, visible: paneVisible, sourceHead: messages[0]?.id, onStart: startHistoryReading,
onPosition: recordScrollPosition, onSettled: rememberReadingPosition,
@@ -231,7 +232,6 @@ export function useTranscriptScroll({
// consumes belongs to that dock.
const markScrollGesture = useCallback(
(event: Event) => {
- 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,
@@ -252,7 +252,7 @@ export function useTranscriptScroll({
// Real input takes the viewport back from a held disclosure position.
releaseDisclosureAnchor();
},
- [cancelReadingPosition, isHistoryLocked, latestNavigation, leaveFollow, releaseDisclosureAnchor, rememberReadingPosition, retryHistoryPaging],
+ [cancelReadingPosition, latestNavigation, leaveFollow, releaseDisclosureAnchor, rememberReadingPosition, retryHistoryPaging],
);
useEffect(() => {
@@ -380,10 +380,10 @@ export function useTranscriptScroll({
useEffect(() => cancelFollowScroll, [cancelFollowScroll]);
- const loadOlder = useCallback((background = false) => {
+ const loadOlder = useCallback(() => {
if (!paneVisibleRef.current) return;
if (!hasMoreBefore || !onLoadOlder) return;
- preserveHistory(onLoadOlder, windowSize, true, background);
+ preserveHistory(onLoadOlder, windowSize, true);
}, [hasMoreBefore, onLoadOlder, preserveHistory, windowSize]);
/**
@@ -392,15 +392,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((background = false) => {
+ const reachTop = useCallback(() => {
const el = scrollRef.current;
if (!el || isHistoryPaging()) return;
const grown = growTranscriptWindow(windowSize, historyLengthRef.current);
if (grown !== windowSize) {
- preserveHistory(() => setWindowSize(grown), windowSize, false, background);
+ preserveHistory(() => setWindowSize(grown), windowSize);
return;
}
- loadOlder(background);
+ loadOlder();
}, [isHistoryPaging, loadOlder, preserveHistory, windowSize]);
@@ -409,8 +409,12 @@ export function useTranscriptScroll({
const handleScroll = useCallback(() => {
const el = scrollRef.current;
if (!el) return;
+ const now = performance.now();
+ const elapsed = now - lastScrollAtRef.current;
+ lastScrollAtRef.current = now;
+ const upwardSpeed = Math.max(0, lastScrollTopRef.current - el.scrollTop) /
+ (elapsed > 0 && elapsed <= 200 ? Math.max(8, elapsed) : 16);
if (latestNavigation.isActive()) { recordScrollPosition(el.scrollTop); return; }
- if (isHistoryLocked() && restoreHistoryAnchor()) return;
trackHistoryPosition();
if (paneVisibleRef.current && transcriptHasLayout(el)) {
lastLaidOutScrollTopRef.current = el.scrollTop;
@@ -436,8 +440,8 @@ export function useTranscriptScroll({
) {
reachTop();
} else if (paneVisibleRef.current && gesturing && el.scrollTop < lastScrollTopRef.current &&
- isHistoryPrefetchPosition(el)) {
- reachTop(true);
+ isHistoryPrefetchPosition(el, false, { upwardSpeed, latencyMs: historyReadLatency() })) {
+ reachTop();
}
if (readingWindow) {
pinnedRef.current = false;
@@ -484,7 +488,7 @@ export function useTranscriptScroll({
setShowJump(transition.showJump);
}
rememberReadingPosition();
- }, [cancelFollowScroll, isHistoryLocked, latestNavigation, reachTop, readingPositionPendingRef, readingWindow, recordScrollPosition, rememberReadingPosition, restoreHistoryAnchor, scheduleFollowScroll, trackHistoryPosition]);
+ }, [cancelFollowScroll, historyReadLatency, latestNavigation, reachTop, readingPositionPendingRef, readingWindow, recordScrollPosition, rememberReadingPosition, 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.
diff --git a/apps/desktop/src/lib/transcript-content-observer.ts b/apps/desktop/src/lib/transcript-content-observer.ts
new file mode 100644
index 000000000..f26c42cbd
--- /dev/null
+++ b/apps/desktop/src/lib/transcript-content-observer.ts
@@ -0,0 +1,59 @@
+type ContentListener = () => void;
+
+/** One read batch per viewport frame, shared by its measured content shells. */
+class TranscriptContentObserver {
+ private readonly listeners = new Map<HTMLElement, ContentListener>();
+ private readonly resize: ResizeObserver;
+ private frame: number | null = null;
+
+ private readonly viewport: HTMLElement;
+
+ constructor(viewport: HTMLElement) {
+ this.viewport = viewport;
+ this.resize = new ResizeObserver(this.schedule);
+ this.resize.observe(viewport);
+ viewport.addEventListener("scroll", this.schedule, { passive: true });
+ viewport.addEventListener("focusin", this.schedule);
+ viewport.addEventListener("focusout", this.schedule);
+ viewport.ownerDocument.addEventListener("selectionchange", this.schedule);
+ }
+
+ private readonly schedule = () => {
+ if (this.frame !== null) return;
+ this.frame = requestAnimationFrame(() => {
+ this.frame = null;
+ for (const listener of this.listeners.values()) listener();
+ });
+ };
+
+ add(element: HTMLElement, listener: ContentListener): () => void {
+ this.listeners.set(element, listener);
+ this.resize.observe(element);
+ this.schedule();
+ return () => {
+ this.resize.unobserve(element);
+ this.listeners.delete(element);
+ if (this.listeners.size !== 0) return;
+ this.resize.disconnect();
+ this.viewport.removeEventListener("scroll", this.schedule);
+ this.viewport.removeEventListener("focusin", this.schedule);
+ this.viewport.removeEventListener("focusout", this.schedule);
+ this.viewport.ownerDocument.removeEventListener("selectionchange", this.schedule);
+ if (this.frame !== null) cancelAnimationFrame(this.frame);
+ observers.delete(this.viewport);
+ };
+ }
+}
+
+const observers = new WeakMap<HTMLElement, TranscriptContentObserver>();
+
+export function observeTranscriptContent(element: HTMLElement, listener: ContentListener): () => void {
+ const viewport = element.closest<HTMLElement>(".thread-scroll");
+ if (!viewport) return () => {};
+ let observer = observers.get(viewport);
+ if (!observer) {
+ observer = new TranscriptContentObserver(viewport);
+ observers.set(viewport, observer);
+ }
+ return observer.add(element, listener);
+}
diff --git a/apps/desktop/src/lib/transcript-content-window.ts b/apps/desktop/src/lib/transcript-content-window.ts
new file mode 100644
index 000000000..5c793ca25
--- /dev/null
+++ b/apps/desktop/src/lib/transcript-content-window.ts
@@ -0,0 +1,33 @@
+/** Geometry is relative to the scroll viewport, not the document. */
+export interface TranscriptContentGeometry {
+ top: number;
+ bottom: number;
+ viewportHeight: number;
+ width: number;
+ measuredHeight: number | null;
+ measuredWidth: number | null;
+ mounted: boolean;
+ /** Streaming, selection, focus, or an explicit navigation target. */
+ protected: boolean;
+}
+
+/**
+ * Retain addressable message shells while releasing expensive offscreen content.
+ * Only a measurement at the current width is safe to use as a placeholder.
+ * Different entry/exit buffers prevent churn near a virtualization boundary.
+ * This policy does not evict history data or change the pagination cursor.
+ */
+export function shouldMountTranscriptContent(geometry: TranscriptContentGeometry): boolean {
+ if (geometry.protected) return true;
+ if (geometry.viewportHeight === 0) return geometry.mounted;
+ const { top, bottom, width, measuredHeight, measuredWidth, viewportHeight } = geometry;
+ if (
+ !Number.isFinite(top) || !Number.isFinite(bottom) || bottom < top ||
+ !Number.isFinite(viewportHeight) || viewportHeight < 0 ||
+ !Number.isFinite(width) || width <= 0 ||
+ measuredHeight === null || !Number.isFinite(measuredHeight) || measuredHeight < 0 ||
+ measuredWidth === null || !Number.isFinite(measuredWidth) || measuredWidth !== width
+ ) return true;
+ const buffer = viewportHeight * (geometry.mounted ? 5 : 3);
+ return bottom >= -buffer && top <= viewportHeight + buffer;
+}
diff --git a/apps/desktop/src/lib/transcript-latest-navigation.ts b/apps/desktop/src/lib/transcript-latest-navigation.ts
index 722420d3b..49206b108 100644
--- a/apps/desktop/src/lib/transcript-latest-navigation.ts
+++ b/apps/desktop/src/lib/transcript-latest-navigation.ts
@@ -7,7 +7,7 @@ type ScrollPort = {
now: () => number;
reducedMotion: () => boolean;
};
-type Navigation = { from: number; startedAt: number; duration: number; lastTop: number; arrive: () => void };
+type Navigation = { distance: number; startedAt: number; duration: number; arrive: () => void };
/** One viewport owner for a short, interruptible trip through mounted content. */
export function createTranscriptLatestNavigation(port: ScrollPort) {
@@ -27,7 +27,7 @@ export function createTranscriptLatestNavigation(port: ScrollPort) {
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,
+ const navigation: Navigation = { distance,
startedAt: port.now(), duration: Math.min(420, Math.max(180, distance / 30)), arrive };
current = navigation;
const advance = (now: number) => {
@@ -38,10 +38,10 @@ export function createTranscriptLatestNavigation(port: ScrollPort) {
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;
+ // Animate remaining viewport distance, not an absolute document offset.
+ // Lazy layout above the reader shifts both the target and the visible
+ // content; compensate that shift in full rather than easing it as motion.
+ const top = Math.max(0, bottom - navigation.distance * (1 - eased));
port.move(top);
if (progress === 1) {
current = undefined;
diff --git a/apps/desktop/src/lib/transcript-scroll.ts b/apps/desktop/src/lib/transcript-scroll.ts
index 691cd902c..b6be0c302 100644
--- a/apps/desktop/src/lib/transcript-scroll.ts
+++ b/apps/desktop/src/lib/transcript-scroll.ts
@@ -57,9 +57,17 @@ export function isHistoryRevealPosition(
export function isHistoryPrefetchPosition(
geometry: TranscriptScrollerGeometry,
pinned = false,
+ motion?: { upwardSpeed: number; latencyMs: number },
): boolean {
- return !pinned && transcriptHasLayout(geometry) &&
- geometry.scrollTop <= Math.min(2400, Math.max(HISTORY_REVEAL_THRESHOLD_PX, geometry.clientHeight * 3));
+ if (pinned || !transcriptHasLayout(geometry)) return false;
+ const baseline = Math.min(2400, Math.max(HISTORY_REVEAL_THRESHOLD_PX, geometry.clientHeight * 3));
+ const speed = motion && Number.isFinite(motion.upwardSpeed) ? Math.max(0, motion.upwardSpeed) : 0;
+ const latency = motion && Number.isFinite(motion.latencyMs) ? Math.max(0, motion.latencyMs) : 250;
+ // Reserve a layout/commit margin as well as the measured read time. Neither
+ // a slow read nor an extreme gesture may turn this into eager full loading.
+ const ceiling = Math.max(baseline, Math.min(12000, geometry.clientHeight * 12));
+ const lead = Math.min(ceiling, Math.max(baseline, speed * (latency + 150)));
+ return geometry.scrollTop <= lead;
}
export type TranscriptScrollInput = {
diff --git a/apps/desktop/test/manual-transcript-desktop.test.mjs b/apps/desktop/test/manual-transcript-desktop.test.mjs
new file mode 100644
index 000000000..c2552a238
--- /dev/null
+++ b/apps/desktop/test/manual-transcript-desktop.test.mjs
@@ -0,0 +1,34 @@
+import assert from "node:assert/strict";
+import { EventEmitter } from "node:events";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+
+// Exercise the launcher failure path without opening another Desktop instance.
+test("failed Desktop readiness closes the owned child and saves diagnostics", async () => {
+ const source = await readFile(new URL("../../../scripts/manual-transcript-desktop.mjs", import.meta.url), "utf8");
+ const body = source.slice(source.indexOf("const child = spawn("));
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.pid = 123;
+ let killed = false;
+ child.kill = () => { killed = true; child.emit("close", 1); return true; };
+ const files = [];
+ const process = { argv: [], exitCode: 0 };
+ const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
+ const run = new AsyncFunction("spawn", "electronBinary", "port", "join", "directory", "appDir", "env", "once", "writeFile", "sessions", "waitFor", "process", "console", body);
+ let resolveClose;
+ const closed = new Promise(resolve => { resolveClose = resolve; });
+ child.on("close", resolveClose);
+ const running = run(() => child, "electron", 1, (...parts) => parts.join("/"), "fixture", "app", {},
+ () => closed, async (path) => { files.push(path); }, [],
+ async () => { throw new Error("Synthetic readiness failure"); }, process, { error() {}, log() {} });
+ // Flush the immediate readiness rejection; no wall-clock timeout or real process.
+ for (let i = 0; i < 10; i++) await Promise.resolve();
+ const cleanedUp = killed;
+ if (!killed) child.emit("close", 1);
+ await running;
+ assert.equal(cleanedUp, true, "failed readiness must terminate its child before awaiting close");
+ assert.equal(process.exitCode, 1);
+ assert.ok(files.includes("fixture/desktop.log"));
+});
diff --git a/apps/desktop/test/transcript-content-observer.test.mjs b/apps/desktop/test/transcript-content-observer.test.mjs
new file mode 100644
index 000000000..3bfbaf41a
--- /dev/null
+++ b/apps/desktop/test/transcript-content-observer.test.mjs
@@ -0,0 +1,59 @@
+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 { observeTranscriptContent } = await import("../src/lib/transcript-content-observer.ts");
+
+test("content observers share viewport work and dispose after the last shell", () => {
+ const original = { ResizeObserver: globalThis.ResizeObserver,
+ requestAnimationFrame: globalThis.requestAnimationFrame, cancelAnimationFrame: globalThis.cancelAnimationFrame };
+ const frames = new Map();
+ const observers = [];
+ let sequence = 0;
+ globalThis.requestAnimationFrame = callback => { frames.set(++sequence, callback); return sequence; };
+ globalThis.cancelAnimationFrame = id => frames.delete(id);
+ globalThis.ResizeObserver = class {
+ observed = new Set();
+ constructor(callback) { this.callback = callback; observers.push(this); }
+ observe(element) { this.observed.add(element); }
+ unobserve(element) { this.observed.delete(element); }
+ disconnect() { this.observed.clear(); }
+ };
+ try {
+ const viewport = new EventTarget();
+ viewport.ownerDocument = new EventTarget();
+ const first = { closest: () => viewport };
+ const second = { closest: () => viewport };
+ let firstCalls = 0;
+ let secondCalls = 0;
+ const stopFirst = observeTranscriptContent(first, () => firstCalls++);
+ const stopSecond = observeTranscriptContent(second, () => secondCalls++);
+ assert.equal(observers.length, 1);
+ assert.equal(observers[0].observed.size, 3);
+ viewport.dispatchEvent(new Event("scroll"));
+ viewport.dispatchEvent(new Event("focusin"));
+ observers[0].callback();
+ assert.equal(frames.size, 1);
+ const callbacks = [...frames.values()]; frames.clear();
+ callbacks.forEach(callback => callback());
+ assert.equal(firstCalls, 1); assert.equal(secondCalls, 1);
+ stopFirst();
+ viewport.dispatchEvent(new Event("scroll"));
+ assert.equal(frames.size, 1);
+ stopSecond();
+ assert.equal(frames.size, 0);
+ assert.equal(observers[0].observed.size, 0);
+ viewport.dispatchEvent(new Event("scroll"));
+ viewport.ownerDocument.dispatchEvent(new Event("selectionchange"));
+ assert.equal(frames.size, 0);
+ const stopRemount = observeTranscriptContent(first, () => firstCalls++);
+ assert.equal(observers.length, 2);
+ stopRemount();
+ assert.equal(frames.size, 0);
+ } finally { Object.assign(globalThis, original); }
+});
+
+test("content outside a transcript does not allocate viewport resources", () => {
+ const stop = observeTranscriptContent({ closest: () => null }, () => assert.fail("unexpected callback"));
+ stop();
+});
diff --git a/apps/desktop/test/transcript-content-window.test.mjs b/apps/desktop/test/transcript-content-window.test.mjs
new file mode 100644
index 000000000..760daad2a
--- /dev/null
+++ b/apps/desktop/test/transcript-content-window.test.mjs
@@ -0,0 +1,57 @@
+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 { shouldMountTranscriptContent } = await import("../src/lib/transcript-content-window.ts");
+
+const sample = (changes = {}) => ({
+ top: 10000, bottom: 10200, viewportHeight: 600,
+ measuredHeight: 200, measuredWidth: 800, width: 800,
+ mounted: true, protected: false, ...changes,
+});
+
+test("measured content is released on both sides of the viewport", () => {
+ assert.equal(shouldMountTranscriptContent(sample()), false);
+ assert.equal(shouldMountTranscriptContent(sample({ top: -10000, bottom: -9800 })), false);
+});
+
+test("enter and exit buffers prevent boundary mount oscillation", () => {
+ assert.equal(shouldMountTranscriptContent(sample({ top: 2500, bottom: 2700 })), true);
+ assert.equal(shouldMountTranscriptContent(sample({ top: 2500, bottom: 2700, mounted: false })), false);
+ assert.equal(shouldMountTranscriptContent(sample({ top: 2300, bottom: 2500, mounted: false })), true);
+ assert.equal(shouldMountTranscriptContent(sample({ top: -1900, bottom: -1700, mounted: false })), true);
+});
+
+test("a long answer intersecting the viewport is never evicted by its start position", () => {
+ assert.equal(shouldMountTranscriptContent(sample({ top: -10000, bottom: 200 })), true);
+});
+
+test("unknown, resized, or invalid geometry cannot become a stale placeholder", () => {
+ for (const changes of [
+ { measuredHeight: null }, { measuredWidth: null }, { width: 700 },
+ { measuredHeight: NaN }, { measuredHeight: -1 }, { measuredWidth: Infinity },
+ { width: 0 }, { top: NaN }, { bottom: Infinity }, { top: 10201 },
+ ]) assert.equal(shouldMountTranscriptContent(sample(changes)), true, JSON.stringify(changes));
+});
+
+test("streaming, focused, selected, and navigation-owned content stays mounted", () => {
+ assert.equal(shouldMountTranscriptContent(sample({ protected: true })), true);
+});
+
+test("a hidden retained pane does not evict its existing contents", () => {
+ assert.equal(shouldMountTranscriptContent(sample({ viewportHeight: 0 })), true);
+ assert.equal(shouldMountTranscriptContent(sample({ viewportHeight: 0, mounted: false })), false);
+});
+
+test("traversing a measured transcript does not accumulate mounted content", () => {
+ let mounted = Array.from({ length: 1000 }, () => true);
+ for (const scrollTop of [0, 12000, 60000, 120000, 180000, 60000, 0]) {
+ mounted = mounted.map((previous, index) => shouldMountTranscriptContent(sample({
+ top: index * 200 - scrollTop, bottom: (index + 1) * 200 - scrollTop,
+ mounted: previous,
+ })));
+ assert(mounted.filter(Boolean).length <= 34);
+ const visible = Math.floor(scrollTop / 200);
+ assert(mounted.slice(visible, visible + 3).every(Boolean));
+ }
+});
diff --git a/apps/desktop/test/transcript-latest-navigation.test.mjs b/apps/desktop/test/transcript-latest-navigation.test.mjs
index 2c9b283f4..d46713285 100644
--- a/apps/desktop/test/transcript-latest-navigation.test.mjs
+++ b/apps/desktop/test/transcript-latest-navigation.test.mjs
@@ -86,3 +86,20 @@ test("reduced motion reaches bottom synchronously", () => {
assert.equal(f.arrivals(), 1);
assert.equal(f.frames.size, 0);
});
+
+for (const delta of [2400, -1200]) {
+ test(`layout above the reader (${delta}px) does not alter latest's visible trajectory`, () => {
+ const baseline = fixture();
+ const changed = fixture();
+ baseline.start(); changed.start();
+ baseline.advance(); changed.advance();
+ changed.box.scrollHeight += delta;
+ baseline.advance(); changed.advance();
+ const remaining = f => f.box.scrollHeight - f.box.clientHeight - f.box.scrollTop;
+ assert(Math.abs(remaining(changed) - remaining(baseline)) <= 1,
+ `layout must be compensated, not interpolated: ${remaining(changed)} vs ${remaining(baseline)}`);
+ baseline.finish(); changed.finish();
+ assert.equal(remaining(changed), 0);
+ assert.equal(changed.arrivals(), 1);
+ });
+}
diff --git a/apps/desktop/test/transcript-scroll.test.mjs b/apps/desktop/test/transcript-scroll.test.mjs
index 96bda49a5..18a532464 100644
--- a/apps/desktop/test/transcript-scroll.test.mjs
+++ b/apps/desktop/test/transcript-scroll.test.mjs
@@ -218,3 +218,20 @@ test("history prefetch begins within three viewports but stays bounded", () => {
assert.equal(isHistoryPrefetchPosition(box, true), false);
assert.equal(isHistoryPrefetchPosition({ ...box, clientHeight: 0 }), false);
});
+
+test("fast upward travel prefetches before the fixed three-screen band", () => {
+ const geometry = { scrollTop: 4000, scrollHeight: 20000, clientHeight: 800 };
+ assert.equal(isHistoryPrefetchPosition(geometry, false, { upwardSpeed: 12, latencyMs: 300 }), true);
+ assert.equal(isHistoryPrefetchPosition(geometry, false, { upwardSpeed: 0, latencyMs: 300 }), false);
+ assert.equal(isHistoryPrefetchPosition(geometry, true, { upwardSpeed: 12, latencyMs: 300 }), false);
+});
+
+test("adaptive prefetch uses read latency but remains finitely bounded", () => {
+ const geometry = { scrollTop: 6000, scrollHeight: 30000, clientHeight: 800 };
+ assert.equal(isHistoryPrefetchPosition(geometry, false, { upwardSpeed: 10, latencyMs: 100 }), false);
+ assert.equal(isHistoryPrefetchPosition(geometry, false, { upwardSpeed: 10, latencyMs: 600 }), true);
+ assert.equal(isHistoryPrefetchPosition({ ...geometry, scrollTop: 10000 }, false,
+ { upwardSpeed: 1000, latencyMs: 10000 }), false);
+ assert.equal(isHistoryPrefetchPosition({ ...geometry, clientHeight: 0 }, false,
+ { upwardSpeed: 1000, latencyMs: 10000 }), false);
+});
diff --git a/apps/desktop/test/transcript-window.test.mjs b/apps/desktop/test/transcript-window.test.mjs
index 07616805a..66fcd0be8 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\(\(background = false\) => \{([\s\S]*?)\n \}, \[[^\]]*\]\);/,
+ /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, /preserveHistory\(\(\) => setWindowSize\(grown\), windowSize, false, background\)/);
+ assert.match(reachTop, /preserveHistory\(\(\) => setWindowSize\(grown\), windowSize\)/);
assert.match(reachTop, /setWindowSize\(grown\)/);
- assert.match(reachTop, /loadOlder\(background\)/);
+ assert.match(reachTop, /loadOlder\(\)/);
});
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, background\)/);
+ assert.match(transcript, /preserveHistory\(onLoadOlder, windowSize, true\)/);
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 a4f5b8f12..a70debb3e 100644
--- a/docs/adr/0130-bounded-mounted-transcript-window.md
+++ b/docs/adr/0130-bounded-mounted-transcript-window.md
@@ -50,10 +50,10 @@ reference-equal, and that runs on every streamed token.
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
+ newest visible message anchor without hiding overflow or discarding input,
+ including the hard-edge (`<= 120px`), explicit continuation, and underfilled
+ top-boundary fallback. The moving anchor remains owned through IO and three
+ stable layout frames; it never owns user input. 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.
@@ -97,12 +97,14 @@ and the `session.get` window contract are untouched.
- **Full virtualization with measured row offsets:** rejected for now. Transcript
rows have highly variable, content-dependent heights that change after mount
(streaming, disclosure toggles, lazy Mermaid), so a measured-offset virtualizer
- needs a height cache and invalidation for all of it. The trailing window gets
- the same memory ceiling with a fraction of the moving parts, and the existing
- pinned-follow and prepend-anchor logic keeps working unchanged.
-- **Unmount by distance from the viewport in both directions:** rejected. The
- transcript is read from the bottom and streams at the bottom; withholding rows
- *below* the viewport would fight pinned-follow for no benefit.
+ needs a height cache and invalidation for all of it. The trailing window
+ reduces initial mounting with fewer moving parts, but does not provide a
+ lifetime memory ceiling after repeated backward expansion. Measured prose
+ shells add bidirectional renderer recycling without replacing row navigation.
+- **Unmount whole rows by distance in both directions:** rejected for the
+ original row window because removing addressable geometry interferes with
+ pinned-follow. Measured prose recycling now releases only renderer children,
+ retaining equal-height shells and the streaming tail.
- **Cap the loaded history instead, discarding older pages from the store:**
rejected. It would make paging non-monotonic and re-fetch rows the user just
scrolled past, and the store's transcript is also read by the outcome card and
@@ -115,9 +117,11 @@ and the `session.get` window contract are untouched.
## Consequences
-- Retained renderer memory for a transcript is bounded by the window rather than
- by how far back the user has scrolled, and per-frame reconciliation during
- streaming is bounded with it.
+- The initial row window limits cold mounting, but expands as the reader moves
+ backward. It is not a bound on retained message data or addressable row shells.
+ Measured assistant prose additionally releases offscreen Markdown renderers in
+ both directions; this limits expensive mounted content, not total session
+ memory. A single intersecting answer and protected content remain mounted.
- Upward travel through a long session costs one frame per growth step before
pagination resumes. Each step is a mount of already-loaded rows, so it does not
add IPC.
@@ -131,18 +135,22 @@ and the `session.get` window contract are untouched.
## 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.
+- **Adaptive, gesture-driven ahead-loading:** The base lead is
+ `min(2400px, max(120px, 3 * clientHeight))`. Upward speed in pixels/ms times
+ measured page latency plus a `150ms` commit margin can increase that lead,
+ capped at `max(base, min(12000px, 12 * clientHeight))`. Single-flight
+ escalation still mounts cached withheld rows before requesting a Host page.
+ No early-threshold observer drains pages at rest. All escalation paths,
+ including the hard edge and explicit continuation, leave overflow and input
+ untouched. The actual-message anchor subtracts observed scroll displacement
+ before correcting layout, preserving compositor movement even when lazy rows
+ lay out before their scroll event. A transaction settles after three stable
+ layout frames. Failed or empty reads wait for new input or an explicit retry.
+- **Layout-independent latest trajectory:** Animate remaining distance to the
+ current bottom, not an absolute initial scroll coordinate. Height changes
+ above the reader must not be multiplied into the remaining animation. Tests
+ separate legitimate final travel from history-to-live commit drift and use
+ nonempty layout-complete samples for delayed-layout stability (`<= 2px`).
- **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
@@ -158,6 +166,16 @@ and the `session.get` window contract are untouched.
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.
+- **Measured prose window:** `TranscriptProse` preserves the existing prose and
+ message shells. At the current width, measured offscreen prose becomes an
+ equal-height placeholder beyond five viewport heights; it remounts within
+ three. Streaming, focused, selected, and search-target prose stays mounted.
+ Missing measurements or a changed width require rendering again rather than
+ guessing a height. Explicitly collapsed disclosure scopes release their
+ Markdown without changing stored disclosure choices. One observer and frame
+ scheduler per viewport handles scroll, resize, focus, and selection, and is
+ disposed when its last shell leaves.
+- **Cache invariants:** Message, page, mounted-row-window, recent snapshot, and
+ retained session-pane data caches are unchanged. There is no idle TTL or
+ session-data reclamation; viewport-driven Markdown unmounting is independent
+ of those caches and does not initiate history reads.
diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.md
index d07429321..a774779c1 100644
--- a/docs/spec/04-ux/09-interaction-patterns.md
+++ b/docs/spec/04-ux/09-interaction-patterns.md
@@ -1635,28 +1635,34 @@ Project drag/drop follows these patterns:
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
+ and retained session-pane data caches remain unchanged, with no idle TTL or
+ session-data reclamation.
+- Assistant prose may release its Markdown renderer outside a five-screen
+ retention buffer and restore it inside a three-screen entry buffer, keeping
+ measured-height message/prose shells. Measurements must match the current
+ width; unknown geometry is rendered, not estimated. Streaming, focus,
+ selection, and search targets protect mounted content. Collapsed disclosure
+ scopes release their prose without losing explicit disclosure choices.
+ This bounds expensive offscreen prose, not retained data, row shells, or the
+ size of a single intersecting answer; it never initiates a history request.
+- A real upward scroll gesture starts ahead-loading within a base lead of
+ `min(2400px, max(120px, 3 * clientHeight))`. Upward speed times measured read
+ latency plus `150ms` can increase the lead, capped at
+ `max(base, min(12000px, 12 * clientHeight))`. Cached history mounts before Host
+ IO; requests stay single-flight. The actual-message anchor tracks user
+ displacement and corrects prepend/layout changes before paint.
+- All paging paths leave `overflow-y` and input untouched, including the
+ `<= 120px` hard edge, explicit earlier-history actions, and the underfilled
+ top-boundary observer. Wheel/trackpad, touch and keyboard input continue
+ through IO and the three stable layout frames used for settlement. Nested
+ scroll owners, editable fields, and title activation retain their own input.
+ The loading label keeps identical layout space when hidden; 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.
+ a late page cannot reclaim that navigation. A failed or empty page ends the
+ transaction and waits for a new scroll gesture or explicit earlier-history
+ action before retrying. Requests remain single-flight 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
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 7a0131836..82363b783 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -13544,9 +13544,9 @@ 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. 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.
+ 1. Scroll upward into the adaptive ahead-loading band (base three screens,
+ at most twelve screens or `12000px`) while holding Host page IO; continue
+ scrolling during IO, then complete the page. Repeat from `4000px` at speed.
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
@@ -13563,12 +13563,12 @@ This test plan spec is accepted when:
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
+ early-threshold observer or eager draining at rest. The `<= 120px` hard edge,
+ explicit earlier-history action, and underfilled observer use the same moving
+ anchor without locking overflow or discarding input. Native wheel movement
+ must occur during IO, with insertion preserving the resulting reading point.
+ Nested scrolling, editable fields and title activation remain independent.
+ 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
@@ -13597,11 +13597,28 @@ This test plan spec is accepted when:
native browser smooth travel across the prefetch threshold, resuming follow
during pending IO, press-only interruption plus remount, delayed failed search,
focused and restored disjoint ranges (no automatic forward reads), stream
- growth/completion, hide/unmount, and reduced-motion media emulation. Empty
- layout viewports are checked after layout and before paint, not before lazy
- rows have had their layout opportunity. Only external Host IPC is controlled;
+ growth/completion, hide/unmount, and reduced-motion media emulation. An extra
+ latest case changes height above the reader by `2400px`; unit cases also shrink
+ it by `1200px`. Separate final animation travel from history-release drift.
+ Delayed-layout checks require nonempty post-layout/prepaint samples within
+ `2px`, retaining pre-layout rAF diagnostics rather than treating them as paint.
+ Only external Host IPC is controlled;
the ordinary-motion cases still require intermediate frames. Manual procedures:
`tests/history-loading-scroll-test-cases.md`.
+ The production `SessionPane` resource journey opens collapsed process groups,
+ traverses both ends and the middle, and checks measured prose recycling plus
+ restoration of visible content without additional history requests. A separate
+ variant includes a 1,600-paragraph final answer. `--manual-smoke` drives the
+ manual toolbar through two 100-message pages and reset, sending 24 native
+ wheel events in each direction per pending page; directional movement,
+ single-flight requests, and frame-gap p95 <= 100ms are checked. This is a
+ measured fixture budget, not a universal zero-latency guarantee.
+ `node scripts/manual-transcript-desktop.mjs --interaction-smoke` complements
+ this with the complete product shell and real Host database: native upward
+ wheel input crosses the initial 100-message page without mounting all 1,000
+ messages, then the actual latest button reaches the bottom with nonblank
+ sampled frames and <=2px tail drift during 600ms after arrival. The isolated
+ instance confirms the application's normal quit dialog and exits.
- **Specs linked**: `04-ux/09-interaction-patterns.md` §2.2 / §9.1 / §10.4, ADR 0130.
- **Acceptance**: C (conversation), Quality.
- **Status**: Automated Electron fixture and unit regressions implemented; run
diff --git a/scripts/README.md b/scripts/README.md
index 1ace2bb2b..f40e1f748 100644
--- a/scripts/README.md
+++ b/scripts/README.md
@@ -63,7 +63,8 @@ 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 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-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), adaptive speed/latency lead and unlocked hard-edge 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 1,000-message synthetic conversation (40 initially loaded, 100 per page) with page-complete/fail controls and request status; `--manual-smoke` verifies toolbar paging/reset and bidirectional native-wheel frame gaps; see [manual cases](../tests/history-loading-scroll-test-cases.md) |
+| `manual-transcript-desktop.mjs` | `node scripts/manual-transcript-desktop.mjs [--smoke\|--interaction-smoke]` | Complete PI-Desktop sidebar/chat/Composer with scratch-isolated Host data and 1,000-message plus long-answer sessions. `--smoke` checks readiness; `--interaction-smoke` crosses a real Host page with native wheel input and checks the actual latest button, nonblank navigation and <=2px arrival drift. Automated modes confirm normal application quit; no provider is configured |
| `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 92387ea57..8962806ce 100644
--- a/scripts/e2e-transcript-history-loading.mjs
+++ b/scripts/e2e-transcript-history-loading.mjs
@@ -11,6 +11,7 @@ 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 manualSmoke = process.argv.includes("--manual-smoke");
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")],
@@ -48,17 +49,62 @@ app.whenReady().then(async () => {
};
win.focus();
try {
- await win.loadFile(require('node:path').join(__dirname, 'index.html'));
+ await win.loadFile(require('node:path').join(__dirname, 'index.html'), { query: ${JSON.stringify(manual || manualSmoke ? { manual: "1" } : {})} });
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()})');
console.log('HISTORY_MOTION ' + await js('JSON.stringify({ reduced: matchMedia("(prefers-reduced-motion: reduce)").matches })'));
if (${manual}) return;
+ if (${manualSmoke}) {
+ const click = label => { console.log('MANUAL_CLICK ' + label); return js('Array.from(document.querySelectorAll("nav button")).find(button => button.textContent === ' + JSON.stringify(label) + ').click()'); };
+ const wait = expression => js('new Promise((resolve,reject)=>{const end=performance.now()+8000;const check=()=>{if(' + expression + ')resolve();else if(performance.now()>end)reject(new Error("manual control did not settle"));else requestAnimationFrame(check)};check()})');
+ await wait('document.querySelector("#history-manual-status").textContent.includes("40 of 1000")');
+ for (const count of [140, 240]) {
+ await click('Load earlier (hold)');
+ await wait('globalThis.historyLoadingFixture.inspect().busy');
+ for (const deltaY of [-120, 120]) {
+ const before = await call('inspect()');
+ await js('globalThis.manualFrameProbe = { gaps: [], last: performance.now(), active: true }; requestAnimationFrame(function sample(now) { const p = globalThis.manualFrameProbe; if (!p.active) return; p.gaps.push(now - p.last); p.last = now; requestAnimationFrame(sample); })');
+ win.webContents.sendInputEvent({ type: 'mouseMove', x: before.x, y: before.y });
+ for (let step = 0; step < 24; step++) {
+ win.webContents.sendInputEvent({ type: 'mouseWheel', x: before.x, y: before.y, deltaY, deltaX: 0, canScroll: true });
+ await js('new Promise(resolve => requestAnimationFrame(resolve))');
+ }
+ await call('frames()');
+ const after = await call('inspect()');
+ const gaps = await js('globalThis.manualFrameProbe.active = false; globalThis.manualFrameProbe.gaps');
+ const sorted = gaps.filter(value => value > 0).sort((a, b) => a - b);
+ assert(sorted.length >= 20, 'native scrolling did not produce enough frame samples');
+ const p95 = sorted[Math.ceil(sorted.length * 0.95) - 1];
+ console.log('MANUAL_NATIVE_SCROLL ' + JSON.stringify({ count, deltaY, events: 24, moved: after.top - before.top, samples: sorted.length, p95, max: sorted.at(-1) }));
+ assert((after.top - before.top) * -Math.sign(deltaY) > 240, 'pending page swallowed sustained native input');
+ assert.equal(after.calls, before.calls, 'native input duplicated a held page request');
+ assert(p95 <= 100, 'native scroll frame p95 exceeded the renderer responsiveness budget');
+ }
+ await click('Complete page');
+ await wait('!globalThis.historyLoadingFixture.inspect().busy');
+ assert.match(await js('document.querySelector("#history-manual-status").textContent'), new RegExp(count + ' messages loaded'));
+ await call('frames()');
+ }
+ await click('Reset conversation');
+ await wait('document.querySelector("#history-manual-status").textContent.includes("40 of 1000")');
+ console.log('HISTORY_LOADING_PROBE ' + JSON.stringify({ ok: true, manualControls: true, pages: 2 }));
+ app.exit(0); 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);
+ let before = await call('begin()');
+ if (name === 'wheel') {
+ assert.deepEqual(await call('inputOwnership()'),
+ { wheel: false, key: false, touch: false, field: false, activation: false, nested: false, zoom: false });
+ await call('frames()');
+ before = await call('track()');
+ await call('armNativeInput()');
+ await wheel(before, -180);
+ console.log('HISTORY_EDGE_NATIVE_PENDING ' + JSON.stringify({ before, after: await call('inspect()') }));
+ const moved = await call('finishNativeInput()');
+ assert(moved.top > before.top + 20, 'hard-edge loading swallowed native input');
+ before = await call('track()');
+ }
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') + ')');
@@ -66,7 +112,8 @@ app.whenReady().then(async () => {
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(after.layoutSampleCount > 0 && after.layoutMaxDrift <= 2,
+ name + ': a painted frame moved the reading anchor by ' + after.layoutMaxDrift);
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');
@@ -95,12 +142,12 @@ app.whenReady().then(async () => {
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(aheadAfter.layoutSampleCount > 0 && aheadAfter.layoutMaxDrift <= 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,
+ assert(cached.after.layoutSampleCount > 0 && cached.after.layoutMaxDrift <= 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');
diff --git a/scripts/e2e/full-desktop-transcript.mjs b/scripts/e2e/full-desktop-transcript.mjs
new file mode 100644
index 000000000..fe5f192f3
--- /dev/null
+++ b/scripts/e2e/full-desktop-transcript.mjs
@@ -0,0 +1,63 @@
+import assert from "node:assert/strict";
+
+/** Public DOM and native input only: no store injection or component fixture. */
+export async function verifyFullDesktopTranscript({ send, evaluate, waitFor }) {
+ const geometry = () => evaluate(`(() => {
+ const el = document.querySelector('.thread-scroll');
+ const box = el.getBoundingClientRect();
+ return { top: el.scrollTop, bottom: el.scrollHeight - el.clientHeight - el.scrollTop,
+ x: box.left + box.width / 2, y: box.top + box.height / 2,
+ rows: el.querySelectorAll('.message-row').length };
+ })()`);
+ const initial = await geometry();
+ assert(initial.rows > 0 && initial.rows < 1000, "initial rendering must remain incremental");
+ let moved = false;
+ let nativeWheelEvents = 0;
+ for (let i = 0; i < 256; i++) {
+ const before = await geometry();
+ await send("Input.dispatchMouseEvent", { type: "mouseWheel", x: before.x, y: before.y,
+ deltaX: 0, deltaY: -500 });
+ await evaluate("new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))");
+ const after = await geometry();
+ moved ||= after.top < before.top - 1 || after.bottom > before.bottom + 1;
+ nativeWheelEvents++;
+ if (after.rows > 100) break;
+ }
+ assert(moved, "native wheel must move the full product transcript");
+ const reading = await geometry();
+ assert(reading.bottom > 100, "upward reading must leave the live bottom");
+ await waitFor(() => evaluate("Boolean(document.querySelector('.jump-latest-btn'))"), 5000, "return-to-latest control");
+ assert(reading.rows > 100 && reading.rows < 1000, "cross the initial Host page without loading the entire conversation");
+ const motion = await evaluate(`new Promise(resolve => {
+ const el = document.querySelector('.thread-scroll');
+ const samples = [];
+ const start = performance.now();
+ let arrivedAt = null;
+ function sample(now) {
+ const box = el.getBoundingClientRect();
+ const rows = [...el.querySelectorAll('.message-row')];
+ const visible = rows.filter(row => { const r = row.getBoundingClientRect();
+ return r.bottom > box.top && r.top < box.bottom; });
+ const bottom = Math.max(0, el.scrollHeight - el.clientHeight - el.scrollTop);
+ const tail = rows.at(-1);
+ samples.push({ bottom, visible: visible.length, tailTop: tail?.getBoundingClientRect().top });
+ if (bottom <= 2 && arrivedAt === null) arrivedAt = now;
+ if ((arrivedAt !== null && now - arrivedAt >= 600) || now - start >= 5000) {
+ resolve({ samples, arrived: arrivedAt !== null }); return;
+ }
+ requestAnimationFrame(sample);
+ }
+ document.querySelector('.jump-latest-btn').click();
+ requestAnimationFrame(sample);
+ })`);
+ assert(motion.arrived, "return-to-latest must reach the real bottom");
+ assert(motion.samples.every(sample => sample.visible > 0), "navigation must not paint a blank transcript");
+ const arrival = motion.samples.findIndex(sample => sample.bottom <= 2);
+ const settled = motion.samples.slice(arrival);
+ const tailTops = settled.map(sample => sample.tailTop);
+ const drift = Math.max(...tailTops) - Math.min(...tailTops);
+ assert(drift <= 2, `full Desktop bottom handoff drift: ${drift}px`);
+ const result = { initial, reading, final: await geometry(), samples: motion.samples.length, drift, nativeWheelEvents };
+ console.log("FULL_DESKTOP_INTERACTION " + JSON.stringify(result));
+ return result;
+}
diff --git a/scripts/e2e/transcript-history-loading.tsx b/scripts/e2e/transcript-history-loading.tsx
index d2d35c787..08d385976 100644
--- a/scripts/e2e/transcript-history-loading.tsx
+++ b/scripts/e2e/transcript-history-loading.tsx
@@ -7,6 +7,20 @@ 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";
+import { Button } from "../../apps/desktop/src/components/ui";
+
+const manual = new URLSearchParams(location.search).has("manual");
+let firstMessage = manual ? 960 : 60;
+let manualStatus = "Scroll upward to request history. No real sessions or providers are used.";
+function showStatus(message: string) {
+ manualStatus = message;
+ const output = document.getElementById("history-manual-status");
+ if (output) output.textContent = message;
+}
+async function manualAction(action: () => Promise<unknown>) {
+ try { await action(); }
+ catch (error) { showStatus(error instanceof Error ? error.message : String(error)); }
+}
const frame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
async function until(test: () => boolean, label: string) {
@@ -34,6 +48,7 @@ let fail: (() => void) | undefined;
let anchor: HTMLElement | undefined;
let baseline = 0;
let samples: number[] = [];
+let layoutSamples: number[] = [];
let sampling = 0;
let scenario = 0;
let nativeInputEnded = false;
@@ -50,16 +65,18 @@ const busy = () => host.querySelector('.transcript-history-loading[aria-hidden="
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"));
+ showStatus(`Request ${calls} pending; ${current.length} messages loaded. Keep scrolling, then complete or fail this page.`);
});
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>
+ <Button onClick={() => void manualAction(reset)}>Reset conversation</Button>
+ <Button onClick={() => void manualAction(manual ? requestManualPage : () => begin())}>Load earlier (hold)</Button>
+ <Button onClick={() => void manualAction(() => release())}>Complete page</Button>
+ <Button onClick={() => void manualAction(() => release(true))}>Fail page</Button>
+ <span>Keep scrolling during loading; releasing a page must not reverse your movement.</span>
</nav>
+ {manual ? <output id="history-manual-status" aria-live="polite" style={{ padding: 8 }}>{manualStatus}</output> : null}
<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} />
@@ -68,7 +85,10 @@ function render() {
}
async function reset() {
finish?.(); finish = undefined;
- scenario++; calls = 0; more = true; visible = true; current = messages(60, 100);
+ scenario++; calls = 0; more = true; visible = true;
+ firstMessage = manual ? 960 : 60;
+ current = messages(firstMessage, manual ? 1000 : 100);
+ showStatus(`Ready: ${current.length} of ${manual ? 1000 : 100} synthetic messages loaded. Scroll upward to request a page.`);
anchor = undefined; cancelAnimationFrame(sampling); samples = [];
render();
await until(() => !host.querySelector('[data-transcript-settling="true"]'), "first paint did not settle");
@@ -84,11 +104,38 @@ async function begin(top = 80) {
await until(busy, "page did not start");
return track();
}
+async function requestManualPage() {
+ const currentScenario = scenario;
+ for (let attempt = 0; attempt < 30 && !finish && more && scenario === currentScenario; attempt++) {
+ const el = scroller();
+ el.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -120 }));
+ el.scrollTo({ top: 80, behavior: "instant" });
+ el.dispatchEvent(new Event("scroll", { bubbles: true }));
+ // Cached-window expansion settles independently of physical page loading.
+ let stable = 0;
+ let height = el.scrollHeight;
+ while (stable < 3 && !finish && scenario === currentScenario) {
+ await frame();
+ const next = el.scrollHeight;
+ stable = next === height ? stable + 1 : 0;
+ height = next;
+ }
+ }
+ if (scenario !== currentScenario) return;
+ if (finish) track();
+ else showStatus(more ? "Continue scrolling upward to request history." : "All synthetic history has been reached.");
+}
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;
- if (!failed && !empty) { current = [...messages(0, 60), ...current]; more = false; render(); }
+ if (!failed && !empty) {
+ const start = manual ? Math.max(0, firstMessage - 100) : 0;
+ current = [...messages(start, firstMessage), ...current];
+ firstMessage = start; more = start > 0; render();
+ }
+ showStatus(failed ? "Simulated page failure. Scroll upward again to retry." :
+ `Page complete: ${current.length} messages loaded; ${firstMessage} older messages remain unloaded.`);
if (failed) fail?.(); else resolve();
fail = undefined;
if (lateLayout) {
@@ -108,6 +155,8 @@ function inspect() {
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,
+ layoutSampleCount: layoutSamples.length,
+ layoutMaxDrift: layoutSamples.length ? Math.max(...layoutSamples.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() {
@@ -120,6 +169,7 @@ async function hideAndReveal() {
finish?.(); finish = undefined;
visible = true; render();
await until(() => !busy(), "hidden load did not release");
+ await until(() => layoutSamples.length > 0, "revealed history did not produce a layout sample");
return inspect();
}
function inputOwnership() {
@@ -156,8 +206,17 @@ function track() {
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); };
+ baseline = offset(); samples = []; layoutSamples = [];
+ const tracked = anchor;
+ const sample = () => {
+ if (visible) samples.push(offset());
+ const observer = new ResizeObserver(() => {
+ observer.disconnect();
+ if (visible && anchor === tracked) layoutSamples.push(offset());
+ });
+ observer.observe(el);
+ sampling = requestAnimationFrame(sample);
+ };
sampling = requestAnimationFrame(sample);
return inspect();
}
diff --git a/scripts/e2e/transcript-history-navigation.tsx b/scripts/e2e/transcript-history-navigation.tsx
index 99b620efa..1ebfd3728 100644
--- a/scripts/e2e/transcript-history-navigation.tsx
+++ b/scripts/e2e/transcript-history-navigation.tsx
@@ -78,10 +78,12 @@ globalThis.transcriptHistoryNavigationProbe = async (reducedOnly = false) => {
for (const item of pending.splice(0)) item.resolve(item.response);
searchRead?.resolve({ session: null }); searchRead = undefined; deferSearch = false;
id = `navigation-${name}`;
- const count = tailOnly ? 35 : 280;
+ const count = tailOnly ? 35 : name === "continuous-pages" ? 1035 : 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)}`,
+ role: role === "user" || index % (name.startsWith("motion-") && !tailOnly ? 100 : 30) === 0 ? "user" : "assistant",
+ content: name === "content-window-long" && index === count - 1
+ ? `Message ${index}\n\n${Array.from({ length: 1600 }, (_, paragraph) => `Long answer paragraph ${paragraph}. ${"Readable long-answer content. ".repeat(3)}`).join("\n\n")}`
+ : `Message ${index}\n\n${"Stationary visible reading paragraph. ".repeat(80)}`,
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 };
@@ -127,6 +129,52 @@ globalThis.transcriptHistoryNavigationProbe = async (reducedOnly = false) => {
const results: unknown[] = [];
const failures: string[] = [];
try {
+ for (const variant of reducedOnly ? [] : ["collapsed", "expanded", "long"]) {
+ const expanded = variant !== "collapsed";
+ await reset(`content-window-${variant}`, "mixed", false, true);
+ const el = scroller();
+ if (expanded) {
+ const toggles = [...el.querySelectorAll<HTMLButtonElement>('.turn-process > button[aria-expanded="false"]')];
+ assert(toggles.length > 0, "expanded resource fixture needs collapsed process groups");
+ flushSync(() => { for (const toggle of toggles) toggle.click(); });
+ await until(() => toggles.every(toggle => toggle.getAttribute("aria-expanded") === "true"), "process groups did not expand");
+ await frame();
+ }
+ const shells = () => [...el.querySelectorAll<HTMLElement>(".assistant-turn-fragment .prose-chat")];
+ const resources = () => shells().filter(node => node.childElementCount > 0).length;
+ const visibleReady = () => {
+ const viewport = el.getBoundingClientRect();
+ return shells().every(node => {
+ const rect = node.getBoundingClientRect();
+ return rect.bottom <= viewport.top || rect.top >= viewport.bottom || node.childElementCount > 0;
+ });
+ };
+ assert(shells().length > 20, "resource fixture must contain enough assistant content");
+ const readsBefore = reads.length;
+ const counts: number[] = [];
+ for (const fraction of [1, 0, 0.5, 1, 0]) {
+ el.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: fraction === 1 ? 400 : -400 }));
+ el.scrollTo({ top: (el.scrollHeight - el.clientHeight) * fraction, behavior: "instant" });
+ el.dispatchEvent(new Event("scroll", { bubbles: true }));
+ // Let scroll delivery, shared observation, and React layout commit run
+ // before accepting a result from the destination viewport.
+ for (let n = 0; n < 3; n++) await frame();
+ try {
+ await until(() => resources() <= 20 && visibleReady(), "content window did not recycle and restore visible prose");
+ } catch (error) {
+ console.log("CONTENT_WINDOW_FAILURE", JSON.stringify({ fraction, resources: resources(), visibleReady: visibleReady(),
+ height: el.clientHeight, top: el.scrollTop, shells: shells().map(node => ({
+ state: node.dataset.transcriptContent, height: node.getBoundingClientRect().height,
+ width: node.getBoundingClientRect().width, top: node.getBoundingClientRect().top,
+ })) }));
+ throw error;
+ }
+ counts.push(resources());
+ }
+ assert(reads.length === readsBefore, "content recycling initiated a history request");
+ console.log("CONTENT_WINDOW_RESOURCES", JSON.stringify({ variant, expanded, total: shells().length, counts }));
+ results.push({ contentWindow: counts });
+ }
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();
@@ -138,6 +186,11 @@ globalThis.transcriptHistoryNavigationProbe = async (reducedOnly = false) => {
}
await until(() => Boolean(host.querySelector(".jump-latest-btn")), "latest control did not appear");
let blankFrames = 0;
+ const textOffsets: number[] = [];
+ const bottomOffsets: number[] = [];
+ const arrivalSamples: { distance: number; history: boolean; rowTop: number; textTop: number | null; sameNode: boolean }[] = [];
+ let previousLatest: HTMLElement | null = null;
+ const latestMessageId = data.at(-1)!.id;
const distance = () => Math.max(0, el.scrollHeight - el.clientHeight - el.scrollTop);
const start = distance();
const samples: number[] = [start];
@@ -152,6 +205,29 @@ globalThis.transcriptHistoryNavigationProbe = async (reducedOnly = false) => {
observer.disconnect(); observers.delete(observer);
if (!sampling) return;
const viewport = el.getBoundingClientRect();
+ const latest = el.querySelector<HTMLElement>(`[data-message-id="${CSS.escape(latestMessageId)}"]`);
+ if (latest) {
+ const rect = latest.getBoundingClientRect();
+ if (rect.top < viewport.bottom && rect.bottom > viewport.top) {
+ textOffsets.push(rect.top - viewport.top);
+ // Near-bottom is not arrival: the last animation frames still
+ // travel legitimately. Historical arrival commits the live view.
+ if (bottom() && (tailOnly || !useAppStore.getState().transcriptViews[id])) {
+ bottomOffsets.push(rect.top - viewport.top);
+ }
+ if (bottom()) {
+ const walker = document.createTreeWalker(latest, NodeFilter.SHOW_TEXT);
+ let text = walker.nextNode();
+ while (text && !text.textContent?.trim()) text = walker.nextNode();
+ const range = document.createRange();
+ if (text) range.selectNodeContents(text);
+ arrivalSamples.push({ distance: distance(), history: Boolean(useAppStore.getState().transcriptViews[id]),
+ rowTop: rect.top - viewport.top, textTop: text ? range.getBoundingClientRect().top - viewport.top : null,
+ sameNode: latest === previousLatest });
+ }
+ previousLatest = latest;
+ }
+ }
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 &&
@@ -166,15 +242,21 @@ globalThis.transcriptHistoryNavigationProbe = async (reducedOnly = false) => {
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();
+ for (let n = 0; n < 30; 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) };
+ const textReversal = Math.max(0, ...textOffsets.slice(1).map((value, i) => value - textOffsets[i]));
+ const settledTextDrift = bottomOffsets.length ? Math.max(...bottomOffsets) - Math.min(...bottomOffsets) : 0;
+ console.log("LATEST_TEXT_TRAJECTORY " + JSON.stringify({ tailOnly, running, textReversal, settledTextDrift, bottomOffsets }));
+ console.log("LATEST_ARRIVAL_PHASES " + JSON.stringify({ tailOnly, running, arrivalSamples }));
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(textReversal <= 2 && settledTextDrift <= 2,
+ `latest text bounced despite bottom distance: ${JSON.stringify({ tailOnly, running, textReversal, settledTextDrift })}`);
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)); }
@@ -185,7 +267,7 @@ globalThis.transcriptHistoryNavigationProbe = async (reducedOnly = false) => {
assert(failures.length === 0 && unexpected.length === 0, failures.join("\n"));
return { ok: true, reducedMotion: true, cases: results };
}
- for (const action of ["interrupt", "press", "growth", "complete", "hide", "unmount", "new-search", "failed-search"] as const) {
+ for (const action of ["interrupt", "press", "growth", "layout-above", "complete", "hide", "unmount", "new-search", "failed-search"] as const) {
await reset(`lifecycle-${action}`, "mixed", action === "growth" || action === "complete");
const anchor = begin();
try {
@@ -235,7 +317,17 @@ globalThis.transcriptHistoryNavigationProbe = async (reducedOnly = false) => {
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") {
+ if (action === "layout-above") {
+ const content = el.querySelector<HTMLElement>(".thread-content")!;
+ const remaining = el.scrollHeight - el.clientHeight - el.scrollTop;
+ const previousPadding = content.style.paddingTop;
+ content.style.paddingTop = "2400px";
+ await frame();
+ const afterLayout = el.scrollHeight - el.clientHeight - el.scrollTop;
+ content.style.paddingTop = previousPadding;
+ assert(afterLayout <= remaining + 2,
+ `layout above reversed latest travel: before=${remaining}, after=${afterLayout}`);
+ } 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" }] });
@@ -312,15 +404,16 @@ globalThis.transcriptHistoryNavigationProbe = async (reducedOnly = false) => {
} catch (error) { failures.push(String(error)); console.log("PREFETCH_REPIN_ERROR " + String(error)); }
finally { anchor.stop(); }
}
- for (const { role, lateEntry } of [
- { role: "user", lateEntry: false }, { role: "mixed", lateEntry: false },
- { role: "user", lateEntry: true },
+ for (const { role, lateEntry, fast } of [
+ { role: "user", lateEntry: false, fast: false }, { role: "mixed", lateEntry: false, fast: false },
+ { role: "user", lateEntry: true, fast: false }, { role: "user", lateEntry: false, fast: true },
] as const) {
- await reset(`prefetch-${role}${lateEntry ? "-late-entry" : ""}`, role);
- const anchor = begin(scroller().clientHeight * 2);
+ await reset(`prefetch-${role}${lateEntry ? "-late-entry" : ""}${fast ? "-fast" : ""}`, role);
+ const anchor = begin(fast ? 4000 : 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");
+ if (fast) assert(scroller().scrollTop > 2400, "fast prefetch fell back to the old fixed band");
assert(scroller().style.overflowY !== "hidden", "background prefetch locked scrolling");
let previous: HTMLElement | undefined;
if (lateEntry) {
@@ -349,13 +442,61 @@ globalThis.transcriptHistoryNavigationProbe = async (reducedOnly = false) => {
const offset = anchor.measure();
await finish();
const drift = Math.abs(anchor.measure() - offset);
- const result = { role, lateEntry, prefetch: true, drift, top: scroller().scrollTop };
+ const result = { role, lateEntry, fast, 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(); }
}
+ await reset("continuous-pages");
+ {
+ const firstRead = reads.length;
+ const pages: { cursor: number; drift: number; mounted: number }[] = [];
+ for (let page = 0; page < 3; page++) {
+ // Cached window expansion may precede the physical read. Each attempt
+ // is a new upward gesture, never an observer-driven idle drain.
+ for (let attempt = 0; pending.length === 0 && attempt < 12; attempt++) {
+ const mounted = begin(scroller().clientHeight * 2);
+ mounted.stop();
+ await frame();
+ await until(() => pending.length > 0 || !busy(), "cached expansion did not settle");
+ let previousGeometry = "";
+ let stableFrames = 0;
+ await until(() => {
+ if (pending.length > 0) return true;
+ const el = scroller();
+ const geometry = `${el.scrollTop}:${el.scrollHeight}:${el.querySelectorAll("[data-message-id]").length}`;
+ stableFrames = geometry === previousGeometry ? stableFrames + 1 : 0;
+ previousGeometry = geometry;
+ return stableFrames >= 3 && !busy();
+ }, "cached expansion geometry did not stabilize");
+ }
+ assert(pending.length === 1, "continuous history lost single-flight paging");
+ const anchor = begin(scroller().clientHeight * 2);
+ try {
+ await frame(); await frame();
+ const before = anchor.measure();
+ const el = scroller();
+ el.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -100 }));
+ el.scrollTo({ top: el.scrollTop - 100, behavior: "instant" });
+ await frame(); await frame();
+ assert(Math.abs(anchor.measure() - before - 100) <= 2, "continuous read swallowed movement");
+ const offset = anchor.measure();
+ await finish();
+ const drift = Math.abs(anchor.measure() - offset);
+ assert(drift <= 2, `continuous prepend drifted by ${drift}`);
+ assert(reads.length === firstRead + page + 1, "page settlement eagerly requested more history");
+ pages.push({ cursor: reads.at(-1)!, drift,
+ mounted: el.querySelectorAll("[data-message-id]").length });
+ } finally { anchor.stop(); }
+ }
+ assert(pages.every((page, index) => index === 0 || page.cursor === pages[index - 1].cursor - 100),
+ `continuous history skipped or duplicated a page: ${JSON.stringify(pages)}`);
+ assert(useAppStore.getState().transcriptViews[id]?.hasMoreBefore, "fixture drained all history");
+ console.log("CONTINUOUS_HISTORY " + JSON.stringify(pages));
+ results.push({ continuousPages: pages });
+ }
for (const role of ["user", "mixed"] as const) {
await reset(`quiet-${role}`, role);
const anchor = begin();
diff --git a/scripts/manual-transcript-desktop.mjs b/scripts/manual-transcript-desktop.mjs
new file mode 100644
index 000000000..7fcdc226e
--- /dev/null
+++ b/scripts/manual-transcript-desktop.mjs
@@ -0,0 +1,136 @@
+#!/usr/bin/env node
+// Full production Desktop with isolated, synthetic Host-persisted conversations.
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import { once } from "node:events";
+import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
+import { createServer } from "node:net";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { Host, resolveHostBinary } from "./e2e/host.mjs";
+import { assertDesktopBuild, resolveElectronBinary } from "./e2e/boot.mjs";
+import { waitFor } from "./e2e/wait.mjs";
+import { verifyFullDesktopTranscript } from "./e2e/full-desktop-transcript.mjs";
+
+const root = fileURLToPath(new URL("..", import.meta.url));
+assert(process.env.PI_SCRATCH_DIR, "Set PI_SCRATCH_DIR to an isolated test directory");
+const directory = await mkdtemp(join(process.env.PI_SCRATCH_DIR, "full-transcript-desktop-"));
+const project = join(directory, "Scroll test workspace");
+await mkdir(project);
+const data = join(directory, "data");
+const binary = resolveHostBinary();
+assertDesktopBuild(root);
+const home = join(directory, "home");
+await mkdir(home);
+const isolation = { HOME: home, USERPROFILE: home, PI_CODING_AGENT_DIR: join(home, ".pi", "agent"),
+ PI_DESKTOP_AGENTS_DIR: join(home, ".agents"),
+ APPDATA: join(home, "AppData", "Roaming"), LOCALAPPDATA: join(home, "AppData", "Local") };
+const host = new Host(binary, data, { env: isolation });
+const sessions = [];
+try {
+ await host.start();
+ await host.call("workspace.set", { path: project });
+ const { servers } = await host.call("mcp.list", { projectPath: project });
+ assert.deepEqual(servers, [], "The isolated fixture must not discover user MCP servers");
+ await host.call("settings.set", { language: "zh-CN", autoGenerateTitle: false });
+ for (const [title, count, long] of [
+ ["Scroll test — 1000 messages", 1000, false],
+ ["Scroll test — long answers", 80, true],
+ ]) {
+ const { session } = await host.call("session.create", { title, mode: "agent", projectPath: project });
+ sessions.push({ id: session.id, title, count });
+ for (let index = 0; index < count; index++) {
+ const assistant = index % 2 === 1;
+ const paragraphs = long && index === count - 1 ? 1600 : 5 + index % 9;
+ const content = assistant
+ ? `## Answer ${index + 1}\n\n` + Array.from({ length: paragraphs }, (_, p) =>
+ `Paragraph ${p + 1} — message ${index + 1}. This synthetic conversation exercises continuous reading, early history loading and return to latest. Keep this numbered paragraph in view while scrolling. **Stable reading anchor** and inline code \`message-${index + 1}\`.`).join("\n\n") +
+ `\n\n\`\`\`typescript\nconst message = ${index + 1};\nconsole.log(message);\n\`\`\`\n\nEnd of answer ${index + 1}.`
+ : `Message ${index + 1}: inspect the next answer, scroll rapidly in both directions, then use the down-arrow to return to latest.`;
+ await host.call("session.appendMessage", { sessionId: session.id, message: {
+ id: randomUUID(), role: assistant ? "assistant" : "user", content,
+ createdAt: new Date(1700000000000 + index * 1000).toISOString(), status: "complete",
+ } });
+ }
+ console.log("SEEDED " + JSON.stringify(sessions.at(-1)));
+ }
+} finally { await host.stop(); }
+const server = createServer();
+await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
+const port = server.address().port;
+await new Promise(resolve => server.close(resolve));
+const { appDir, electronBinary } = resolveElectronBinary(root);
+const env = { ...process.env, ...isolation, PI_DESKTOP_DATA_DIR: data, PI_DESKTOP_HOST_BIN: binary,
+ ELECTRON_RENDERER_URL: "", PI_DESKTOP_START_MAXIMIZED: "0" };
+delete env.ELECTRON_RUN_AS_NODE;
+const child = spawn(electronBinary, [`--remote-debugging-port=${port}`, `--user-data-dir=${join(directory, "profile")}`, "."],
+ { cwd: appDir, env, stdio: ["ignore", "pipe", "pipe"] });
+child.on("error", error => { console.error(error); process.exitCode = 1; });
+const closed = once(child, "close");
+let output = "";
+for (const stream of [child.stdout, child.stderr]) stream.on("data", chunk => { output += chunk; });
+await writeFile(join(directory, "instance.json"), JSON.stringify({ directory, port, pid: child.pid, sessions }, null, 2));
+let ws;
+try {
+ let target;
+ await waitFor(async () => {
+ try { target = (await (await fetch(`http://127.0.0.1:${port}/json/list`)).json())
+ .find(entry => entry.type === "page" && entry.url.includes("index.html") && !entry.url.includes("plugin-launcher"));
+ return Boolean(target); } catch { return false; }
+ }, 45000, "full Desktop page");
+ ws = new WebSocket(target.webSocketDebuggerUrl);
+ await once(ws, "open");
+ let sequence = 0;
+ const pending = new Map();
+ ws.onmessage = ({ data }) => {
+ const response = JSON.parse(data), entry = pending.get(response.id);
+ if (!entry) return;
+ pending.delete(response.id); clearTimeout(entry.timer);
+ if (response.error) entry.reject(new Error(JSON.stringify(response.error)));
+ else entry.resolve(response.result);
+ };
+ const send = (method, params = {}) => new Promise((resolve, reject) => {
+ const id = ++sequence;
+ const timer = setTimeout(() => { pending.delete(id); reject(new Error(`CDP timeout: ${method}`)); }, 15000);
+ pending.set(id, { resolve, reject, timer }); ws.send(JSON.stringify({ id, method, params }));
+ });
+ const evaluate = async expression => {
+ const response = await send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
+ if (response.exceptionDetails) throw new Error(JSON.stringify(response.exceptionDetails));
+ return response.result.value;
+ };
+ const selector = `[data-sidebar-session-row="${sessions[0].id}"]`;
+ await waitFor(() => evaluate(`Boolean(document.querySelector(${JSON.stringify(selector)}))`), 45000, "seeded sidebar session");
+ await evaluate(`document.querySelector(${JSON.stringify(selector)}).click()`);
+ await waitFor(() => evaluate(`Boolean(document.querySelector('.thread-scroll .message-row') && document.querySelector('.composer-shell'))`), 30000, "full transcript and composer");
+ const proof = await evaluate(`({ title: document.title, rows: document.querySelectorAll('.thread-scroll .message-row').length, sidebar: Boolean(document.querySelector('[data-sidebar-session-row]')), composer: Boolean(document.querySelector('.composer-shell')), text: document.querySelector('.thread-scroll')?.innerText.slice(-300) })`);
+ const screenshot = await send("Page.captureScreenshot", { format: "png" });
+ await writeFile(join(directory, "desktop.png"), Buffer.from(screenshot.data, "base64"));
+ await writeFile(join(directory, "proof.json"), JSON.stringify(proof, null, 2));
+ console.log("FULL_DESKTOP_READY " + JSON.stringify({ directory, port, pid: child.pid, proof }));
+ if (process.argv.includes("--interaction-smoke")) {
+ const interaction = await verifyFullDesktopTranscript({ send, evaluate, waitFor });
+ await writeFile(join(directory, "interaction.json"), JSON.stringify(interaction, null, 2));
+ }
+ if (process.argv.includes("--smoke") || process.argv.includes("--interaction-smoke")) {
+ await evaluate(`window.piDesktop.invoke('pi-desktop/app/quit')`);
+ await waitFor(() => evaluate(`Boolean(document.querySelector('.lifecycle-confirmation-actions button:last-child'))`),
+ 5000, "normal quit confirmation");
+ await evaluate(`document.querySelector('.lifecycle-confirmation-actions button:last-child').click(); true`);
+ }
+} catch (error) {
+ console.error(error);
+ console.error(output.slice(-6000));
+ process.exitCode = 1;
+ child.kill("SIGKILL");
+} finally { ws?.close(); }
+const exitTimer = process.argv.some(arg => arg === "--smoke" || arg === "--interaction-smoke")
+ ? setTimeout(() => {
+ console.error("Desktop did not close within 20s after the smoke check");
+ console.error(output.slice(-6000));
+ process.exitCode = 1;
+ child.kill("SIGKILL");
+ }, 20000) : undefined;
+try { await closed; } finally { clearTimeout(exitTimer); }
+await writeFile(join(directory, "desktop.log"), output);
diff --git a/tests/history-loading-scroll-test-cases.md b/tests/history-loading-scroll-test-cases.md
index 9822e1736..d9c91a756 100644
--- a/tests/history-loading-scroll-test-cases.md
+++ b/tests/history-loading-scroll-test-cases.md
@@ -3,11 +3,11 @@
## Scope and prerequisites
- 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
+ (base `min(2400px, max(120px, 3 * clientHeight))`, increased by speed times
+ measured read latency plus `150ms`, capped at twelve screens or `12000px`)
+ without hiding overflow or blocking input. All paths, including the hard edge
+ and explicit continuation, track the moving actual-message anchor through IO
+ and three stable layout frames. 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
@@ -24,14 +24,66 @@
and never reads real sessions or contacts a provider.
- Close the fixture window to exit and remove its temporary profile.
+## Full PI-Desktop manual session
+
+For the complete application (sidebar, project, transcript and Composer), run:
+
+```bash
+node scripts/manual-transcript-desktop.mjs
+```
+
+Set `PI_SCRATCH_DIR` to an isolated test directory first. A current Desktop build
+and Host binary are required; `PI_DESKTOP_HOST_BIN` can select that binary.
+The launcher creates a new database, profile and user home under scratch, then
+uses Host RPC to seed **Scroll test — 1000 messages** and
+**Scroll test — long answers** (80 messages, with a 1,600-paragraph final answer).
+Select either session in the normal sidebar. Scroll quickly in both directions,
+click the down-arrow, resize the window, and switch away and back. Pagination
+uses the real Host database rather than the held-page component fixture below.
+No model provider is configured; this fixture is for reading/navigation, not
+sending model requests. Test data and screenshots remain in the printed scratch
+directory. Exit using the application's normal Quit action.
+
+`node scripts/manual-transcript-desktop.mjs --smoke` verifies seeded sidebar,
+transcript and Composer readiness, captures a screenshot, and quits only its
+own newly launched instance through the normal application IPC and its quit
+confirmation dialog. `--interaction-smoke` additionally sends native wheel
+input until the mounted window crosses the initial 100-message Host page,
+asserts that fewer than 1,000 rows are mounted, clicks the real return-to-latest
+button, and checks visible rows on every sampled navigation frame and at most
+`2px` of tail drift during the 600ms after arrival. It writes `interaction.json`
+and exits normally. These checks complement, rather than replace, the held-IO
+component fixture's prepend-anchor and request-concurrency measurements.
+
## 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 fixture offers 1,000 synthetic messages, initially loading only the newest
+40. Each successful page adds up to 100 older messages. The status line shows
+requests and loaded/unloaded counts; **Reset conversation** restores the initial
+40 messages. The toolbar deliberately holds a page until **Complete page** or
+**Fail page** is clicked, making delay reproducible even on fast disks.
+
+Scroll normally to trigger prefetch, or use **Load earlier (hold)** to traverse
+cached row-window expansion until a physical page request starts. While it is
+pending, scroll rapidly in either direction or click the transcript's down-arrow
+to return to latest. Then complete the page: the old request must not pull the
+viewport back. Repeat with failure and retry. Closing the window ends the test;
+no real session, provider configuration, or user database is changed.
+
+For an automated check of the same toolbar and two delayed pages, run:
+
+```bash
+node scripts/e2e-transcript-history-loading.mjs --manual-smoke
+```
+
+This also sends 24 native wheel events in each direction during each pending
+page, checks directional movement and single-flight requests, and reports rAF
+frame-gap p95/max (p95 budget: 100ms). These measurements cover this fixture and
+machine, not arbitrary hardware or a guarantee of zero frame delay.
The actual production `ChatTranscript`, scroll hooks, Markdown and stylesheet
are used. It is not a mock implementation of scrolling.
@@ -45,13 +97,12 @@ are used. It is not a mock implementation of scrolling.
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 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.
+- Expected: wheel/touch/scroll-key input moves the reading point during IO;
+ neither overflow hiding nor input cancellation freezes the viewport. The page
+ lands above the resulting reading point without adding a visible jump. With
+ no input, the same message stays within `2px`. Horizontal, zero-delta and
+ `Ctrl`+wheel input remain unaffected. No eager history drain occurs at rest.
+- Postcondition: earlier messages are available and input remains usable.
### TC-F-002: no-input loading has no vertical jitter
@@ -73,13 +124,13 @@ are used. It is not a mock implementation of scrolling.
answer group's first message changes. Do not assess only `scrollTop` or the
outer group's position. Repeat with ordinary standalone user rows.
-### TC-ERR-001: a failed page releases input
+### TC-ERR-001: a failed page preserves input
-- Priority: High. Requirement: failure recovery does not leave a locked viewport.
+- Priority: High. Requirement: failure recovery preserves the usable 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;
+- Expected: loading ends without an immediate automatic retry loop. Input stays
+ usable. 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 animates smoothly and overrides pending IO
@@ -109,8 +160,8 @@ are used. It is not a mock implementation of scrolling.
- Priority: High. Use an application built from this checkout with a long local
conversation containing several historical pages, tool output and code.
- Steps:
- 1. Scroll upward into the ahead-loading band (`min(2400px, max(120px, 3 *
- clientHeight))`) and continue reading upward while cached rows mount first
+ 1. Scroll upward into the adaptive ahead-loading band; repeat fast travel from
+ `4000px` above the boundary. Continue reading 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
@@ -125,9 +176,9 @@ are used. It is not a mock implementation of scrolling.
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
+ empty reads wait for a new gesture or explicit action). The `<= 120px`
+ hard edge, explicit continuation and underfilled observer use the same unlocked
+ behavior. 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,
@@ -156,8 +207,8 @@ unlocked ahead-loading with native wheel movement (`beginAhead`). Its
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),
-three ahead-read prefetch cases (standalone user rows, mixed grouped answers,
-and a preceding message that grows `400px` after upward input). All move the
+ ahead-read cases (standalone user rows, mixed grouped answers, a preceding
+ message growing `400px` after input, and adaptive prefetch from `4000px`). All move the
same visible message `100px` during IO and stay within `2px` after prepend;
the delayed predecessor must not replace a still-visible original anchor.
There are also two quiet message-stability cases and four pending/settled
@@ -166,13 +217,22 @@ browser-native smooth travel, resume follow during pending IO, interrupt by a
press without a scroll and remount the saved message, start a delayed failed
search, and return from focused/restored disjoint ranges without forward paging.
Stream growth/completion, hide/unmount, and reduced-motion media emulation are
-covered separately. Empty-view checks run after layout, before paint.
+covered separately. Latest navigation also tests `2400px` growth above the
+reader, with unit coverage for `1200px` shrinkage. History-release drift excludes
+legitimate final animation travel. Empty-view and delayed-layout stability
+checks require nonempty layout-complete/prepaint samples (`<= 2px`), retaining
+pre-layout rAF diagnostics separately. A 1,035-message fixture traverses three
+physical pages through the production cached-window escalation, moves the same
+message `100px` during each read, checks `<= 2px` insertion drift, descending
+100-message cursors, single-flight reads and no extra read after settlement.
+It records mounted-message counts as a baseline; this programmatic-position
+journey is not a native high-speed throughput or bounded-resource guarantee.
| Requirement | Cases | Evidence level |
| --- | --- | --- |
| 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 |
+| Hard-edge fallback preserves input and anchors the new reading point | TC-F-001, TC-F-002, TC-F-003 | Native Electron wheel + layout-complete samples + delayed geometry |
+| Failure or empty page ends 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 |