@@ -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 = {