void;
+ onRetryLastUserMessage?: (text: string) => void;
+ onResubmitUserMessage?: (messageId: string, nextText: string) => void;
+ getMessageTokens?: (messageId: string) => number | null | undefined;
+}
+
+/**
+ * One transcript turn with the transcript-level actions wired in: retry
+ * is only offered on a failed last user message, and edit/resubmit only
+ * on the last turn. Used as the render slot of the virtual turn list.
+ */
+export function ChatThreadTurnSlot({
+ turn,
+ isLastTurn,
+ canRetryLastUser,
+ onCopyMessage,
+ onRetryLastUserMessage,
+ onResubmitUserMessage,
+ getMessageTokens,
+}: ChatThreadTurnSlotProps) {
+ const failedLastUser =
+ isLastTurn && canRetryLastUser && turn.userMessage !== null;
+
+ return (
+
+ );
+}
diff --git a/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-virtual-turn-list.spec.tsx b/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-virtual-turn-list.spec.tsx
new file mode 100644
index 0000000..bdd77d7
--- /dev/null
+++ b/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-virtual-turn-list.spec.tsx
@@ -0,0 +1,136 @@
+// @vitest-environment jsdom
+import type { AgentMessageSnapshot } from "@pi-desktop/shared";
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+import { buildChatTurns } from "./chat/chat-thread-turns";
+import { ChatThreadVirtualTurnList } from "./chat-thread-virtual-turn-list";
+
+function createMessages(count: number): AgentMessageSnapshot[] {
+ const messages: AgentMessageSnapshot[] = [];
+ for (let index = 0; index < count; index += 1) {
+ messages.push({
+ id: `user-${index}`,
+ role: "user",
+ text: `Question ${index}`,
+ status: "complete",
+ timestamp: index * 2,
+ });
+ messages.push({
+ id: `assistant-${index}`,
+ role: "assistant",
+ text: `Answer ${index}`,
+ status: "complete",
+ timestamp: index * 2 + 1,
+ });
+ }
+ return messages;
+}
+
+function renderList(
+ turnCount: number,
+ overrides: Partial
[0]> = {},
+) {
+ const turns = buildChatTurns(createMessages(turnCount));
+ return render(
+ (
+ {turn.id}
+ )}
+ {...overrides}
+ />,
+ );
+}
+
+afterEach(() => {
+ cleanup();
+});
+
+describe("ChatThreadVirtualTurnList", () => {
+ it("mounts a bounded number of rows for a 2000-turn fixture", () => {
+ renderList(2000);
+
+ const rows = screen.getAllByTestId("chat-turn-row");
+ expect(rows.length).toBeGreaterThan(0);
+ expect(rows.length).toBeLessThanOrEqual(30);
+ // The latest turns are mounted on first paint; early history is not.
+ expect(screen.getByTestId("turn-content-user-1999")).toBeInTheDocument();
+ expect(screen.queryByTestId("turn-content-user-0")).not.toBeInTheDocument();
+ // Skipped history is represented by spacers, keeping the total
+ // scroll height (and therefore the scroll position) meaningful.
+ expect(screen.getAllByTestId("virtual-turn-spacer").length).toBeGreaterThan(
+ 0,
+ );
+ });
+
+ it("re-renders only the trailing window when a streaming turn appends", () => {
+ const messages = createMessages(2000);
+ const turns = buildChatTurns(messages);
+ const { rerender } = render(
+ {turn.id}
}
+ />,
+ );
+ const before = screen
+ .getAllByTestId("chat-turn-row")
+ .map((row) => row.dataset.turnId);
+
+ const nextTurns = buildChatTurns([
+ ...messages,
+ {
+ id: "assistant-1999",
+ role: "assistant",
+ text: "Answer 1999 (streaming more)",
+ status: "streaming",
+ timestamp: 4000,
+ },
+ ]);
+ rerender(
+ {turn.id}
}
+ />,
+ );
+
+ const after = screen
+ .getAllByTestId("chat-turn-row")
+ .map((row) => row.dataset.turnId);
+ expect(after).toEqual(before);
+ expect(after[after.length - 1]).toBe("user-1999");
+ });
+
+ it("force-mounts the turn containing a targeted (search) message", () => {
+ renderList(2000, { targetMessageId: "assistant-123" });
+
+ // Turn 123 is far outside the trailing window but must be mounted so
+ // the panel can scroll it into view.
+ expect(screen.getByTestId("turn-content-user-123")).toBeInTheDocument();
+ expect(screen.getByTestId("turn-content-user-1999")).toBeInTheDocument();
+ expect(screen.getAllByTestId("chat-turn-row").length).toBeLessThanOrEqual(
+ 31,
+ );
+ });
+
+ it("renders every turn when the history is short", () => {
+ renderList(5);
+ expect(screen.getAllByTestId("chat-turn-row")).toHaveLength(5);
+ expect(screen.queryByTestId("virtual-turn-spacer")).not.toBeInTheDocument();
+ });
+
+ it("renders nothing for an empty history", () => {
+ render(
+ {turn.id}
}
+ />,
+ );
+ expect(
+ screen.queryByTestId("chat-virtual-turn-list"),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-virtual-turn-list.tsx b/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-virtual-turn-list.tsx
new file mode 100644
index 0000000..21cb4c2
--- /dev/null
+++ b/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-virtual-turn-list.tsx
@@ -0,0 +1,114 @@
+import * as React from "react";
+import type { ChatThreadTurn } from "./chat/chat-thread-turns";
+import { useVirtualTurnListScroll } from "./chat/use-virtual-turn-list-scroll";
+import {
+ buildMountedSegments,
+ computeMountedTurnIndices,
+ findTurnIndexForMessage,
+} from "./chat/virtual-turn-window";
+
+export interface ChatThreadVirtualTurnListProps {
+ turns: ChatThreadTurn[];
+ isStreaming: boolean;
+ /** Message to reveal (e.g. a search result): its turn is force-mounted. */
+ targetMessageId?: string | null;
+ /** Thread id used to save/restore the reading position across switches. */
+ scrollStoreKey?: string | null;
+ renderTurn: (turn: ChatThreadTurn, turnIndex: number) => React.ReactNode;
+}
+
+function TurnSpacer({ height }: { height: number }) {
+ return (
+
+ );
+}
+
+/**
+ * Windowed turn list for the transcript (issue #11). Completed turns are
+ * mounted only near the viewport; skipped turns become spacers sized from
+ * measured or estimated heights (see useVirtualTurnListScroll). The
+ * active streaming turn and a targeted (search) turn are always mounted,
+ * so streaming output and search reveals never wait for a scroll.
+ */
+export function ChatThreadVirtualTurnList({
+ turns,
+ isStreaming,
+ targetMessageId,
+ scrollStoreKey,
+ renderTurn,
+}: ChatThreadVirtualTurnListProps) {
+ const { rootRef, registerRow, metrics, layout } = useVirtualTurnListScroll(
+ turns,
+ scrollStoreKey,
+ );
+
+ const lastTurnIndex = turns.length - 1;
+ const activeTurnIndex =
+ lastTurnIndex >= 0 && (isStreaming || turns[lastTurnIndex]?.isStreaming)
+ ? lastTurnIndex
+ : -1;
+ const targetTurnIndex = targetMessageId
+ ? findTurnIndexForMessage(turns, targetMessageId)
+ : -1;
+
+ // Keep the targeted turn mounted after the panel clears the target:
+ // scrollIntoView only lands if the turn stays in the tree.
+ const [stickyTargetIndex, setStickyTargetIndex] = React.useState(-1);
+ if (targetTurnIndex >= 0 && targetTurnIndex !== stickyTargetIndex) {
+ setStickyTargetIndex(targetTurnIndex);
+ }
+ const forcedTurnIndex =
+ targetTurnIndex >= 0 ? targetTurnIndex : stickyTargetIndex;
+
+ const mountedIndices = computeMountedTurnIndices({
+ turnCount: turns.length,
+ layout,
+ viewportTop: metrics?.top ?? null,
+ viewportHeight: metrics?.height ?? 0,
+ activeTurnIndex,
+ forcedTurnIndex,
+ });
+ const { segments, trailingSpacer } = buildMountedSegments(
+ mountedIndices,
+ layout,
+ );
+
+ if (turns.length === 0) return null;
+
+ return (
+
+ {segments.map((segment) => (
+
+ {segment.spacerBefore > 0 ? (
+
+ ) : null}
+ {turns
+ .slice(segment.startIndex, segment.endIndex + 1)
+ .map((turn, offset) => (
+
+ {renderTurn(turn, segment.startIndex + offset)}
+
+ ))}
+
+ ))}
+ {trailingSpacer > 0 ?
: null}
+
+ );
+}
diff --git a/apps/desktop/src/renderer/src/features/workspace/components/chat/chat-thread-turns.spec.ts b/apps/desktop/src/renderer/src/features/workspace/components/chat/chat-thread-turns.spec.ts
index e4313ca..8bcc251 100644
--- a/apps/desktop/src/renderer/src/features/workspace/components/chat/chat-thread-turns.spec.ts
+++ b/apps/desktop/src/renderer/src/features/workspace/components/chat/chat-thread-turns.spec.ts
@@ -1,6 +1,6 @@
import type { AgentMessageSnapshot } from "@pi-desktop/shared";
import { describe, expect, it } from "vitest";
-import { buildChatTurns } from "./chat-thread-turns";
+import { buildChatTurns, createChatTurnsBuilder } from "./chat-thread-turns";
function createMessage(
overrides: Partial,
@@ -106,4 +106,63 @@ describe("buildChatTurns", () => {
},
]);
});
+
+ it("preserves unchanged turn identities across streaming updates", () => {
+ const builder = createChatTurnsBuilder();
+ const completed = createMessage({
+ id: "user-1",
+ role: "user",
+ text: "First question",
+ timestamp: 10,
+ });
+ const completedAnswer = createMessage({
+ id: "assistant-1",
+ role: "assistant",
+ text: "First answer",
+ timestamp: 20,
+ });
+ const streamingUser = createMessage({
+ id: "user-2",
+ role: "user",
+ text: "Second question",
+ timestamp: 30,
+ });
+ const streamingPart = createMessage({
+ id: "assistant-2",
+ role: "assistant",
+ text: "Second ans",
+ status: "streaming",
+ timestamp: 40,
+ });
+
+ const first = builder.build([
+ completed,
+ completedAnswer,
+ streamingUser,
+ streamingPart,
+ ]);
+ const second = builder.build([
+ completed,
+ completedAnswer,
+ streamingUser,
+ { ...streamingPart, text: "Second answer" },
+ ]);
+
+ // The completed turn is referentially identical; only the streaming
+ // turn (whose message object changed) gets a new identity.
+ expect(second[0]).toBe(first[0]);
+ expect(second[1]).not.toBe(first[1]);
+ expect(second[1]?.messages[0]?.text).toBe("Second answer");
+
+ // Appending a new turn also preserves all prior completed turns.
+ const third = builder.build([
+ completed,
+ completedAnswer,
+ streamingUser,
+ { ...streamingPart, text: "Second answer", status: "complete" },
+ createMessage({ id: "user-3", role: "user", text: "Third question" }),
+ ]);
+ expect(third[0]).toBe(first[0]);
+ expect(third).toHaveLength(3);
+ });
});
diff --git a/apps/desktop/src/renderer/src/features/workspace/components/chat/chat-thread-turns.ts b/apps/desktop/src/renderer/src/features/workspace/components/chat/chat-thread-turns.ts
index 49e4769..de409e6 100644
--- a/apps/desktop/src/renderer/src/features/workspace/components/chat/chat-thread-turns.ts
+++ b/apps/desktop/src/renderer/src/features/workspace/components/chat/chat-thread-turns.ts
@@ -58,3 +58,41 @@ export function buildChatTurns(
return turns;
}
+
+function isSameTurn(left: ChatThreadTurn, right: ChatThreadTurn): boolean {
+ return (
+ left.id === right.id &&
+ left.userMessage === right.userMessage &&
+ left.lastAssistantTimestamp === right.lastAssistantTimestamp &&
+ left.isStreaming === right.isStreaming &&
+ left.messages.length === right.messages.length &&
+ left.messages.every((message, index) => message === right.messages[index])
+ );
+}
+
+export interface ChatTurnsBuilder {
+ build: (messages: AgentMessageSnapshot[]) => ChatThreadTurn[];
+}
+
+/**
+ * Incremental turn builder (issue #11): turns whose source messages are
+ * unchanged keep their object identity across rebuilds — e.g. while the
+ * last turn streams, every completed turn stays referentially stable, so
+ * memoized turn rows skip re-rendering and virtualization anchors keyed
+ * by turn id remain meaningful. Hold one builder per mounted thread.
+ */
+export function createChatTurnsBuilder(): ChatTurnsBuilder {
+ let previous: ChatThreadTurn[] = [];
+
+ return {
+ build(messages) {
+ const next = buildChatTurns(messages);
+ const reconciled = next.map((turn, index) => {
+ const prior = previous[index];
+ return prior && isSameTurn(prior, turn) ? prior : turn;
+ });
+ previous = reconciled;
+ return reconciled;
+ },
+ };
+}
diff --git a/apps/desktop/src/renderer/src/features/workspace/components/chat/use-virtual-turn-list-scroll.ts b/apps/desktop/src/renderer/src/features/workspace/components/chat/use-virtual-turn-list-scroll.ts
new file mode 100644
index 0000000..52ed663
--- /dev/null
+++ b/apps/desktop/src/renderer/src/features/workspace/components/chat/use-virtual-turn-list-scroll.ts
@@ -0,0 +1,220 @@
+import * as React from "react";
+import type { ChatThreadTurn } from "./chat-thread-turns";
+import {
+ captureScrollAnchor,
+ computeTurnLayout,
+ findScrollContainer,
+ getRelativeViewportTop,
+ resolveScrollAnchor,
+ type ScrollAnchor,
+ type TurnLayout,
+ threadScrollAnchorStore,
+} from "./virtual-turn-window";
+
+export interface ViewportMetrics {
+ top: number;
+ height: number;
+}
+
+export interface VirtualTurnListScroll {
+ rootRef: React.RefObject;
+ registerRow: (turnId: string) => (element: HTMLDivElement | null) => void;
+ metrics: ViewportMetrics | null;
+ layout: TurnLayout;
+}
+
+/**
+ * Scroll/measurement engine for the virtualized transcript (issue #11).
+ *
+ * - Discovers the surrounding scroll container and tracks the viewport in
+ * list-relative coordinates.
+ * - Measures mounted turn heights with a ResizeObserver; the layout falls
+ * back to estimates for turns that have never been mounted.
+ * - Anchors the reading position to the turn at the viewport top: when a
+ * height correction above the anchor shifts its offset, scrollTop is
+ * adjusted by the same delta so the visible content does not jump.
+ * - Saves the anchor per thread (module-level store) and restores it when
+ * the list remounts after a thread switch.
+ */
+export function useVirtualTurnListScroll(
+ turns: ChatThreadTurn[],
+ scrollStoreKey: string | null | undefined,
+): VirtualTurnListScroll {
+ const rootRef = React.useRef(null);
+ const containerRef = React.useRef(null);
+ const rowElementsRef = React.useRef(new Map());
+ const rowCallbacksRef = React.useRef(
+ new Map void>(),
+ );
+ const resizeObserverRef = React.useRef(null);
+ const anchorRef = React.useRef(null);
+ const anchorOffsetRef = React.useRef(null);
+ const atBottomRef = React.useRef(true);
+ const restoredKeyRef = React.useRef(null);
+ const storeKeyRef = React.useRef(scrollStoreKey);
+ storeKeyRef.current = scrollStoreKey;
+
+ const [measuredHeights, setMeasuredHeights] = React.useState<
+ ReadonlyMap
+ >(() => new Map());
+ const [metrics, setMetrics] = React.useState(null);
+
+ const layout = React.useMemo(
+ () => computeTurnLayout(turns, measuredHeights),
+ [turns, measuredHeights],
+ );
+ const layoutRef = React.useRef(layout);
+ layoutRef.current = layout;
+ const turnsRef = React.useRef(turns);
+ turnsRef.current = turns;
+
+ const measureRow = React.useCallback((entries: ResizeObserverEntry[]) => {
+ setMeasuredHeights((previous) => {
+ let next: Map | null = null;
+ for (const entry of entries) {
+ const element = entry.target as HTMLDivElement;
+ const turnId = element.dataset.turnId;
+ if (!turnId) continue;
+ const height = Math.round(entry.contentRect.height);
+ if (height > 0 && previous.get(turnId) !== height) {
+ next ??= new Map(previous);
+ next.set(turnId, height);
+ }
+ }
+ return next ?? previous;
+ });
+ }, []);
+
+ const registerRow = React.useCallback((turnId: string) => {
+ const cached = rowCallbacksRef.current.get(turnId);
+ if (cached) return cached;
+ const callback = (element: HTMLDivElement | null) => {
+ const existing = rowElementsRef.current.get(turnId);
+ if (existing && existing !== element) {
+ resizeObserverRef.current?.unobserve(existing);
+ rowElementsRef.current.delete(turnId);
+ }
+ if (element) {
+ rowElementsRef.current.set(turnId, element);
+ resizeObserverRef.current?.observe(element);
+ }
+ };
+ rowCallbacksRef.current.set(turnId, callback);
+ return callback;
+ }, []);
+
+ const hasTurns = turns.length > 0;
+
+ // Discover the scroll container, track viewport metrics, and restore
+ // the saved anchor for this thread on mount.
+ React.useEffect(() => {
+ if (!hasTurns) return;
+ const root = rootRef.current;
+ if (!root) return;
+ if (typeof ResizeObserver !== "undefined" && !resizeObserverRef.current) {
+ resizeObserverRef.current = new ResizeObserver(measureRow);
+ for (const element of rowElementsRef.current.values()) {
+ resizeObserverRef.current.observe(element);
+ }
+ }
+ const container = findScrollContainer(root);
+ containerRef.current = container;
+ if (!container) return;
+
+ let frame = 0;
+ const updateMetrics = () => {
+ frame = 0;
+ const top = getRelativeViewportTop(container, root);
+ const currentLayout = layoutRef.current;
+ const currentTurns = turnsRef.current;
+ anchorRef.current = captureScrollAnchor(currentTurns, currentLayout, top);
+ anchorOffsetRef.current = anchorRef.current
+ ? resolveScrollAnchor(anchorRef.current, currentTurns, currentLayout)
+ : null;
+ atBottomRef.current =
+ container.scrollHeight - container.scrollTop - container.clientHeight <=
+ 2;
+ const key = storeKeyRef.current;
+ if (key) {
+ if (atBottomRef.current || !anchorRef.current) {
+ threadScrollAnchorStore.delete(key);
+ } else {
+ threadScrollAnchorStore.set(key, anchorRef.current);
+ }
+ }
+ setMetrics((previous) =>
+ previous &&
+ Math.abs(previous.top - top) < 1 &&
+ previous.height === container.clientHeight
+ ? previous
+ : { top, height: container.clientHeight },
+ );
+ };
+ const scheduleUpdate = () => {
+ if (!frame) frame = requestAnimationFrame(updateMetrics);
+ };
+ container.addEventListener("scroll", scheduleUpdate, { passive: true });
+ window.addEventListener("resize", scheduleUpdate);
+
+ const key = storeKeyRef.current ?? null;
+ const saved = key ? threadScrollAnchorStore.get(key) : null;
+ if (saved && restoredKeyRef.current !== key) {
+ restoredKeyRef.current = key;
+ const resolved = resolveScrollAnchor(
+ saved,
+ turnsRef.current,
+ layoutRef.current,
+ );
+ if (resolved !== null) {
+ // Two frames: let the stick-to-bottom container finish its
+ // initial jump before applying the restored position.
+ requestAnimationFrame(() => {
+ requestAnimationFrame(() => {
+ const rootOffset =
+ container.scrollTop - getRelativeViewportTop(container, root);
+ container.scrollTop = rootOffset + resolved;
+ scheduleUpdate();
+ });
+ });
+ }
+ } else {
+ scheduleUpdate();
+ }
+
+ return () => {
+ if (frame) cancelAnimationFrame(frame);
+ container.removeEventListener("scroll", scheduleUpdate);
+ window.removeEventListener("resize", scheduleUpdate);
+ };
+ }, [measureRow, hasTurns]);
+
+ // Save the anchor when the list unmounts (thread switch remounts it).
+ React.useEffect(() => {
+ return () => {
+ const key = storeKeyRef.current;
+ if (!key) return;
+ if (atBottomRef.current || !anchorRef.current) {
+ threadScrollAnchorStore.delete(key);
+ } else {
+ threadScrollAnchorStore.set(key, anchorRef.current);
+ }
+ };
+ }, []);
+
+ // Height corrections above the anchor turn shift its offset; compensate
+ // scrollTop by the same delta so the reading position does not jump.
+ React.useEffect(() => {
+ const container = containerRef.current;
+ const anchor = anchorRef.current;
+ if (!container || !anchor || atBottomRef.current) return;
+ const resolved = resolveScrollAnchor(anchor, turns, layout);
+ if (resolved === null || anchorOffsetRef.current === null) return;
+ const delta = resolved - anchorOffsetRef.current;
+ anchorOffsetRef.current = resolved;
+ if (delta !== 0) {
+ container.scrollTop += delta;
+ }
+ }, [layout, turns]);
+
+ return { rootRef, registerRow, metrics, layout };
+}
diff --git a/apps/desktop/src/renderer/src/features/workspace/components/chat/virtual-turn-window.spec.ts b/apps/desktop/src/renderer/src/features/workspace/components/chat/virtual-turn-window.spec.ts
new file mode 100644
index 0000000..d3b5c35
--- /dev/null
+++ b/apps/desktop/src/renderer/src/features/workspace/components/chat/virtual-turn-window.spec.ts
@@ -0,0 +1,208 @@
+import type { AgentMessageSnapshot } from "@pi-desktop/shared";
+import { describe, expect, it } from "vitest";
+import { buildChatTurns, type ChatThreadTurn } from "./chat-thread-turns";
+import {
+ buildMountedSegments,
+ captureScrollAnchor,
+ computeMountedTurnIndices,
+ computeTurnLayout,
+ estimateTurnHeight,
+ FALLBACK_MOUNTED_TURNS,
+ findTurnIndexForMessage,
+ resolveScrollAnchor,
+ ThreadScrollAnchorStore,
+} from "./virtual-turn-window";
+
+function createTurns(count: number): ChatThreadTurn[] {
+ const messages: AgentMessageSnapshot[] = [];
+ for (let index = 0; index < count; index += 1) {
+ messages.push({
+ id: `user-${index}`,
+ role: "user",
+ text: `Question ${index}`,
+ status: "complete",
+ timestamp: index * 2,
+ });
+ messages.push({
+ id: `assistant-${index}`,
+ role: "assistant",
+ text: `Answer ${index}`,
+ status: "complete",
+ timestamp: index * 2 + 1,
+ });
+ }
+ return buildChatTurns(messages);
+}
+
+describe("computeTurnLayout", () => {
+ it("produces cumulative offsets and prefers measured heights", () => {
+ const turns = createTurns(3);
+ const estimated = computeTurnLayout(turns);
+ expect(estimated.offsets[0]).toBe(0);
+ expect(estimated.offsets[1]).toBe(estimated.heights[0]);
+ expect(estimated.totalHeight).toBe(
+ estimated.heights.reduce((sum, height) => sum + height, 0),
+ );
+
+ const measured = computeTurnLayout(
+ turns,
+ new Map([[turns[1]?.id ?? "", 500]]),
+ );
+ expect(measured.heights[1]).toBe(500);
+ expect(measured.offsets[2]).toBe((measured.heights[0] ?? 0) + 500);
+ expect(estimateTurnHeight(turns[0] as ChatThreadTurn)).toBeGreaterThan(0);
+ });
+});
+
+describe("computeMountedTurnIndices", () => {
+ it("bounds mounted rows for a 2000-turn fixture at the top", () => {
+ const turns = createTurns(2000);
+ const layout = computeTurnLayout(turns);
+
+ const mounted = computeMountedTurnIndices({
+ turnCount: turns.length,
+ layout,
+ viewportTop: 0,
+ viewportHeight: 800,
+ });
+
+ expect(mounted.length).toBeLessThan(40);
+ expect(mounted[0]).toBe(0);
+ expect(mounted).not.toContain(1000);
+ });
+
+ it("mounts a bounded window around a mid-history viewport", () => {
+ const turns = createTurns(2000);
+ const layout = computeTurnLayout(turns);
+ const middleTop = layout.offsets[1000] ?? 0;
+
+ const mounted = computeMountedTurnIndices({
+ turnCount: turns.length,
+ layout,
+ viewportTop: middleTop,
+ viewportHeight: 800,
+ });
+
+ expect(mounted.length).toBeLessThan(60);
+ expect(mounted).toContain(1000);
+ expect(mounted).not.toContain(0);
+ expect(mounted).not.toContain(1999);
+ });
+
+ it("always retains the active turn and a forced (search) turn", () => {
+ const turns = createTurns(2000);
+ const layout = computeTurnLayout(turns);
+
+ const mounted = computeMountedTurnIndices({
+ turnCount: turns.length,
+ layout,
+ viewportTop: 0,
+ viewportHeight: 800,
+ activeTurnIndex: 1999,
+ forcedTurnIndex: 42,
+ });
+
+ expect(mounted).toContain(1999);
+ expect(mounted).toContain(42);
+ expect(mounted.length).toBeLessThan(42);
+ });
+
+ it("falls back to a bounded trailing window before metrics exist", () => {
+ const turns = createTurns(2000);
+ const layout = computeTurnLayout(turns);
+
+ const mounted = computeMountedTurnIndices({
+ turnCount: turns.length,
+ layout,
+ viewportTop: null,
+ viewportHeight: 0,
+ });
+
+ expect(mounted).toHaveLength(FALLBACK_MOUNTED_TURNS);
+ expect(mounted[0]).toBe(2000 - FALLBACK_MOUNTED_TURNS);
+ expect(mounted[mounted.length - 1]).toBe(1999);
+ });
+});
+
+describe("buildMountedSegments", () => {
+ it("accounts for every pixel of the total height exactly once", () => {
+ const turns = createTurns(100);
+ const layout = computeTurnLayout(turns);
+ const mounted = computeMountedTurnIndices({
+ turnCount: turns.length,
+ layout,
+ viewportTop: 0,
+ viewportHeight: 800,
+ activeTurnIndex: 99,
+ forcedTurnIndex: 50,
+ });
+
+ const { segments, trailingSpacer } = buildMountedSegments(mounted, layout);
+ const mountedHeight = mounted.reduce(
+ (sum, index) => sum + (layout.heights[index] ?? 0),
+ 0,
+ );
+ const spacerHeight =
+ segments.reduce((sum, segment) => sum + segment.spacerBefore, 0) +
+ trailingSpacer;
+
+ expect(segments.length).toBeGreaterThan(1);
+ expect(mountedHeight + spacerHeight).toBe(layout.totalHeight);
+ });
+});
+
+describe("scroll anchors", () => {
+ it("round-trips the reading position through a layout change", () => {
+ const turns = createTurns(100);
+ const layout = computeTurnLayout(turns);
+ const viewportTop = (layout.offsets[40] ?? 0) + 10;
+
+ const anchor = captureScrollAnchor(turns, layout, viewportTop);
+ expect(anchor?.turnId).toBe(turns[40]?.id);
+ if (!anchor) throw new Error("expected a scroll anchor");
+ expect(resolveScrollAnchor(anchor, turns, layout)).toBe(viewportTop);
+
+ // Simulate turns above the anchor measuring taller than estimated:
+ // the resolved position shifts by exactly the growth above it.
+ const grown = computeTurnLayout(
+ turns,
+ new Map([[turns[10]?.id ?? "", (layout.heights[10] ?? 0) + 250]]),
+ );
+ expect(resolveScrollAnchor(anchor, turns, grown)).toBe(viewportTop + 250);
+ });
+
+ it("returns null when the anchored turn is gone", () => {
+ const turns = createTurns(10);
+ const layout = computeTurnLayout(turns);
+ const anchor = captureScrollAnchor(turns, layout, 0);
+ if (!anchor) throw new Error("expected a scroll anchor");
+ expect(resolveScrollAnchor(anchor, [], layout)).toBeNull();
+ });
+});
+
+describe("findTurnIndexForMessage", () => {
+ it("finds turns by user and assistant message ids", () => {
+ const turns = createTurns(10);
+ expect(findTurnIndexForMessage(turns, "user-7")).toBe(7);
+ expect(findTurnIndexForMessage(turns, "assistant-3")).toBe(3);
+ expect(findTurnIndexForMessage(turns, "missing")).toBe(-1);
+ });
+});
+
+describe("ThreadScrollAnchorStore", () => {
+ it("stores, returns, deletes, and evicts least-recently-used anchors", () => {
+ const store = new ThreadScrollAnchorStore(2);
+ store.set("thread-a", { turnId: "turn-1", offsetWithinTurn: 5 });
+ store.set("thread-b", { turnId: "turn-2", offsetWithinTurn: 0 });
+ expect(store.get("thread-a")?.turnId).toBe("turn-1");
+
+ // thread-a was just read, so thread-b is the eviction victim.
+ store.set("thread-c", { turnId: "turn-3", offsetWithinTurn: 0 });
+ expect(store.size).toBe(2);
+ expect(store.get("thread-b")).toBeNull();
+ expect(store.get("thread-a")?.turnId).toBe("turn-1");
+
+ store.delete("thread-a");
+ expect(store.get("thread-a")).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/src/features/workspace/components/chat/virtual-turn-window.ts b/apps/desktop/src/renderer/src/features/workspace/components/chat/virtual-turn-window.ts
new file mode 100644
index 0000000..2c89999
--- /dev/null
+++ b/apps/desktop/src/renderer/src/features/workspace/components/chat/virtual-turn-window.ts
@@ -0,0 +1,325 @@
+import type { ChatThreadTurn } from "./chat-thread-turns";
+
+/**
+ * Pure windowing math for the virtualized conversation transcript
+ * (issue #11). The transcript mounts only the turns near the viewport,
+ * plus the active (streaming) turn and any forced turn (e.g. a search
+ * target), and replaces the skipped turns with spacers whose heights
+ * come from this layout: measured heights when a turn has been mounted
+ * before, deterministic estimates otherwise.
+ */
+
+/** Turns mounted when no scroll metrics are available yet (first paint). */
+export const FALLBACK_MOUNTED_TURNS = 30;
+/** Extra pixels rendered above and below the visible viewport. */
+export const DEFAULT_OVERSCAN_PX = 1200;
+
+const BASE_MESSAGE_HEIGHT = 72;
+const LINE_HEIGHT = 22;
+const CHARS_PER_LINE = 88;
+const TOOL_MESSAGE_EXTRA_HEIGHT = 28;
+const MAX_MESSAGE_HEIGHT = 720;
+const MIN_TURN_HEIGHT = 48;
+
+function estimateMessageHeight(text: string, isTool: boolean): number {
+ const lines = Math.max(1, Math.ceil(text.length / CHARS_PER_LINE));
+ const height =
+ BASE_MESSAGE_HEIGHT +
+ (lines - 1) * LINE_HEIGHT +
+ (isTool ? TOOL_MESSAGE_EXTRA_HEIGHT : 0);
+ return Math.min(MAX_MESSAGE_HEIGHT, height);
+}
+
+/** Deterministic height estimate for a turn that has never been mounted. */
+export function estimateTurnHeight(turn: ChatThreadTurn): number {
+ let height = 0;
+ if (turn.userMessage) {
+ height += estimateMessageHeight(turn.userMessage.text, false);
+ }
+ for (const message of turn.messages) {
+ height += estimateMessageHeight(message.text, message.role === "tool");
+ }
+ return Math.max(MIN_TURN_HEIGHT, height);
+}
+
+export interface TurnLayout {
+ heights: number[];
+ /** offsets[i] is the top of turn i relative to the list top. */
+ offsets: number[];
+ totalHeight: number;
+}
+
+export function computeTurnLayout(
+ turns: ReadonlyArray,
+ measuredHeights?: ReadonlyMap,
+): TurnLayout {
+ const heights: number[] = [];
+ const offsets: number[] = [];
+ let totalHeight = 0;
+ for (const turn of turns) {
+ const measured = measuredHeights?.get(turn.id);
+ const height =
+ measured !== undefined && Number.isFinite(measured) && measured > 0
+ ? measured
+ : estimateTurnHeight(turn);
+ offsets.push(totalHeight);
+ heights.push(height);
+ totalHeight += height;
+ }
+ return { heights, offsets, totalHeight };
+}
+
+export interface ScrollAnchor {
+ turnId: string;
+ /** Pixels from the top of the anchored turn to the viewport top. */
+ offsetWithinTurn: number;
+}
+
+/**
+ * Capture the turn at the top of the viewport so the reading position can
+ * be restored after heights change, streaming appends, or a thread switch.
+ * `viewportTop` is relative to the list top (see computeTurnLayout).
+ */
+export function captureScrollAnchor(
+ turns: ReadonlyArray,
+ layout: TurnLayout,
+ viewportTop: number,
+): ScrollAnchor | null {
+ if (turns.length === 0) return null;
+ const clampedTop = Math.max(0, viewportTop);
+ for (let index = 0; index < turns.length; index += 1) {
+ const offset = layout.offsets[index] ?? 0;
+ const height = layout.heights[index] ?? 0;
+ if (offset + height > clampedTop) {
+ const turn = turns[index];
+ if (!turn) return null;
+ return {
+ turnId: turn.id,
+ offsetWithinTurn: Math.min(clampedTop - offset, height),
+ };
+ }
+ }
+ const last = turns[turns.length - 1];
+ if (!last) return null;
+ return {
+ turnId: last.id,
+ offsetWithinTurn: layout.heights[turns.length - 1] ?? 0,
+ };
+}
+
+/**
+ * Resolve a captured anchor against a (possibly changed) layout. Returns
+ * the list-relative scroll top that puts the same turn content at the top
+ * of the viewport, or null when the anchored turn no longer exists.
+ */
+export function resolveScrollAnchor(
+ anchor: ScrollAnchor,
+ turns: ReadonlyArray,
+ layout: TurnLayout,
+): number | null {
+ const index = turns.findIndex((turn) => turn.id === anchor.turnId);
+ if (index === -1) return null;
+ const offset = layout.offsets[index] ?? 0;
+ const height = layout.heights[index] ?? 0;
+ return offset + Math.min(anchor.offsetWithinTurn, height);
+}
+
+/** Index of the turn containing `messageId`, or -1 when absent. */
+export function findTurnIndexForMessage(
+ turns: ReadonlyArray,
+ messageId: string,
+): number {
+ return turns.findIndex(
+ (turn) =>
+ turn.userMessage?.id === messageId ||
+ turn.messages.some((message) => message.id === messageId),
+ );
+}
+
+export interface MountedTurnWindowInput {
+ turnCount: number;
+ layout: TurnLayout;
+ /** List-relative viewport top, or null when not measured yet. */
+ viewportTop: number | null;
+ viewportHeight: number;
+ overscanPx?: number;
+ /** Turn that must always stay mounted (the streaming turn), or -1. */
+ activeTurnIndex?: number;
+ /** Turn that must be mounted so it can be revealed (search target), or -1. */
+ forcedTurnIndex?: number;
+ fallbackTurnCount?: number;
+}
+
+/**
+ * The bounded set of turn indices to mount. With scroll metrics, this is
+ * the visible range plus overscan; before metrics exist (first paint, or
+ * no scroll container) it is the trailing window so the latest turns —
+ * including the active one — are what render. The active and forced turns
+ * are always included, even when scrolled far away from them.
+ */
+export function computeMountedTurnIndices(
+ input: MountedTurnWindowInput,
+): number[] {
+ const { turnCount, layout } = input;
+ if (turnCount === 0) return [];
+ const mounted = new Set();
+
+ if (input.viewportTop === null) {
+ const fallback = input.fallbackTurnCount ?? FALLBACK_MOUNTED_TURNS;
+ const start = Math.max(0, turnCount - fallback);
+ for (let index = start; index < turnCount; index += 1) {
+ mounted.add(index);
+ }
+ } else {
+ const overscan = input.overscanPx ?? DEFAULT_OVERSCAN_PX;
+ const rangeTop = input.viewportTop - overscan;
+ const rangeBottom = input.viewportTop + input.viewportHeight + overscan;
+ for (let index = 0; index < turnCount; index += 1) {
+ const offset = layout.offsets[index] ?? 0;
+ const height = layout.heights[index] ?? 0;
+ if (offset + height > rangeTop && offset < rangeBottom) {
+ mounted.add(index);
+ }
+ }
+ if (mounted.size === 0) {
+ // Viewport sits past the end of the (shrunk) content: mount the
+ // nearest turn so the list never renders blank.
+ let nearest = turnCount - 1;
+ for (let index = 0; index < turnCount; index += 1) {
+ const offset = layout.offsets[index] ?? 0;
+ const height = layout.heights[index] ?? 0;
+ if (offset + height > input.viewportTop) {
+ nearest = index;
+ break;
+ }
+ }
+ mounted.add(nearest);
+ }
+ }
+
+ for (const extra of [input.activeTurnIndex, input.forcedTurnIndex]) {
+ if (extra !== undefined && extra >= 0 && extra < turnCount) {
+ mounted.add(extra);
+ }
+ }
+
+ return Array.from(mounted).sort((a, b) => a - b);
+}
+
+export interface MountedSegment {
+ startIndex: number;
+ endIndex: number;
+ /** Spacer height (px) that must precede this segment. */
+ spacerBefore: number;
+}
+
+export interface MountedSegments {
+ segments: MountedSegment[];
+ /** Spacer height (px) after the last mounted turn. */
+ trailingSpacer: number;
+}
+
+/** Group mounted indices into contiguous runs with their spacer heights. */
+export function buildMountedSegments(
+ indices: ReadonlyArray,
+ layout: TurnLayout,
+): MountedSegments {
+ const segments: MountedSegment[] = [];
+ let previousEnd = -1;
+ for (const index of indices) {
+ const current = segments[segments.length - 1];
+ if (current && index === current.endIndex + 1) {
+ current.endIndex = index;
+ } else {
+ const offset = layout.offsets[index] ?? 0;
+ const previousBottom =
+ previousEnd === -1
+ ? 0
+ : (layout.offsets[previousEnd] ?? 0) +
+ (layout.heights[previousEnd] ?? 0);
+ segments.push({
+ startIndex: index,
+ endIndex: index,
+ spacerBefore: Math.max(0, offset - previousBottom),
+ });
+ }
+ previousEnd = index;
+ }
+
+ let trailingSpacer = 0;
+ if (previousEnd !== -1) {
+ const bottom =
+ (layout.offsets[previousEnd] ?? 0) + (layout.heights[previousEnd] ?? 0);
+ trailingSpacer = Math.max(0, layout.totalHeight - bottom);
+ }
+ return { segments, trailingSpacer };
+}
+
+/**
+ * Scroll anchors remembered per thread so switching away and back restores
+ * the reading position even though the thread panel remounts. Bounded with
+ * least-recently-used eviction.
+ */
+export class ThreadScrollAnchorStore {
+ private readonly anchors = new Map();
+ private readonly maxEntries: number;
+
+ constructor(maxEntries = 50) {
+ this.maxEntries = maxEntries;
+ }
+
+ get size(): number {
+ return this.anchors.size;
+ }
+
+ get(threadId: string): ScrollAnchor | null {
+ const anchor = this.anchors.get(threadId);
+ if (!anchor) return null;
+ this.anchors.delete(threadId);
+ this.anchors.set(threadId, anchor);
+ return anchor;
+ }
+
+ set(threadId: string, anchor: ScrollAnchor): void {
+ this.anchors.delete(threadId);
+ this.anchors.set(threadId, anchor);
+ while (this.anchors.size > this.maxEntries) {
+ const oldest = this.anchors.keys().next().value;
+ if (oldest === undefined) break;
+ this.anchors.delete(oldest);
+ }
+ }
+
+ delete(threadId: string): void {
+ this.anchors.delete(threadId);
+ }
+}
+
+/** Shared store: module scope so it survives per-thread panel remounts. */
+export const threadScrollAnchorStore = new ThreadScrollAnchorStore();
+
+/** Nearest ancestor (exclusive) that scrolls vertically, if any. */
+export function findScrollContainer(start: HTMLElement): HTMLElement | null {
+ let element = start.parentElement;
+ while (element) {
+ const overflowY = window.getComputedStyle(element).overflowY;
+ if (overflowY === "auto" || overflowY === "scroll") {
+ return element;
+ }
+ element = element.parentElement;
+ }
+ return null;
+}
+
+/**
+ * Viewport top relative to the content element's top, in the same
+ * coordinate space as computeTurnLayout offsets.
+ */
+export function getRelativeViewportTop(
+ container: HTMLElement,
+ content: HTMLElement,
+): number {
+ return (
+ container.getBoundingClientRect().top - content.getBoundingClientRect().top
+ );
+}
diff --git a/apps/desktop/src/renderer/src/features/workspace/components/workspace-shell-main-pane.tsx b/apps/desktop/src/renderer/src/features/workspace/components/workspace-shell-main-pane.tsx
index 4510f9a..ce5bd92 100644
--- a/apps/desktop/src/renderer/src/features/workspace/components/workspace-shell-main-pane.tsx
+++ b/apps/desktop/src/renderer/src/features/workspace/components/workspace-shell-main-pane.tsx
@@ -159,24 +159,19 @@ function WorkspaceShellMainPaneImpl({
onFileSave={onFileSave}
/>
) : hasActiveThread ? (
-
-
-
+ />
) : null}