xonecas.io
64875
Mc

mini-coder / commit 0d42cc7

feat(ui): virtualize conversation log and harden tool streaming

xonecas2026-04-20 0d42cc7a2c2f4cef8559bdea9ce5c6424ee37236 parent 8bc061e

7 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

TODO.md+11−1
@@ -7,10 +7,20 @@ The spec and code are the sources of truth; this file is just the verified backl
77
88 ## Open issues:
99
10-_None._
10+- [ ] Stream stops without finishing the turn after tools calls. happens in both headless and interactive mode.
11+
12+### Conversation log virtualization / performance plan
13+
14+Goal: replace the current message-count chunking with a real visible-slice virtual list and remove expensive preview/layout work from the scroll hot path.
15+
16+- [ ] Run a focused benchmark for long sessions after the virtualization refactor and confirm the new path holds up.
1117
1218 # Defered issues:
1319
20+- [ ] Read tool output should include line numbers to help the llm find it's anchors.
21+- [ ] If an agent uses readImage on a non-image file, mc crashes
22+- [ ] If a conversation is truncated away from the db when the UI is still open somewhere, the app crashes.
23+
1424 ## Theme config plan
1525
1626 - [ ] Extend the existing `settings.json` schema/loader with `theme` overrides and merge them into the active UI theme (`src/settings.ts`, `src/theme.ts`, `src/index.ts`, `spec.md`)
src/agent.test.ts+123−0
@@ -1314,6 +1314,129 @@ describe("agent loop", () => {
13141314 }
13151315 });
13161316
1317+ test("waits one task for a delayed result-only follow-up after tool use", async () => {
1318+ const api = "agent-delayed-tool-followup-test";
1319+ const sourceId = "agent-delayed-tool-followup-test-source";
1320+ const model: Model<string> = {
1321+ id: "agent-delayed-tool-followup-model",
1322+ name: "Agent Delayed Tool Follow-up Model",
1323+ api,
1324+ provider: "test",
1325+ baseUrl: "http://localhost:0",
1326+ reasoning: false,
1327+ input: ["text"],
1328+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1329+ contextWindow: 128000,
1330+ maxTokens: 4096,
1331+ };
1332+
1333+ const toolCallMessage: AssistantMessage = {
1334+ role: "assistant",
1335+ content: [
1336+ {
1337+ type: "toolCall",
1338+ id: "tool-1",
1339+ name: "shell",
1340+ arguments: { command: "echo hi" },
1341+ },
1342+ ],
1343+ api,
1344+ provider: model.provider,
1345+ model: model.id,
1346+ usage: ZERO_USAGE,
1347+ stopReason: "toolUse",
1348+ timestamp: Date.now(),
1349+ };
1350+ const finalMessage: AssistantMessage = {
1351+ role: "assistant",
1352+ content: [{ type: "text", text: "Done after tool." }],
1353+ api,
1354+ provider: model.provider,
1355+ model: model.id,
1356+ usage: ZERO_USAGE,
1357+ stopReason: "stop",
1358+ timestamp: Date.now(),
1359+ };
1360+ let requestCount = 0;
1361+
1362+ const buildStream = () => {
1363+ requestCount += 1;
1364+ if (requestCount === 1) {
1365+ const stream = createAssistantMessageEventStream();
1366+ queueMicrotask(() => {
1367+ stream.push({
1368+ type: "done",
1369+ reason: "toolUse",
1370+ message: toolCallMessage,
1371+ });
1372+ stream.end(toolCallMessage);
1373+ });
1374+ return stream;
1375+ }
1376+
1377+ const stream = createAssistantMessageEventStream();
1378+ stream[Symbol.asyncIterator] = async function* () {};
1379+ stream.result = () =>
1380+ new Promise<AssistantMessage>((resolve) => {
1381+ setTimeout(() => resolve(finalMessage), 0);
1382+ });
1383+ return stream;
1384+ };
1385+
1386+ registerApiProvider(
1387+ {
1388+ api,
1389+ stream: () => buildStream(),
1390+ streamSimple: () => buildStream(),
1391+ },
1392+ sourceId,
1393+ );
1394+
1395+ const session = createSession(db, { cwd: tmp });
1396+ const userMsg = makeUser("hello");
1397+ const turn = appendMessage(db, session.id, userMsg);
1398+
1399+ try {
1400+ const result = await runAgentLoop({
1401+ db,
1402+ sessionId: session.id,
1403+ turn,
1404+ model,
1405+ systemPrompt: "Test",
1406+ tools: [shellTool],
1407+ toolHandlers: new Map<string, ToolHandler>([
1408+ [
1409+ "shell",
1410+ () => ({
1411+ content: [{ type: "text", text: "tool output" }],
1412+ isError: false,
1413+ }),
1414+ ],
1415+ ]),
1416+ messages: [userMsg],
1417+ cwd: tmp,
1418+ });
1419+
1420+ expect(result.stopReason).toBe("stop");
1421+ expect(result.messages.map((message) => message.role)).toEqual([
1422+ "user",
1423+ "assistant",
1424+ "toolResult",
1425+ "assistant",
1426+ ]);
1427+
1428+ const lastMessage = result.messages.at(-1);
1429+ expect(lastMessage?.role).toBe("assistant");
1430+ if (!lastMessage || lastMessage.role !== "assistant") {
1431+ throw new Error("Expected assistant message");
1432+ }
1433+ expect(lastMessage.stopReason).toBe("stop");
1434+ expect(lastMessage.content).toEqual(finalMessage.content);
1435+ } finally {
1436+ unregisterApiProviders(sourceId);
1437+ }
1438+ });
1439+
13171440 test("treats a stream that ends without a terminal event as an error instead of hanging", async () => {
13181441 const api = "agent-incomplete-stream-test";
13191442 const sourceId = "agent-incomplete-stream-test-source";
src/agent.ts+19−0
@@ -418,6 +418,19 @@ function buildIncompleteAssistantMessage(
418418 };
419419 }
420420
421+async function resolveStreamResultSoon(
422+ streamResult: Promise<AssistantMessage>,
423+): Promise<AssistantMessage | undefined> {
424+ const pending = Symbol("pending");
425+ const result = await Promise.race([
426+ streamResult,
427+ new Promise<typeof pending>((resolve) => {
428+ setTimeout(() => resolve(pending), 0);
429+ }),
430+ ]);
431+ return result === pending ? undefined : result;
432+}
433+
421434 async function streamAssistantMessage(
422435 opts: Pick<
423436 RunAgentOpts,
@@ -455,7 +468,13 @@ async function streamAssistantMessage(
455468 }
456469
457470 // `end(result)` resolves the final result without emitting a terminal event.
471+ // Some wrappers settle that promise on the next task, so give it one more
472+ // turn before treating the stream as incomplete.
458473 await Promise.resolve();
474+ if (!assistantMessage && !settledStreamResult) {
475+ settledStreamResult = await resolveStreamResultSoon(streamResult);
476+ }
477+
459478 const finalAssistantMessage =
460479 assistantMessage ??
461480 settledStreamResult ??
src/ui.test.ts+101−2
@@ -9,7 +9,7 @@ import {
99 } from "node:fs";
1010 import { tmpdir } from "node:os";
1111 import { join } from "node:path";
12-import { cel, MockTerminal } from "@cel-tui/core";
12+import { cel, MockTerminal, measureContentHeight, VStack } from "@cel-tui/core";
1313 import type { ContainerNode, Node } from "@cel-tui/types";
1414 import type { AssistantMessage, Model } from "@mariozechner/pi-ai";
1515 import {
@@ -26,6 +26,11 @@ import { createSession, loadMessages, openDatabase } from "./session.ts";
2626 import { DEFAULT_SHOW_REASONING, DEFAULT_VERBOSE } from "./settings.ts";
2727 import { DEFAULT_THEME } from "./theme.ts";
2828 import {
29+ buildConversationLogNodes,
30+ CONVERSATION_GAP,
31+} from "./ui/conversation.ts";
32+import {
33+ buildConversationLog,
2934 createInputController,
3035 createRenderScheduler,
3136 handleInput,
@@ -90,7 +95,13 @@ function startUiViewport(
9095 ): void {
9196 cel.init(terminal);
9297 cel.viewport(() => {
93- const base = renderBaseLayout(state, terminal.columns, controller);
98+ const base = renderBaseLayout(
99+ state,
100+ terminal.columns,
101+ controller,
102+ undefined,
103+ terminal.rows,
104+ );
94105 const overlay = renderActiveOverlay(state);
95106 return overlay ? [base, overlay] : base;
96107 });
@@ -227,6 +238,94 @@ describe("ui render scheduling", () => {
227238 });
228239
229240 describe("ui rendering", () => {
241+ test("virtualizes long conversation logs with spacers while preserving total height", () => {
242+ const state = createTestState();
243+ state.messages = Array.from({ length: 40 }, (_, index) => ({
244+ role: "user",
245+ content: `message ${index + 1}`,
246+ timestamp: index + 1,
247+ }));
248+ const controller = createInputController(state);
249+
250+ try {
251+ const viewportHeight = 4;
252+ const fullNodes = buildConversationLogNodes(
253+ state,
254+ {
255+ isStreaming: false,
256+ content: [],
257+ pendingToolResults: [],
258+ },
259+ 0,
260+ 80,
261+ );
262+ const fullHeight = measureContentHeight(
263+ VStack({ gap: CONVERSATION_GAP }, fullNodes),
264+ { width: 80 },
265+ );
266+ const base = expectVStack(
267+ renderBaseLayout(state, 80, controller, undefined, 8),
268+ );
269+ const conversation = expectVStack(base.children[0]!);
270+ const maxOffset = Math.max(0, fullHeight - viewportHeight);
271+
272+ conversation.props.onScroll?.(Math.floor(maxOffset / 2), maxOffset);
273+
274+ const virtualNodes = buildConversationLog(state, 80, viewportHeight);
275+ const virtualHeight = measureContentHeight(
276+ VStack({ gap: CONVERSATION_GAP }, virtualNodes),
277+ { width: 80 },
278+ );
279+ const visibleMessages = virtualNodes
280+ .flatMap((node) => collectText(node))
281+ .filter((line) => line.startsWith("message "));
282+
283+ expect(virtualHeight).toBe(fullHeight);
284+ expect(virtualNodes.length).toBeLessThan(fullNodes.length);
285+ expect(visibleMessages.length).toBeLessThan(state.messages.length);
286+ expect(visibleMessages).not.toContain("message 1");
287+ expect(visibleMessages).not.toContain("message 40");
288+ } finally {
289+ state.db.close();
290+ }
291+ });
292+
293+ test("renderBaseLayout derives the virtualized log height from the terminal rows", () => {
294+ const state = createTestState();
295+ state.messages = Array.from({ length: 30 }, (_, index) => ({
296+ role: "user",
297+ content: `message ${index + 1}`,
298+ timestamp: index + 1,
299+ }));
300+ const controller = createInputController(state);
301+
302+ try {
303+ const compactBase = expectVStack(
304+ renderBaseLayout(state, 80, controller, undefined, 10),
305+ );
306+ const compactConversation = expectVStack(compactBase.children[0]!);
307+ const compactMessages = collectText(compactConversation).filter((line) =>
308+ line.startsWith("message "),
309+ );
310+
311+ controller.onChange("line 1\nline 2\nline 3\nline 4\nline 5\nline 6");
312+
313+ const tallInputBase = expectVStack(
314+ renderBaseLayout(state, 80, controller, undefined, 10),
315+ );
316+ const tallInputConversation = expectVStack(tallInputBase.children[0]!);
317+ const tallInputMessages = collectText(tallInputConversation).filter(
318+ (line) => line.startsWith("message "),
319+ );
320+
321+ expect(compactMessages.length).toBeGreaterThan(tallInputMessages.length);
322+ expect(compactMessages.at(-1)).toBe("message 30");
323+ expect(tallInputMessages.at(-1)).toBe("message 30");
324+ } finally {
325+ state.db.close();
326+ }
327+ });
328+
230329 test("first user message creates the session lazily", async () => {
231330 const faux = registerFauxProvider();
232331 const state = createTestState();
src/ui.ts+188−72
@@ -27,7 +27,7 @@ import type { Theme } from "./theme.ts";
2727 import { createUiAgentController } from "./ui/agent.ts";
2828 import { createCommandController } from "./ui/commands.ts";
2929 import {
30- buildConversationLogNodes,
30+ buildConversationLayoutSnapshot,
3131 CONVERSATION_GAP,
3232 resetConversationRenderCache,
3333 } from "./ui/conversation.ts";
@@ -74,8 +74,8 @@ const TERMINAL_TITLE_FRAMES = [
7474 "[o=---]",
7575 ] as const;
7676
77-/** Maximum number of committed messages rendered before older history is chunked. */
78-const CONVERSATION_CHUNK_MESSAGES = 50;
77+/** Overscan applied above and below the viewport for virtualized log rendering. */
78+const CONVERSATION_OVERSCAN_ROWS = 6;
7979
8080 /** Minimum delay between coalesced streaming renders. */
8181 const STREAM_RENDER_MIN_INTERVAL_MS = 33;
@@ -115,9 +115,6 @@ let scrollOffset = 0;
115115 /** Whether the log auto-scrolls to the bottom. */
116116 let stickToBottom = true;
117117
118-/** First visible committed message when older history is chunked. */
119-let visibleConversationStart = 0;
120-
121118 /** Current text in the input area. */
122119 let inputValue = "";
123120
@@ -177,7 +174,6 @@ export function isQuitKey(key: string, input: string): boolean {
177174 export function resetUiState(): void {
178175 scrollOffset = 0;
179176 stickToBottom = true;
180- visibleConversationStart = 0;
181177 inputValue = "";
182178 inputReadOnly = false;
183179 inputFocused = true;
@@ -528,62 +524,151 @@ function renderDivider(state: AppState, width: number): Node {
528524 // Conversation log
529525 // ---------------------------------------------------------------------------
530526
531-function getLatestConversationChunkStart(messageCount: number): number {
532- return Math.max(0, messageCount - CONVERSATION_CHUNK_MESSAGES);
527+function measureConversationSliceHeight(
528+ prefixHeights: readonly number[],
529+ startIndex: number,
530+ endIndex: number,
531+): number {
532+ const count = endIndex - startIndex;
533+ if (count <= 0) {
534+ return 0;
535+ }
536+ return (
537+ prefixHeights[endIndex]! -
538+ prefixHeights[startIndex]! +
539+ CONVERSATION_GAP * Math.max(0, count - 1)
540+ );
541+}
542+
543+function getConversationItemTop(
544+ prefixHeights: readonly number[],
545+ index: number,
546+): number {
547+ return prefixHeights[index]! + CONVERSATION_GAP * index;
533548 }
534549
535-function getVisibleConversationStart(messageCount: number): number {
536- if (stickToBottom) {
537- return getLatestConversationChunkStart(messageCount);
550+function findConversationStartIndex(
551+ itemHeights: readonly { height: number }[],
552+ prefixHeights: readonly number[],
553+ offset: number,
554+): number {
555+ let low = 0;
556+ let high = itemHeights.length;
557+
558+ while (low < high) {
559+ const mid = Math.floor((low + high) / 2);
560+ const bottom =
561+ getConversationItemTop(prefixHeights, mid) + itemHeights[mid]!.height;
562+ if (bottom > offset) {
563+ high = mid;
564+ } else {
565+ low = mid + 1;
566+ }
538567 }
539568
540- visibleConversationStart = Math.min(
541- visibleConversationStart,
542- getLatestConversationChunkStart(messageCount),
543- );
544- return visibleConversationStart;
569+ return Math.min(low, Math.max(0, itemHeights.length - 1));
570+}
571+
572+function findConversationEndIndex(
573+ items: readonly { height: number }[],
574+ prefixHeights: readonly number[],
575+ offset: number,
576+): number {
577+ let low = 0;
578+ let high = items.length;
579+
580+ while (low < high) {
581+ const mid = Math.floor((low + high) / 2);
582+ if (getConversationItemTop(prefixHeights, mid) < offset) {
583+ low = mid + 1;
584+ } else {
585+ high = mid;
586+ }
587+ }
588+
589+ return low;
590+}
591+
592+function renderConversationSpacer(height: number): Node | null {
593+ const rows = Math.max(0, Math.floor(height));
594+ if (rows === 0) {
595+ return null;
596+ }
597+
598+ const paddingY = Math.floor(rows / 2);
599+ if (rows % 2 === 0) {
600+ return VStack({ padding: { y: paddingY } }, []);
601+ }
602+
603+ return VStack({ padding: { y: paddingY } }, [Text("")]);
545604 }
546605
547606 /** Build the full conversation log as an array of nodes. */
548607 export function buildConversationLog(
549608 state: AppState,
550609 width = Number.POSITIVE_INFINITY,
610+ viewportHeight = Number.POSITIVE_INFINITY,
551611 ): Node[] {
552- return buildConversationLogNodes(
612+ const layout = buildConversationLayoutSnapshot(
553613 state,
554614 agentController.getStreamingConversationState(),
555- getVisibleConversationStart(state.messages.length),
556615 width,
557616 );
558-}
617+ const { items, prefixHeights } = layout;
618+ if (!Number.isFinite(viewportHeight) || items.length <= 1) {
619+ return items.map((item) => item.node);
620+ }
559621
560-function measureConversationHeight(
561- state: AppState,
562- width: number,
563- startIndex: number,
564-): number {
565- return measureContentHeight(
566- VStack(
567- { gap: CONVERSATION_GAP },
568- buildConversationLogNodes(
569- state,
570- agentController.getStreamingConversationState(),
571- startIndex,
572- width,
573- ),
574- ),
575- { width: Math.max(1, width) },
622+ const totalHeight = measureConversationSliceHeight(
623+ prefixHeights,
624+ 0,
625+ items.length,
576626 );
577-}
627+ const visibleHeight = Math.max(1, Math.floor(viewportHeight));
628+ const maxOffset = Math.max(0, totalHeight - visibleHeight);
629+ const effectiveScrollOffset = stickToBottom
630+ ? maxOffset
631+ : Math.max(0, Math.min(scrollOffset, maxOffset));
632+ const paddedTop = Math.max(
633+ 0,
634+ effectiveScrollOffset - CONVERSATION_OVERSCAN_ROWS,
635+ );
636+ const paddedBottom = Math.min(
637+ totalHeight,
638+ effectiveScrollOffset + visibleHeight + CONVERSATION_OVERSCAN_ROWS,
639+ );
640+
641+ let startIndex = findConversationStartIndex(items, prefixHeights, paddedTop);
642+ let endIndex = findConversationEndIndex(items, prefixHeights, paddedBottom);
643+ if (endIndex <= startIndex) {
644+ endIndex = Math.min(items.length, startIndex + 1);
645+ }
646+ startIndex = Math.min(startIndex, Math.max(0, endIndex - 1));
578647
579-function prependConversationChunk(state: AppState, width: number): void {
580- const currentStart = visibleConversationStart;
581- const nextStart = Math.max(0, currentStart - CONVERSATION_CHUNK_MESSAGES);
582- const currentHeight = measureConversationHeight(state, width, currentStart);
583- const nextHeight = measureConversationHeight(state, width, nextStart);
648+ const topSpacerHeight = measureConversationSliceHeight(
649+ prefixHeights,
650+ 0,
651+ startIndex,
652+ );
653+ const bottomSpacerHeight = measureConversationSliceHeight(
654+ prefixHeights,
655+ endIndex,
656+ items.length,
657+ );
584658
585- visibleConversationStart = nextStart;
586- scrollOffset += Math.max(0, nextHeight - currentHeight);
659+ const nodes: Node[] = [];
660+ const topSpacer = renderConversationSpacer(topSpacerHeight);
661+ if (topSpacer) {
662+ nodes.push(topSpacer);
663+ }
664+ for (let index = startIndex; index < endIndex; index++) {
665+ nodes.push(items[index]!.node);
666+ }
667+ const bottomSpacer = renderConversationSpacer(bottomSpacerHeight);
668+ if (bottomSpacer) {
669+ nodes.push(bottomSpacer);
670+ }
671+ return nodes;
587672 }
588673
589674 // ---------------------------------------------------------------------------
@@ -930,7 +1015,30 @@ export function suspendToBackground(
9301015 // Main
9311016 // ---------------------------------------------------------------------------
9321017
933-function renderConversationLog(state: AppState, width: number): Node {
1018+function getConversationViewportHeight(
1019+ cols: number,
1020+ rows: number,
1021+ divider: Node,
1022+ input: Node,
1023+ statusBar: Node,
1024+): number {
1025+ if (!Number.isFinite(rows)) {
1026+ return Number.POSITIVE_INFINITY;
1027+ }
1028+
1029+ const width = Math.max(1, Math.floor(cols));
1030+ const reservedHeight =
1031+ measureContentHeight(divider, { width }) +
1032+ measureContentHeight(input, { width }) +
1033+ measureContentHeight(statusBar, { width });
1034+ return Math.max(1, Math.floor(rows) - reservedHeight);
1035+}
1036+
1037+function renderConversationLog(
1038+ state: AppState,
1039+ width: number,
1040+ viewportHeight: number,
1041+): Node {
9341042 return VStack(
9351043 {
9361044 flex: 1,
@@ -939,23 +1047,11 @@ function renderConversationLog(state: AppState, width: number): Node {
9391047 justifyContent: state.messages.length === 0 ? "center" : undefined,
9401048 scrollOffset: stickToBottom ? Infinity : scrollOffset,
9411049 onScroll: (offset, maxOffset) => {
942- const wasStickToBottom = stickToBottom;
9431050 scrollOffset = offset;
944-
945- if (wasStickToBottom && offset < maxOffset) {
946- visibleConversationStart = getLatestConversationChunkStart(
947- state.messages.length,
948- );
949- }
950-
9511051 stickToBottom = offset >= maxOffset;
952-
953- if (!stickToBottom && offset === 0 && visibleConversationStart > 0) {
954- prependConversationChunk(state, width);
955- }
9561052 },
9571053 },
958- buildConversationLog(state, width),
1054+ buildConversationLog(state, width, viewportHeight),
9591055 );
9601056 }
9611057
@@ -968,6 +1064,8 @@ function renderConversationLog(state: AppState, width: number): Node {
9681064 * @param state - Application state.
9691065 * @param cols - Current terminal width in columns.
9701066 * @param inputController - Stable callbacks for the controlled TextInput.
1067+ * @param onSuspend - Optional suspend handler for Ctrl+Z.
1068+ * @param rows - Current terminal height in rows.
9711069 * @returns The base layout node.
9721070 */
9731071 export function renderBaseLayout(
@@ -975,6 +1073,7 @@ export function renderBaseLayout(
9751073 cols: number,
9761074 inputController: InputController,
9771075 onSuspend?: () => void,
1076+ rows = Number.POSITIVE_INFINITY,
9781077 ): Node {
9791078 titleState = state;
9801079 titleViewportActive = true;
@@ -982,6 +1081,17 @@ export function renderBaseLayout(
9821081 syncTerminalTitle(state);
9831082 }
9841083
1084+ const divider = renderDivider(state, cols);
1085+ const input = renderInputArea(state.theme, inputController);
1086+ const statusBar = renderStatusBar(state, cols);
1087+ const conversationViewportHeight = getConversationViewportHeight(
1088+ cols,
1089+ rows,
1090+ divider,
1091+ input,
1092+ statusBar,
1093+ );
1094+
9851095 return VStack(
9861096 {
9871097 height: "100%",
@@ -1012,16 +1122,16 @@ export function renderBaseLayout(
10121122 },
10131123 [
10141124 // ── Conversation log ──
1015- renderConversationLog(state, cols),
1125+ renderConversationLog(state, cols, conversationViewportHeight),
10161126
10171127 // ── Animated divider (pulse when agent is working) ──
1018- renderDivider(state, cols),
1128+ divider,
10191129
10201130 // ── Input area ──
1021- renderInputArea(state.theme, inputController),
1131+ input,
10221132
10231133 // ── Status bar (1 line) ──
1024- renderStatusBar(state, cols),
1134+ statusBar,
10251135 ],
10261136 );
10271137 }
@@ -1044,16 +1154,22 @@ export function startUI(state: AppState): void {
10441154
10451155 cel.viewport(() => {
10461156 const cols = terminal.columns;
1047- const base = renderBaseLayout(state, cols, inputController, () => {
1048- suspendToBackground(() => {
1049- resumeTerminalUi();
1050- cel._getBuffer()?.clear();
1051- if (state.running) {
1052- startDividerAnimation();
1053- }
1054- requestRender("immediate");
1055- });
1056- });
1157+ const base = renderBaseLayout(
1158+ state,
1159+ cols,
1160+ inputController,
1161+ () => {
1162+ suspendToBackground(() => {
1163+ resumeTerminalUi();
1164+ cel._getBuffer()?.clear();
1165+ if (state.running) {
1166+ startDividerAnimation();
1167+ }
1168+ requestRender("immediate");
1169+ });
1170+ },
1171+ terminal.rows,
1172+ );
10571173 const overlay = renderActiveOverlay(state);
10581174
10591175 if (overlay) {
src/ui/conversation.test.ts+57−0
@@ -164,6 +164,63 @@ describe("ui/conversation", () => {
164164 expect(lines.join("\n")).not.toContain('"command"');
165165 });
166166
167+ test("compact shell tool-call previews only render the visible tail slice", () => {
168+ const command = Array.from(
169+ { length: 14 },
170+ (_, index) => `echo line ${index + 1}`,
171+ ).join("\n");
172+
173+ const compactLines = collectRenderedLines(
174+ renderAssistantMessage(
175+ {
176+ content: [
177+ {
178+ type: "toolCall",
179+ id: "call-shell",
180+ name: "shell",
181+ arguments: { command },
182+ },
183+ ],
184+ },
185+ {
186+ showReasoning: true,
187+ verbose: false,
188+ theme: DEFAULT_THEME,
189+ cwd: "/tmp/project",
190+ previewWidth: 80,
191+ },
192+ ),
193+ );
194+ const verboseLines = collectRenderedLines(
195+ renderAssistantMessage(
196+ {
197+ content: [
198+ {
199+ type: "toolCall",
200+ id: "call-shell",
201+ name: "shell",
202+ arguments: { command },
203+ },
204+ ],
205+ },
206+ {
207+ showReasoning: true,
208+ verbose: true,
209+ theme: DEFAULT_THEME,
210+ cwd: "/tmp/project",
211+ previewWidth: 80,
212+ },
213+ ),
214+ );
215+
216+ expect(compactLines).toContain("│ shell ->");
217+ expect(compactLines).toContain("│ echo line 14");
218+ expect(compactLines).toContain("│ And 6 lines more");
219+ expect(compactLines).not.toContain("│ echo line 1");
220+ expect(verboseLines).toContain("│ echo line 1");
221+ expect(compactLines.length).toBeLessThan(verboseLines.length);
222+ });
223+
167224 test("MCP tool-call previews honor verbose mode", () => {
168225 const args = {
169226 query: "routing",
src/ui/conversation.ts+376−218
@@ -119,16 +119,14 @@ interface ToolCallArgsCache {
119119 entries: Map<string, ToolCallRenderInfo>;
120120 }
121121
122-interface ConversationRenderCache {
123- messages: readonly ConversationMessage[] | null;
124- startIndex: number;
125- count: number;
122+interface ConversationMessageRenderCacheEntry {
123+ node: Node | null;
124+ height: number;
126125 showReasoning: boolean;
127126 verbose: boolean;
128127 previewWidth: number;
129128 cwd: string | null;
130129 theme: Theme | null;
131- nodes: Node[];
132130 }
133131
134132 type ToolRenderDirection = "->" | "<-";
@@ -181,9 +179,36 @@ export interface ToolRenderLine {
181179 text: string;
182180 }
183181
182+/** A rendered conversation item plus its measured height. */
183+export interface ConversationLogItem {
184+ /** Rendered conversation node. */
185+ node: Node;
186+ /** Intrinsic item height in rows, excluding conversation gaps. */
187+ height: number;
188+}
189+
190+/** Rendered items plus cached cumulative intrinsic heights. */
191+export interface ConversationLayoutSnapshot {
192+ /** Rendered items in on-screen order. */
193+ items: readonly ConversationLogItem[];
194+ /** Cumulative intrinsic heights, excluding inter-item gaps. */
195+ prefixHeights: readonly number[];
196+}
197+
198+interface ConversationLayoutCache {
199+ messages: readonly ConversationMessage[] | null;
200+ count: number;
201+ showReasoning: boolean;
202+ verbose: boolean;
203+ previewWidth: number;
204+ cwd: string | null;
205+ theme: Theme | null;
206+ items: ConversationLogItem[];
207+ prefixHeights: number[];
208+}
209+
184210 const EMPTY_STREAMING_CONTENT: AssistantMessage["content"] = [];
185211 const EMPTY_PENDING_TOOL_RESULTS: readonly PendingToolResult[] = [];
186-const EMPTY_RENDER_NODES: Node[] = [];
187212 const EMPTY_TOOL_RESULT_ARGS: Record<string, unknown> = Object.freeze({});
188213
189214 const toolCallArgsCache: ToolCallArgsCache = {
@@ -192,16 +217,21 @@ const toolCallArgsCache: ToolCallArgsCache = {
192217 entries: new Map(),
193218 };
194219
195-const conversationRenderCache: ConversationRenderCache = {
220+let conversationMessageRenderCache = new WeakMap<
221+ ConversationMessage,
222+ ConversationMessageRenderCacheEntry
223+>();
224+
225+const conversationLayoutCache: ConversationLayoutCache = {
196226 messages: null,
197- startIndex: 0,
198227 count: 0,
199228 showReasoning: false,
200229 verbose: false,
201230 previewWidth: DEFAULT_TOOL_PREVIEW_WIDTH,
202231 cwd: null,
203232 theme: null,
204- nodes: EMPTY_RENDER_NODES,
233+ items: [],
234+ prefixHeights: [0],
205235 };
206236
207237 /** Reset cached committed conversation renders. */
@@ -209,15 +239,16 @@ export function resetConversationRenderCache(): void {
209239 toolCallArgsCache.messages = null;
210240 toolCallArgsCache.count = 0;
211241 toolCallArgsCache.entries = new Map();
212- conversationRenderCache.messages = null;
213- conversationRenderCache.startIndex = 0;
214- conversationRenderCache.count = 0;
215- conversationRenderCache.showReasoning = false;
216- conversationRenderCache.verbose = false;
217- conversationRenderCache.previewWidth = DEFAULT_TOOL_PREVIEW_WIDTH;
218- conversationRenderCache.cwd = null;
219- conversationRenderCache.theme = null;
220- conversationRenderCache.nodes = EMPTY_RENDER_NODES;
242+ conversationMessageRenderCache = new WeakMap();
243+ conversationLayoutCache.messages = null;
244+ conversationLayoutCache.count = 0;
245+ conversationLayoutCache.showReasoning = false;
246+ conversationLayoutCache.verbose = false;
247+ conversationLayoutCache.previewWidth = DEFAULT_TOOL_PREVIEW_WIDTH;
248+ conversationLayoutCache.cwd = null;
249+ conversationLayoutCache.theme = null;
250+ conversationLayoutCache.items = [];
251+ conversationLayoutCache.prefixHeights = [0];
221252 }
222253
223254 /** Render a user message with a subtle background. */
@@ -706,36 +737,58 @@ function renderTodoChecklist(todos: readonly TodoItem[], theme: Theme): Node {
706737 );
707738 }
708739
709-function measureToolNodesHeight(lines: readonly Node[], width: number): number {
710- if (lines.length === 0) {
711- return 0;
740+function measureToolNodeHeight(node: Node, width: number): number {
741+ return measureContentHeight(VStack({}, [node]), { width });
742+}
743+
744+function renderFullToolBody(spec: ToolBlockSpec, theme: Theme): Node | null {
745+ if (spec.highlightedBody) {
746+ const highlighted = getHighlightedBodyNode(spec.highlightedBody, theme);
747+ if (highlighted) {
748+ return highlighted;
749+ }
712750 }
713751
714- return measureContentHeight(VStack({}, [...lines]), { width });
715-}
752+ if (spec.bodyLines.length === 0) {
753+ return null;
754+ }
716755
717-function measureToolNodeHeight(line: Node, width: number): number {
718- return measureContentHeight(VStack({}, [line]), { width });
756+ return VStack({}, renderToolLines(spec.bodyLines, theme));
719757 }
720758
721-function countVisibleTailNodes(
722- lines: readonly Node[],
723- width: number,
724- maxRows: number,
725-): number {
726- let remainingRows = maxRows;
727- let visibleLineCount = 0;
759+function renderToolBodyLines(
760+ spec: ToolBlockSpec,
761+ lines: readonly ToolRenderLine[],
762+ theme: Theme,
763+): Node | null {
764+ if (lines.length === 0) {
765+ return null;
766+ }
728767
729- for (let index = lines.length - 1; index >= 0; index--) {
730- const lineHeight = measureToolNodeHeight(lines[index]!, width);
731- if (lineHeight > remainingRows) {
732- return visibleLineCount > 0 ? visibleLineCount : 1;
768+ if (spec.highlightedBody) {
769+ const highlighted = getHighlightedBodyNode(
770+ {
771+ ...spec.highlightedBody,
772+ text: lines.map((line) => line.text).join("\n"),
773+ },
774+ theme,
775+ );
776+ if (highlighted) {
777+ return highlighted;
733778 }
734- remainingRows -= lineHeight;
735- visibleLineCount += 1;
736779 }
737780
738- return visibleLineCount;
781+ return VStack({}, renderToolLines(lines, theme));
782+}
783+
784+function wrapToolPreviewBody(body: Node): Node {
785+ return VStack(
786+ {
787+ height: UI_TOOL_PREVIEW_ROWS,
788+ justifyContent: "end",
789+ },
790+ body.type === "vstack" ? [...body.children] : [body],
791+ );
739792 }
740793
741794 function renderToolHeaderPill(
@@ -768,93 +821,47 @@ function renderToolHeaderRow(spec: ToolBlockSpec, theme: Theme): Node {
768821 return HStack({}, children);
769822 }
770823
771-function renderToolBodyFromNodes(
772- lines: readonly Node[],
773- previewBody: boolean,
774- opts: Pick<ConversationRenderOpts, "previewWidth" | "theme" | "verbose">,
824+function renderCompactToolBody(
825+ spec: ToolBlockSpec,
826+ opts: Pick<ConversationRenderOpts, "previewWidth" | "theme">,
775827 ): { body: Node | null; summary?: ToolRenderLine } {
776- if (lines.length === 0) {
828+ if (spec.bodyLines.length === 0) {
777829 return { body: null };
778830 }
779831
780- if (opts.verbose || !previewBody) {
781- return { body: VStack({}, [...lines]) };
782- }
783-
784832 const bodyWidth = getToolBodyWidth(opts.previewWidth);
785- const totalHeight = measureToolNodesHeight(lines, bodyWidth);
786- if (totalHeight <= UI_TOOL_PREVIEW_ROWS) {
787- return { body: VStack({}, [...lines]) };
788- }
833+ let previewStart = Math.max(0, spec.bodyLines.length - UI_TOOL_PREVIEW_ROWS);
789834
790- const visibleLineCount = countVisibleTailNodes(
791- lines,
792- bodyWidth,
793- UI_TOOL_PREVIEW_ROWS,
794- );
795- const previewLines = lines.slice(-visibleLineCount);
796- const hiddenLineCount = Math.max(0, lines.length - visibleLineCount);
797-
798- return {
799- body: VStack(
800- {
801- height: UI_TOOL_PREVIEW_ROWS,
802- justifyContent: "end",
803- },
804- [...previewLines],
805- ),
806- summary:
807- hiddenLineCount > 0
808- ? {
809- kind: "summary",
810- text: `And ${hiddenLineCount} lines more`,
811- }
812- : undefined,
813- };
814-}
835+ for (;;) {
836+ const previewLines = spec.bodyLines.slice(previewStart);
837+ const previewBody = renderToolBodyLines(spec, previewLines, opts.theme);
838+ if (!previewBody) {
Cut short: this commit's diff is over 1000 lines.