@@ -23,7 +23,6 @@ import {
2323 } from "./session.ts";
2424 import { DEFAULT_SHOW_REASONING, DEFAULT_VERBOSE } from "./settings.ts";
2525 import { DEFAULT_THEME } from "./theme.ts";
26-import * as uiModule from "./ui.ts";
2726 import {
2827 buildConversationLog,
2928 createInputController,
@@ -49,20 +48,28 @@ function collectText(node: Node | null): string[] {
4948 return node.children.flatMap((child) => collectText(child));
5049 }
5150
52-function findNodeWithKeyPress(node: Node | null): ContainerNode | null {
53- if (!node || node.type === "textinput" || node.type === "text") {
54- return null;
51+function expectTextInput(node: Node): Extract<Node, { type: "textinput" }> {
52+ if (node.type !== "textinput") {
53+ throw new Error("Expected input area to render a TextInput");
5554 }
56- if (typeof node.props.onKeyPress === "function") {
57- return node;
58- }
59- for (const child of node.children) {
60- const found = findNodeWithKeyPress(child);
61- if (found) {
62- return found;
63- }
55+ return node;
56+}
57+
58+function expectVStack(node: Node): ContainerNode {
59+ if (node.type !== "vstack") {
60+ throw new Error("Expected app layout to be a vstack");
6461 }
65- return null;
62+ return node;
63+}
64+
65+function createDeferred<T = void>() {
66+ let resolve!: (value: T | PromiseLike<T>) => void;
67+ let reject!: (reason?: unknown) => void;
68+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
69+ resolve = resolvePromise;
70+ reject = rejectPromise;
71+ });
72+ return { promise, resolve, reject };
6673 }
6774
6875 const tempDirs: string[] = [];
@@ -126,7 +133,7 @@ async function waitFor(
126133 if (predicate()) {
127134 return;
128135 }
129- await Bun.sleep(10);
136+ await new Promise<void>((resolve) => setImmediate(resolve));
130137 }
131138 throw new Error("Timed out waiting for condition");
132139 }
@@ -147,20 +154,6 @@ async function stopRunningTurn(
147154 }
148155
149156 describe("ui rendering", () => {
150- test("ui.ts keeps command and render helpers private", () => {
151- const exports = Object.keys(uiModule);
152-
153- expect(exports).not.toContain("applyEffortSelection");
154- expect(exports).not.toContain("applyModelSelection");
155- expect(exports).not.toContain("buildHelpText");
156- expect(exports).not.toContain("formatPromptHistoryPreview");
157- expect(exports).not.toContain("formatRelativeDate");
158- expect(exports).not.toContain("previewToolRenderLines");
159- expect(exports).not.toContain("renderAssistantMessage");
160- expect(exports).not.toContain("renderStatusBar");
161- expect(exports).not.toContain("renderToolResult");
162- });
163-
164157 test("reasoning defaults on and verbose defaults off", () => {
165158 expect(DEFAULT_SHOW_REASONING).toBe(true);
166159 expect(DEFAULT_VERBOSE).toBe(false);
@@ -210,6 +203,7 @@ describe("ui rendering", () => {
210203 return message;
211204 };
212205
206+ const finishStream = createDeferred<void>();
213207 const buildProviderStream = () => {
214208 const stream = createAssistantMessageEventStream();
215209 const finalMessage = createFinalMessage();
@@ -246,14 +240,14 @@ describe("ui rendering", () => {
246240 ],
247241 },
248242 });
249- setTimeout(() => {
243+ void finishStream.promise.then(() => {
250244 stream.push({
251245 type: "done",
252246 reason: "stop",
253247 message: finalMessage,
254248 });
255249 stream.end(finalMessage);
256- }, 50);
250+ });
257251 });
258252
259253 return stream;
@@ -301,6 +295,7 @@ describe("ui rendering", () => {
301295 const streamedText = streamedLogText.join("\n");
302296 expect(streamedText).toBe("hello\nBefore\nThinking... 2 lines.\nAfter");
303297
298+ finishStream.resolve();
304299 await waitFor(() =>
305300 state.messages.some((message) => message.role === "assistant"),
306301 );
@@ -536,32 +531,31 @@ describe("ui rendering", () => {
536531 timestamp: Date.now(),
537532 });
538533
534+ const abortObserved = createDeferred<void>();
535+ const releaseAbort = createDeferred<void>();
539536 const buildProviderStream = (signal?: AbortSignal) => {
540537 const stream = createAssistantMessageEventStream();
541538
542539 queueMicrotask(() => {
543540 const emitAbort = () => {
544- const abortedMessage = buildAbortMessage();
545- stream.push({
546- type: "error",
547- reason: "aborted",
548- error: abortedMessage,
541+ abortObserved.resolve();
542+ void releaseAbort.promise.then(() => {
543+ const abortedMessage = buildAbortMessage();
544+ stream.push({
545+ type: "error",
546+ reason: "aborted",
547+ error: abortedMessage,
548+ });
549+ stream.end(abortedMessage);
549550 });
550- stream.end(abortedMessage);
551551 };
552552
553553 if (signal?.aborted) {
554- setTimeout(emitAbort, 50);
554+ emitAbort();
555555 return;
556556 }
557557
558- signal?.addEventListener(
559- "abort",
560- () => {
561- setTimeout(emitAbort, 50);
562- },
563- { once: true },
564- );
558+ signal?.addEventListener("abort", emitAbort, { once: true });
565559 });
566560
567561 return stream;
@@ -594,6 +588,10 @@ describe("ui rendering", () => {
594588
595589 handleInput("/undo", state);
596590
591+ await abortObserved.promise;
592+ expect(state.running).toBe(true);
593+
594+ releaseAbort.resolve();
597595 await waitFor(() => !state.running);
598596 await waitFor(() => state.messages.length === 0);
599597
@@ -735,76 +733,6 @@ describe("ui rendering", () => {
735733 }
736734 });
737735
738- test("/session resumes a stored session even when historical assistant usage is missing", () => {
739- const state = createTestState();
740- const now = Date.now();
741- const session = createSession(state.db, {
742- cwd: state.canonicalCwd,
743- model: "test/beta",
744- effort: "high",
745- });
746-
747- try {
748- state.db.run(
749- "INSERT INTO messages (session_id, turn, data, created_at) VALUES (?, ?, ?, ?)",
750- [
751- session.id,
752- 1,
753- JSON.stringify({
754- role: "user",
755- content: "historical prompt",
756- timestamp: now,
757- }),
758- now,
759- ],
760- );
761- state.db.run(
762- "INSERT INTO messages (session_id, turn, data, created_at) VALUES (?, ?, ?, ?)",
763- [
764- session.id,
765- 1,
766- JSON.stringify({
767- role: "assistant",
768- content: [{ type: "text", text: "historical reply" }],
769- api: "anthropic-messages",
770- provider: "anthropic",
771- model: "test/beta",
772- stopReason: "stop",
773- timestamp: now + 1,
774- }),
775- now + 1,
776- ],
777- );
778- state.db.run("UPDATE sessions SET updated_at = ? WHERE id = ?", [
779- now + 1,
780- session.id,
781- ]);
782-
783- handleInput("/session", state);
784-
785- const overlay = renderActiveOverlay(state);
786- const selectNode = findNodeWithKeyPress(overlay);
787-
788- expect(selectNode).not.toBeNull();
789- if (!selectNode) {
790- throw new Error("Expected overlay to contain a Select root");
791- }
792-
793- selectNode.props.onKeyPress?.("enter");
794-
795- expect(renderActiveOverlay(state)).toBeNull();
796- expect(state.session?.id).toBe(session.id);
797-
798- const layout = renderBaseLayout(state, 80, createInputController(state));
799- const text = collectText(layout);
800-
801- expect(text).toContain("historical prompt");
802- expect(text).toContain("historical reply");
803- } finally {
804- state.db.close();
805- }
806- });
807-
808736 test("/new clears the active session and defers replacement session creation", async () => {
809737 const faux = registerFauxProvider();
810738 const state = createTestState();
@@ -970,6 +898,7 @@ describe("ui rendering", () => {
970898 };
971899
972900 let callCount = 0;
901+ const finishFirstStream = createDeferred<void>();
973902 const finalToolCall = fauxToolCall(
974903 "shell",
975904 { command: "echo staged-command" },
@@ -1024,30 +953,26 @@ describe("ui rendering", () => {
1024953 contentIndex: 0,
1025954 partial: partialStart,
1026955 });
1027- setTimeout(() => {
956+ stream.push({
957+ type: "toolcall_delta",
958+ contentIndex: 0,
959+ delta: '{"command":"echo staged-command"}',
960+ partial: partialDelta,
961+ });
962+ stream.push({
963+ type: "toolcall_end",
964+ contentIndex: 0,
965+ toolCall: finalToolCall,
966+ partial: finalMessage,
967+ });
968+ void finishFirstStream.promise.then(() => {
1028969 stream.push({
1029- type: "toolcall_delta",
1030- contentIndex: 0,
1031- delta: '{"command":"echo staged-command"}',
1032- partial: partialDelta,
970+ type: "done",
971+ reason: "toolUse",
972+ message: finalMessage,
1033973 });
1034- setTimeout(() => {
1035- stream.push({
1036- type: "toolcall_end",
1037- contentIndex: 0,
1038- toolCall: finalToolCall,
1039- partial: finalMessage,
1040- });
1041- setTimeout(() => {
1042- stream.push({
1043- type: "done",
1044- reason: "toolUse",
1045- message: finalMessage,
1046- });
1047- stream.end(finalMessage);
1048- }, 150);
1049- }, 30);
1050- }, 30);
974+ stream.end(finalMessage);
975+ });
1051976 });
1052977
1053978 return stream;
@@ -1102,6 +1027,9 @@ describe("ui rendering", () => {
11021027 logText.filter((line) => line === "$ echo staged-command"),
11031028 ).toHaveLength(1);
11041029 expect(logText).not.toContain("Preparing...");
1030+
1031+ finishFirstStream.resolve();
1032+ await waitFor(() => !state.running);
11051033 } finally {
11061034 await stopRunningTurn(state);
11071035 unregisterApiProviders(sourceId);
@@ -1126,6 +1054,7 @@ describe("ui rendering", () => {
11261054 };
11271055
11281056 let callCount = 0;
1057+ const finishSecondStream = createDeferred<void>();
11291058 const buildProviderStream = () => {
11301059 callCount += 1;
11311060 const stream = createAssistantMessageEventStream();
@@ -1199,14 +1128,14 @@ describe("ui rendering", () => {
11991128 delta: "Done streaming",
12001129 partial,
12011130 });
1202- setTimeout(() => {
1131+ void finishSecondStream.promise.then(() => {
12031132 stream.push({
12041133 type: "done",
12051134 reason: "stop",
12061135 message: finalMessage,
12071136 });
12081137 stream.end(finalMessage);
1209- }, 200);
1138+ });
12101139 });
12111140
12121141 return stream;
@@ -1258,6 +1187,9 @@ describe("ui rendering", () => {
12581187 expect(logText).not.toContain("Exit code: 0");
12591188 expect(logText).not.toContain("Preparing...");
12601189 expect(logText).not.toContain("Running...");
1190+
1191+ finishSecondStream.resolve();
1192+ await waitFor(() => !state.running);
12611193 } finally {
12621194 await stopRunningTurn(state);
12631195 process.env.PATH = originalPath;
@@ -1266,42 +1198,6 @@ describe("ui rendering", () => {
12661198 }
12671199 });
12681200
1269- test("renderInputArea returns a direct TextInput with stable handlers", () => {
1270- const state = createTestState();
1271-
1272- try {
1273- const controller = createInputController(state);
1274- const firstInput = renderInputArea(state.theme, controller);
1275- const secondInput = renderInputArea(state.theme, controller);
1276-
1277- expect(firstInput.type).toBe("textinput");
1278- expect(secondInput.type).toBe("textinput");
1279- if (firstInput.type !== "textinput" || secondInput.type !== "textinput") {
1280- throw new Error("Expected direct TextInput nodes");
1281- }
1282-
1283- expect(firstInput.props.placeholder?.props.fgColor).toBe(
1284- state.theme.mutedText,
1285- );
1286- expect(firstInput.props.padding).toEqual({ x: 1 });
1287- expect(firstInput.props.minHeight).toBe(2);
1288- expect(firstInput.props.maxHeight).toBe(10);
1289- expect(firstInput.props.onChange).toBe(controller.onChange);
1290- expect(firstInput.props.onFocus).toBe(controller.onFocus);
1291- expect(firstInput.props.onBlur).toBe(controller.onBlur);
1292- expect(firstInput.props.onKeyPress).toBe(controller.onKeyPress);
1293- expect(secondInput.props.padding).toEqual(firstInput.props.padding);
1294- expect(secondInput.props.minHeight).toBe(firstInput.props.minHeight);
1295- expect(secondInput.props.maxHeight).toBe(firstInput.props.maxHeight);
1296- expect(secondInput.props.onChange).toBe(firstInput.props.onChange);
1297- expect(secondInput.props.onFocus).toBe(firstInput.props.onFocus);
1298- expect(secondInput.props.onBlur).toBe(firstInput.props.onBlur);
1299- expect(secondInput.props.onKeyPress).toBe(firstInput.props.onKeyPress);
1300- } finally {
1301- state.db.close();
1302- }
1303- });
1304-
13051201 test("Tab autocompletes the last file path in normal input mode", () => {
13061202 const state = createTestState();
13071203 const cwd = createTempDir();
@@ -1316,10 +1212,7 @@ describe("ui rendering", () => {
13161212
13171213 expect(controller.onKeyPress("tab")).toBe(false);
13181214
1319- const input = renderInputArea(state.theme, controller);
1320- if (input.type !== "textinput") {
1321- throw new Error("Expected input area to render a TextInput");
1322- }
1215+ const input = expectTextInput(renderInputArea(state.theme, controller));
13231216 expect(input.props.value).toBe("inspect src/ui.ts");
13241217 expect(renderActiveOverlay(state)).toBeNull();
13251218 } finally {
@@ -1341,16 +1234,14 @@ describe("ui rendering", () => {
13411234 });
13421235
13431236 const controller = createInputController(state);
1344- const base = renderBaseLayout(state, 80, controller);
1345-
1346- expect(base.type).toBe("vstack");
1347- if (base.type !== "vstack") {
1348- throw new Error("Expected base layout to be a vstack");
1349- }
1237+ const base = expectVStack(renderBaseLayout(state, 80, controller));
13501238
13511239 base.props.onKeyPress?.("ctrl+r");
13521240
13531241 const overlay = renderActiveOverlay(state);
1242+ if (!overlay) {
1243+ throw new Error("Expected an active input history overlay");
1244+ }
13541245 const text = collectText(overlay);
13551246 const newestIndex = text.findIndex((line) =>
13561247 line.includes("newest prompt"),
@@ -1359,7 +1250,6 @@ describe("ui rendering", () => {
13591250 line.includes("older prompt"),
13601251 );
13611252
1362- expect(overlay).not.toBeNull();
13631253 expect(text).toContain("Input history");
13641254 expect(newestIndex).toBeGreaterThan(-1);
13651255 expect(olderIndex).toBeGreaterThan(-1);
@@ -1369,91 +1259,7 @@ describe("ui rendering", () => {
13691259 }
13701260 });
13711261
1372- test("selecting input history restores the exact raw prompt into the input", () => {
1373- const state = createTestState();
1374- const rawPrompt = "first line\nsecond line";
1375-
1376- try {
1377- appendPromptHistory(state.db, {
1378- text: "older prompt",
1379- cwd: "/tmp/older",
1380- });
1381- appendPromptHistory(state.db, {
1382- text: rawPrompt,
1383- cwd: state.cwd,
1384- });
1385-
1386- const controller = createInputController(state);
1387- const base = renderBaseLayout(state, 80, controller);
1388- if (base.type !== "vstack") {
1389- throw new Error("Expected base layout to be a vstack");
1390- }
1391-
1392- base.props.onKeyPress?.("ctrl+r");
1393-
1394- const overlay = renderActiveOverlay(state);
1395- const selectNode = findNodeWithKeyPress(overlay);
1396-
1397- expect(selectNode).not.toBeNull();
1398- if (!selectNode) {
1399- throw new Error("Expected overlay to contain a Select root");
1400- }
1401-
1402- selectNode.props.onKeyPress?.("enter");
1403-
1404- expect(renderActiveOverlay(state)).toBeNull();
1405- const input = renderInputArea(state.theme, controller);
1406- if (input.type !== "textinput") {
1407- throw new Error("Expected input area to render a TextInput");
1408- }
1409- expect(input.props.value).toBe(rawPrompt);
1410- } finally {
1411- state.db.close();
1412- }
1413- });
1414-
1415- test("dismissing input history keeps the current draft unchanged", () => {
1416- const state = createTestState();
1417- const draft = "draft prompt";
1418-
1419- try {
1420- appendPromptHistory(state.db, {
1421- text: "saved prompt",
1422- cwd: state.cwd,
1423- });
1424-
1425- const controller = createInputController(state);
1426- controller.onChange(draft);
1427-
1428- const base = renderBaseLayout(state, 80, controller);
1429- if (base.type !== "vstack") {
1430- throw new Error("Expected base layout to be a vstack");
1431- }
1432-
1433- base.props.onKeyPress?.("ctrl+r");
1434-
1435- const overlay = renderActiveOverlay(state);
1436- const selectNode = findNodeWithKeyPress(overlay);
1437-
1438- expect(selectNode).not.toBeNull();
1439- if (!selectNode) {
1440- throw new Error("Expected overlay to contain a Select root");
1441- }
1442-
1443- selectNode.props.onBlur?.();
1444-
1445- expect(renderActiveOverlay(state)).toBeNull();
1446- const input = renderInputArea(state.theme, controller);
1447- if (input.type !== "textinput") {
1448- throw new Error("Expected input area to render a TextInput");
1449- }
1450- expect(input.props.value).toBe(draft);
1451- } finally {
1452- state.db.close();
1453- }
1454- });
1455-
1456- test("renderBaseLayout keeps a single divider between the log and input", () => {
1262+ test("renderBaseLayout shows a single divider line between the conversation and input areas", () => {
14571263 const state = createTestState();
14581264 const controller: InputController = {
14591265 onChange: () => {},
@@ -1463,17 +1269,9 @@ describe("ui rendering", () => {
14631269 };
14641270
14651271 try {
1466- const node = renderBaseLayout(state, 80, controller);
1272+ const text = collectText(renderBaseLayout(state, 80, controller));
14671273
1468- expect(node.type).toBe("vstack");
1469- if (node.type !== "vstack") {
1470- throw new Error("Expected app layout to be a VStack");
1471- }
1472- expect(node.children).toHaveLength(4);
1473- expect(node.children[0]?.type).toBe("vstack");
1474- expect(node.children[1]?.type).toBe("text");
1475- expect(node.children[2]?.type).toBe("textinput");
1476- expect(node.children[3]?.type).toBe("hstack");
1274+ expect(text.filter((line) => line === "─")).toHaveLength(1);
14771275 } finally {
14781276 state.db.close();
14791277 }
@@ -1490,14 +1288,11 @@ describe("ui rendering", () => {
14901288 let suspended = false;
14911289
14921290 try {
1493- const node = renderBaseLayout(state, 80, controller, () => {
1494- suspended = true;
1495- });
1496-
1497- expect(node.type).toBe("vstack");
1498- if (node.type !== "vstack") {
1499- throw new Error("Expected app layout to be a VStack");
1500- }
1291+ const node = expectVStack(
1292+ renderBaseLayout(state, 80, controller, () => {
1293+ suspended = true;
1294+ }),
1295+ );
15011296
15021297 node.props.onKeyPress?.("ctrl+z");
15031298 expect(suspended).toBe(true);