xonecas.io
64875
Mc

mini-coder / commit 498eb73

feat(ui): preserve chunked scroll anchor

Upgrade cel-tui to 0.5.0 and use measureContentHeight to preserve the viewport anchor when prepending older conversation chunks.

Keep sliced conversation rendering stable by retaining tool call args outside the visible window, and stop forcing scroll-to-bottom while the user has scrolled away during streaming.

xonecas2026-04-08 498eb73cd4b8d1cfccd01daefffbd95ce8d7e0b3 parent 4b39bb1

6 files changed

package.json+3−3
@@ -18,9 +18,9 @@
1818 "test": "bun test"
1919 },
2020 "dependencies": {
21- "@cel-tui/components": "^0.4.1",
22- "@cel-tui/core": "^0.4.1",
23- "@cel-tui/types": "^0.4.1",
21+ "@cel-tui/components": "^0.5.0",
22+ "@cel-tui/core": "^0.5.0",
23+ "@cel-tui/types": "^0.5.0",
2424 "@mariozechner/pi-ai": "^0.65.0",
2525 "diff": "^8.0.4"
2626 },
src/ui.test.ts+272−0
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test";
22 import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
5+import { measureContentHeight, VStack } from "@cel-tui/core";
56 import type { ContainerNode, Node } from "@cel-tui/types";
67 import type { AssistantMessage, Model } from "@mariozechner/pi-ai";
78 import {
@@ -26,6 +27,7 @@ import {
2627 } from "./session.ts";
2728 import { DEFAULT_SHOW_REASONING, DEFAULT_VERBOSE } from "./settings.ts";
2829 import { DEFAULT_THEME } from "./theme.ts";
30+import { buildConversationLogNodes } from "./ui/conversation.ts";
2931 import {
3032 buildConversationLog,
3133 createInputController,
@@ -65,6 +67,67 @@ function expectVStack(node: Node): ContainerNode {
6567 return node;
6668 }
6769
70+function findConversationLogNode(node: Node): ContainerNode {
71+ const found = findConversationLogNodeOrNull(node);
72+ if (!found) {
73+ throw new Error("Expected to find the scrollable conversation log");
74+ }
75+ return found;
76+}
77+
78+function findConversationLogNodeOrNull(node: Node): ContainerNode | null {
79+ if (
80+ node.type === "vstack" &&
81+ node.props.overflow === "scroll" &&
82+ node.props.scrollbar === true
83+ ) {
84+ return node;
85+ }
86+ if (node.type === "text" || node.type === "textinput") {
87+ return null;
88+ }
89+ for (const child of node.children) {
90+ const nested = findConversationLogNodeOrNull(child);
91+ if (nested) {
92+ return nested;
93+ }
94+ }
95+ return null;
96+}
97+
98+function getVisibleMessageIndexes(state: AppState): number[] {
99+ return collectText({
100+ type: "vstack",
101+ props: {},
102+ children: buildConversationLog(state),
103+ }).flatMap((line) => {
104+ const match = /^message (\d+)(?:$|\s)/.exec(line);
105+ return match ? [Number(match[1])] : [];
106+ });
107+}
108+
109+function measureConversationHeight(
110+ state: Pick<AppState, "messages" | "showReasoning" | "verbose" | "theme">,
111+ width: number,
112+ startIndex: number,
113+): number {
114+ return measureContentHeight(
115+ VStack(
116+ {},
117+ buildConversationLogNodes(
118+ state,
119+ {
120+ isStreaming: false,
121+ content: [],
122+ pendingToolResults: [],
123+ },
124+ startIndex,
125+ ),
126+ ),
127+ { width },
128+ );
129+}
130+
68131 function createDeferred<T = void>() {
69132 let resolve!: (value: T | PromiseLike<T>) => void;
70133 let reject!: (reason?: unknown) => void;
@@ -1437,6 +1500,215 @@ describe("ui rendering", () => {
14371500 }
14381501 });
14391502
1503+ test("buildConversationLog initially renders only the latest chunk of a long session and reloads older chunks at the top", () => {
1504+ const state = createTestState();
1505+ const controller = createInputController(state);
1506+ state.messages = Array.from({ length: 1_000 }, (_, index) => ({
1507+ role: "user" as const,
1508+ content: `message ${index}`,
1509+ timestamp: index,
1510+ }));
1511+
1512+ try {
1513+ const initialIndexes = getVisibleMessageIndexes(state);
1514+ const initialMin = Math.min(...initialIndexes);
1515+
1516+ expect(initialIndexes).not.toContain(0);
1517+ expect(Math.max(...initialIndexes)).toBe(999);
1518+
1519+ const initialLayout = renderBaseLayout(state, 80, controller);
1520+ findConversationLogNode(initialLayout).props.onScroll?.(0, 10);
1521+
1522+ const expandedIndexes = getVisibleMessageIndexes(state);
1523+ expect(Math.min(...expandedIndexes)).toBeLessThan(initialMin);
1524+ expect(expandedIndexes.length).toBeGreaterThan(initialIndexes.length);
1525+ expect(Math.max(...expandedIndexes)).toBe(999);
1526+
1527+ const expandedLayout = renderBaseLayout(state, 80, controller);
1528+ findConversationLogNode(expandedLayout).props.onScroll?.(10, 10);
1529+
1530+ const collapsedIndexes = getVisibleMessageIndexes(state);
1531+ expect(Math.min(...collapsedIndexes)).toBe(initialMin);
1532+ expect(Math.max(...collapsedIndexes)).toBe(999);
1533+ } finally {
1534+ state.db.close();
1535+ }
1536+ });
1537+
1538+ test("renderBaseLayout preserves the viewport anchor when loading an older wrapped chunk at the top", () => {
1539+ const state = createTestState();
1540+ const controller = createInputController(state);
1541+ const width = 20;
1542+ state.messages = Array.from({ length: 120 }, (_, index) => ({
1543+ role: "user" as const,
1544+ content: `message ${index} ${"wrapped ".repeat(8)}`.trim(),
1545+ timestamp: index,
1546+ }));
1547+
1548+ try {
1549+ const initialIndexes = getVisibleMessageIndexes(state);
1550+ const initialStart = Math.min(...initialIndexes);
1551+
1552+ const initialLayout = renderBaseLayout(state, width, controller);
1553+ findConversationLogNode(initialLayout).props.onScroll?.(0, 10);
1554+
1555+ const expandedLayout = renderBaseLayout(state, width, controller);
1556+ const expandedIndexes = getVisibleMessageIndexes(state);
1557+ const nextStart = Math.min(...expandedIndexes);
1558+ const expectedAddedHeight =
1559+ measureConversationHeight(state, width, nextStart) -
1560+ measureConversationHeight(state, width, initialStart);
1561+
1562+ expect(nextStart).toBeLessThan(initialStart);
1563+ expect(expectedAddedHeight).toBeGreaterThan(50);
1564+ expect(findConversationLogNode(expandedLayout).props.scrollOffset).toBe(
1565+ expectedAddedHeight,
1566+ );
1567+ } finally {
1568+ state.db.close();
1569+ }
1570+ });
1571+
1572+ test("renderBaseLayout keeps autoscroll paused when the user scrolls mid-turn", async () => {
1573+ const api = "ui-mid-turn-scroll-pause-test";
1574+ const sourceId = "ui-mid-turn-scroll-pause-test-source";
1575+ const model: Model<string> = {
1576+ id: "ui-mid-turn-scroll-pause-model",
1577+ name: "UI Mid-turn Scroll Pause Model",
1578+ api,
1579+ provider: "test",
1580+ baseUrl: "http://localhost:0",
1581+ reasoning: true,
1582+ input: ["text"],
1583+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1584+ contextWindow: 128000,
1585+ maxTokens: 4096,
1586+ };
1587+
1588+ const releaseSecondDelta = createDeferred<void>();
1589+ const finishStream = createDeferred<void>();
1590+ const finalMessage: AssistantMessage = {
1591+ role: "assistant",
1592+ content: [fauxText("first second")],
1593+ api,
1594+ provider: model.provider,
1595+ model: model.id,
1596+ usage: {
1597+ input: 0,
1598+ output: 0,
1599+ cacheRead: 0,
1600+ cacheWrite: 0,
1601+ totalTokens: 0,
1602+ cost: {
1603+ input: 0,
1604+ output: 0,
1605+ cacheRead: 0,
1606+ cacheWrite: 0,
1607+ total: 0,
1608+ },
1609+ },
1610+ stopReason: "stop",
1611+ timestamp: Date.now(),
1612+ };
1613+
1614+ const buildProviderStream = () => {
1615+ const stream = createAssistantMessageEventStream();
1616+
1617+ queueMicrotask(() => {
1618+ stream.push({
1619+ type: "text_delta",
1620+ contentIndex: 0,
1621+ delta: "first",
1622+ partial: {
1623+ ...finalMessage,
1624+ content: [fauxText("first")],
1625+ },
1626+ });
1627+
1628+ void releaseSecondDelta.promise.then(() => {
1629+ stream.push({
1630+ type: "text_delta",
1631+ contentIndex: 0,
1632+ delta: " second",
1633+ partial: finalMessage,
1634+ });
1635+
1636+ void finishStream.promise.then(() => {
1637+ stream.push({
1638+ type: "done",
1639+ reason: "stop",
1640+ message: finalMessage,
1641+ });
1642+ stream.end(finalMessage);
1643+ });
1644+ });
1645+ });
1646+
1647+ return stream;
1648+ };
1649+
1650+ registerApiProvider(
1651+ {
1652+ api,
1653+ stream: () => buildProviderStream(),
1654+ streamSimple: () => buildProviderStream(),
1655+ },
1656+ sourceId,
1657+ );
1658+
1659+ const state = createTestState();
1660+ const controller = createInputController(state);
1661+ state.cwd = process.cwd();
1662+ state.canonicalCwd = process.cwd();
1663+ state.model = model;
1664+
1665+ try {
1666+ handleInput("hello", state);
1667+
1668+ await waitFor(() => {
1669+ const text = collectText({
1670+ type: "vstack",
1671+ props: {},
1672+ children: buildConversationLog(state),
1673+ });
1674+ return state.running && text.includes("first");
1675+ });
1676+
1677+ const beforeScroll = renderBaseLayout(state, 80, controller);
1678+ expect(findConversationLogNode(beforeScroll).props.scrollOffset).toBe(
1679+ Infinity,
1680+ );
1681+
1682+ findConversationLogNode(beforeScroll).props.onScroll?.(3, 10);
1683+
1684+ const pausedLayout = renderBaseLayout(state, 80, controller);
1685+ expect(findConversationLogNode(pausedLayout).props.scrollOffset).toBe(3);
1686+
1687+ releaseSecondDelta.resolve();
1688+
1689+ await waitFor(() => {
1690+ const text = collectText({
1691+ type: "vstack",
1692+ props: {},
1693+ children: buildConversationLog(state),
1694+ });
1695+ return text.includes("first second");
1696+ });
1697+
1698+ const afterSecondDelta = renderBaseLayout(state, 80, controller);
1699+ expect(findConversationLogNode(afterSecondDelta).props.scrollOffset).toBe(
1700+ 3,
1701+ );
1702+
1703+ finishStream.resolve();
1704+ await waitFor(() => !state.running);
1705+ } finally {
1706+ await stopRunningTurn(state);
1707+ unregisterApiProviders(sourceId);
1708+ state.db.close();
1709+ }
1710+ });
1711+
14401712 test("renderBaseLayout shows a single divider line between the conversation and input areas", () => {
14411713 const state = createTestState();
14421714 const controller: InputController = {
src/ui.ts+86−11
@@ -10,7 +10,14 @@
1010
1111 import { exec } from "node:child_process";
1212 import { platform } from "node:os";
13-import { cel, HStack, ProcessTerminal, Text, VStack } from "@cel-tui/core";
13+import {
14+ cel,
15+ HStack,
16+ measureContentHeight,
17+ ProcessTerminal,
18+ Text,
19+ VStack,
20+} from "@cel-tui/core";
1421 import type { Node } from "@cel-tui/types";
1522 import type { AppState } from "./index.ts";
1623 import {
@@ -55,6 +62,9 @@ const DIVIDER_FRAME_MS = 60;
5562 /** Width of the bright pulse segment in the animated divider. */
5663 const PULSE_WIDTH = 5;
5764
65+/** Maximum number of committed messages rendered before older history is chunked. */
66+const CONVERSATION_CHUNK_MESSAGES = 50;
67+
5868 // ---------------------------------------------------------------------------
5969 // UI state (module-scoped, not in AppState)
6070 // ---------------------------------------------------------------------------
@@ -65,6 +75,9 @@ let scrollOffset = 0;
6575 /** Whether the log auto-scrolls to the bottom. */
6676 let stickToBottom = true;
6777
78+/** First visible committed message when older history is chunked. */
79+let visibleConversationStart = 0;
80+
6881 /** Current text in the input area. */
6982 let inputValue = "";
7083
@@ -95,6 +108,7 @@ let activeOverlay: ActiveOverlay | null = null;
95108 export function resetUiState(): void {
96109 scrollOffset = 0;
97110 stickToBottom = true;
111+ visibleConversationStart = 0;
98112 inputValue = "";
99113 inputFocused = true;
100114 dividerTick = 0;
@@ -173,9 +187,57 @@ function renderDivider(state: AppState, width: number): Node {
173187 // Conversation log
174188 // ---------------------------------------------------------------------------
175189
190+function getLatestConversationChunkStart(messageCount: number): number {
191+ return Math.max(0, messageCount - CONVERSATION_CHUNK_MESSAGES);
192+}
193+
194+function getVisibleConversationStart(messageCount: number): number {
195+ if (stickToBottom) {
196+ return getLatestConversationChunkStart(messageCount);
197+ }
198+
199+ visibleConversationStart = Math.min(
200+ visibleConversationStart,
201+ getLatestConversationChunkStart(messageCount),
202+ );
203+ return visibleConversationStart;
204+}
205+
176206 /** Build the full conversation log as an array of nodes. */
177207 export function buildConversationLog(state: AppState): Node[] {
178- return buildConversationLogNodes(state, getStreamingConversationState());
208+ return buildConversationLogNodes(
209+ state,
210+ getStreamingConversationState(),
211+ getVisibleConversationStart(state.messages.length),
212+ );
213+}
214+
215+function measureConversationHeight(
216+ state: AppState,
217+ width: number,
218+ startIndex: number,
219+): number {
220+ return measureContentHeight(
221+ VStack(
222+ {},
223+ buildConversationLogNodes(
224+ state,
225+ getStreamingConversationState(),
226+ startIndex,
227+ ),
228+ ),
229+ { width: Math.max(1, width) },
230+ );
231+}
232+
233+function prependConversationChunk(state: AppState, width: number): void {
234+ const currentStart = visibleConversationStart;
235+ const nextStart = Math.max(0, currentStart - CONVERSATION_CHUNK_MESSAGES);
236+ const currentHeight = measureConversationHeight(state, width, currentStart);
237+ const nextHeight = measureConversationHeight(state, width, nextStart);
238+
239+ visibleConversationStart = nextStart;
240+ scrollOffset += Math.max(0, nextHeight - currentHeight);
179241 }
180242
181243 // ---------------------------------------------------------------------------
@@ -317,6 +379,10 @@ function ensureSession(state: AppState): NonNullable<AppState["session"]> {
317379 return session;
318380 }
319381
382+function scrollConversationToBottom(): void {
383+ stickToBottom = true;
384+}
385+
320386 /**
321387 * Append a UI-only info message to the conversation log.
322388 *
@@ -332,7 +398,7 @@ function appendInfoMessage(text: string, state: AppState): void {
332398 appendMessage(state.db, state.session.id, msg);
333399 }
334400 state.messages.push(msg);
335- stickToBottom = true;
401+ scrollConversationToBottom();
336402 cel.render();
337403 }
338404
@@ -344,9 +410,7 @@ const commandController = createCommandController({
344410 inputValue = value;
345411 },
346412 appendInfoMessage,
347- scrollConversationToBottom: () => {
348- stickToBottom = true;
349- },
413+ scrollConversationToBottom,
350414 render: () => {
351415 cel.render();
352416 },
@@ -367,9 +431,7 @@ const agentController = createUiAgentController({
367431 render: () => {
368432 cel.render();
369433 },
370- scrollConversationToBottom: () => {
371- stickToBottom = true;
372- },
434+ scrollConversationToBottom,
373435 startDividerAnimation,
374436 stopDividerAnimation,
375437 });
@@ -457,7 +519,7 @@ export function suspendToBackground(
457519 // Main
458520 // ---------------------------------------------------------------------------
459521
460-function renderConversationLog(state: AppState): Node {
522+function renderConversationLog(state: AppState, width: number): Node {
461523 return VStack(
462524 {
463525 flex: 1,
@@ -465,8 +527,21 @@ function renderConversationLog(state: AppState): Node {
465527 scrollbar: true,
466528 scrollOffset: stickToBottom ? Infinity : scrollOffset,
467529 onScroll: (offset, maxOffset) => {
530+ const wasStickToBottom = stickToBottom;
468531 scrollOffset = offset;
532+
533+ if (wasStickToBottom && offset < maxOffset) {
534+ visibleConversationStart = getLatestConversationChunkStart(
535+ state.messages.length,
536+ );
537+ }
538+
469539 stickToBottom = offset >= maxOffset;
540+
541+ if (!stickToBottom && offset === 0 && visibleConversationStart > 0) {
542+ prependConversationChunk(state, width);
543+ }
544+
470545 cel.render();
471546 },
472547 },
@@ -520,7 +595,7 @@ export function renderBaseLayout(
520595 },
521596 [
522597 // ── Conversation log ──
523- renderConversationLog(state),
598+ renderConversationLog(state, cols),
524599
525600 // ── Animated divider (pulse when agent is working) ──
526601 renderDivider(state, cols),
src/ui/agent.ts+0−5
@@ -278,7 +278,6 @@ export function createUiAgentController(
278278 case "toolcall_delta":
279279 case "toolcall_end":
280280 streamingContent = event.content;
281- runtime.scrollConversationToBottom();
282281 runtime.render();
283282 break;
284283
@@ -286,7 +285,6 @@ export function createUiAgentController(
286285 state.messages.push(event.message);
287286 state.stats = addMessageToStats(state.stats, event.message);
288287 streamingContent = [];
289- runtime.scrollConversationToBottom();
290288 runtime.render();
291289 break;
292290
@@ -310,7 +308,6 @@ export function createUiAgentController(
310308 isError: event.result.isError,
311309 });
312310 }
313- runtime.scrollConversationToBottom();
314311 runtime.render();
315312 break;
316313 }
@@ -320,7 +317,6 @@ export function createUiAgentController(
320317 pendingToolResults = pendingToolResults.filter(
321318 (toolResult) => toolResult.toolCallId !== event.message.toolCallId,
322319 );
323- runtime.scrollConversationToBottom();
324320 runtime.render();
325321 break;
326322
@@ -328,7 +324,6 @@ export function createUiAgentController(
328324 case "error":
329325 case "aborted":
330326 resetUiAgentState();
331- runtime.scrollConversationToBottom();
332327 runtime.render();
333328 break;
334329 }
src/ui/conversation.test.ts+46−0
@@ -127,6 +127,52 @@ describe("ui/conversation", () => {
127127 expect(text).not.toContain("Exit code: 0");
128128 });
129129
130+ test("buildConversationLogNodes keeps hidden tool call args available when rendering a sliced window", () => {
131+ const nodes = buildConversationLogNodes(
132+ {
133+ messages: [
134+ fauxAssistantMessage([
135+ fauxToolCall(
136+ "edit",
137+ {
138+ path: "src/app.ts",
139+ oldText: "before",
140+ newText: "after",
141+ },
142+ { id: "tool-1" },
143+ ),
144+ ]),
145+ {
146+ role: "toolResult" as const,
147+ toolCallId: "tool-1",
148+ toolName: "edit",
149+ content: [{ type: "text" as const, text: "Updated src/app.ts" }],
150+ isError: false,
151+ timestamp: Date.now(),
152+ },
153+ ],
154+ showReasoning: false,
155+ verbose: false,
156+ theme: DEFAULT_THEME,
157+ },
158+ {
159+ isStreaming: false,
160+ content: [],
161+ pendingToolResults: [],
162+ },
163+ 1,
164+ );
165+ const text = collectText({
166+ type: "vstack",
167+ props: {},
168+ children: nodes,
169+ });
170+
171+ expect(text).toContain("@@ -1,1 +1,1 @@");
172+ expect(text).toContain("-before");
173+ expect(text).toContain("+after");
174+ });
175+
130176 test("buildConversationLogNodes reuses cached committed nodes when the log is unchanged", () => {
131177 const state = {
132178 messages: [fauxAssistantMessage("Committed response")],
src/ui/conversation.ts+51−11
@@ -72,14 +72,20 @@ type ToolCallRenderInfo = {
7272 args: Record<string, unknown>;
7373 };
7474
75+interface ToolCallArgsCache {
76+ messages: readonly ConversationMessage[] | null;
77+ count: number;
78+ entries: Map<string, ToolCallRenderInfo>;
79+}
80+
7581 interface ConversationRenderCache {
7682 messages: readonly ConversationMessage[] | null;
83+ startIndex: number;
7784 count: number;
7885 showReasoning: boolean;
7986 verbose: boolean;
8087 theme: Theme | null;
8188 nodes: Node[];
82- toolCallArgs: Map<string, ToolCallRenderInfo>;
8389 }
8490
8591 const EMPTY_STREAMING_CONTENT: AssistantMessage["content"] = [];
@@ -87,14 +93,20 @@ const EMPTY_PENDING_TOOL_RESULTS: readonly PendingToolResult[] = [];
8793 const EMPTY_RENDER_NODES: Node[] = [];
8894 const EMPTY_TOOL_RESULT_ARGS: Record<string, unknown> = Object.freeze({});
8995
96+const toolCallArgsCache: ToolCallArgsCache = {
97+ messages: null,
98+ count: 0,
99+ entries: new Map(),
100+};
101+
90102 const conversationRenderCache: ConversationRenderCache = {
91103 messages: null,
104+ startIndex: 0,
92105 count: 0,
93106 showReasoning: false,
94107 verbose: false,
95108 theme: null,
96109 nodes: EMPTY_RENDER_NODES,
97- toolCallArgs: new Map(),
98110 };
99111
100112 let editToolDiffCache = new WeakMap<
@@ -104,13 +116,16 @@ let editToolDiffCache = new WeakMap<
104116
105117 /** Reset cached committed conversation renders and derived edit diffs. */
106118 export function resetConversationRenderCache(): void {
119+ toolCallArgsCache.messages = null;
120+ toolCallArgsCache.count = 0;
121+ toolCallArgsCache.entries = new Map();
107122 conversationRenderCache.messages = null;
123+ conversationRenderCache.startIndex = 0;
108124 conversationRenderCache.count = 0;
109125 conversationRenderCache.showReasoning = false;
110126 conversationRenderCache.verbose = false;
111127 conversationRenderCache.theme = null;
112128 conversationRenderCache.nodes = EMPTY_RENDER_NODES;
113- conversationRenderCache.toolCallArgs = new Map();
114129 editToolDiffCache = new WeakMap();
115130 }
116131
@@ -824,11 +839,33 @@ function renderConversationMessage(
824839 );
825840 }
826841
842+function cacheToolCallArgs(messages: readonly ConversationMessage[]): void {
843+ if (
844+ toolCallArgsCache.messages !== messages ||
845+ toolCallArgsCache.count > messages.length
846+ ) {
847+ toolCallArgsCache.messages = messages;
848+ toolCallArgsCache.count = 0;
849+ toolCallArgsCache.entries = new Map();
850+ }
851+
852+ for (let index = toolCallArgsCache.count; index < messages.length; index++) {
853+ const message = messages[index];
854+ if (message?.role === "assistant") {
855+ rememberToolCallArgs(message, toolCallArgsCache.entries);
856+ }
857+ }
858+
859+ toolCallArgsCache.count = messages.length;
860+}
861+
827862 function canReuseCommittedConversationCache(
828863 state: Pick<AppState, "messages" | "showReasoning" | "verbose" | "theme">,
864+ startIndex: number,
829865 ): boolean {
830866 return (
831867 conversationRenderCache.messages === state.messages &&
868+ conversationRenderCache.startIndex === startIndex &&
832869 conversationRenderCache.showReasoning === state.showReasoning &&
833870 conversationRenderCache.verbose === state.verbose &&
834871 conversationRenderCache.theme === state.theme &&
@@ -839,15 +876,18 @@ function canReuseCommittedConversationCache(
839876 function cacheCommittedConversation(
840877 state: Pick<AppState, "messages" | "showReasoning" | "verbose" | "theme">,
841878 renderOpts: ConversationRenderOpts,
879+ startIndex: number,
842880 ): void {
843- if (!canReuseCommittedConversationCache(state)) {
881+ cacheToolCallArgs(state.messages);
882+
883+ if (!canReuseCommittedConversationCache(state, startIndex)) {
844884 conversationRenderCache.messages = state.messages;
845- conversationRenderCache.count = 0;
885+ conversationRenderCache.startIndex = startIndex;
886+ conversationRenderCache.count = startIndex;
846887 conversationRenderCache.showReasoning = state.showReasoning;
847888 conversationRenderCache.verbose = state.verbose;
848889 conversationRenderCache.theme = state.theme;
849890 conversationRenderCache.nodes = [];
850- conversationRenderCache.toolCallArgs = new Map();
851891 }
852892
853893 for (
@@ -860,7 +900,7 @@ function cacheCommittedConversation(
860900 renderConversationMessage(
861901 state.messages[index]!,
862902 renderOpts,
863- conversationRenderCache.toolCallArgs,
903+ toolCallArgsCache.entries,
864904 state.theme,
865905 ),
866906 );
@@ -882,11 +922,13 @@ function hasStreamingTail(streaming: StreamingConversationState): boolean {
882922 *
883923 * @param state - Conversation rendering state.
884924 * @param streaming - Current in-progress assistant tail, if any.
925+ * @param startIndex - Index of the first committed message to render.
885926 * @returns The rendered conversation log nodes.
886927 */
887928 export function buildConversationLogNodes(
888929 state: Pick<AppState, "messages" | "showReasoning" | "verbose" | "theme">,
889930 streaming: StreamingConversationState,
931+ startIndex = 0,
890932 ): Node[] {
891933 const renderOpts: ConversationRenderOpts = {
892934 showReasoning: state.showReasoning,
@@ -894,7 +936,7 @@ export function buildConversationLogNodes(
894936 theme: state.theme,
895937 };
896938
897- cacheCommittedConversation(state, renderOpts);
939+ cacheCommittedConversation(state, renderOpts, startIndex);
898940
899941 if (!hasStreamingTail(streaming)) {
900942 return conversationRenderCache.nodes;
@@ -912,9 +954,7 @@ export function buildConversationLogNodes(
912954 );
913955
914956 for (const pendingToolResult of streaming.pendingToolResults) {
915- const info = conversationRenderCache.toolCallArgs.get(
916- pendingToolResult.toolCallId,
917- );
957+ const info = toolCallArgsCache.entries.get(pendingToolResult.toolCallId);
918958 pushConversationNode(
919959 nodes,
920960 renderToolResultMessage(