xonecas.io
64875
Mc

mini-coder / commit 0b937bf

feat: refactor TUI state, update cel-tui

- This was prep to store raw `Messages` json lines so we can do sessions
and save session history.

xonecas2026-04-25 0b937bf34ef88c5758d52f7cee05c93d722752d9 parent d039c9b

10 files changed

TODO.md+0−2
@@ -1,5 +1,3 @@
11 # Human's TODO list.
22
33 > This file is managed by the user, only edit if asked to.
4-
5-- [ ] `Took XXXX` label in the TUI are all wrong ahah, need to be revised.
bun.lock+4−4
@@ -115,13 +115,13 @@
115115
116116 "@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.4.13", "", { "os": "win32", "cpu": "x64" }, "sha512-tTcMkXyBrmHi9BfrD2VNHs/5rYIUKETqsBlYOvSAABwBkJhSDVb5e7wPukftsQbO3WzQkXe6kaztC6WtUOXSoQ=="],
117117
118- "@cel-tui/clew": ["@cel-tui/clew@0.8.1", "", { "peerDependencies": { "typescript": ">=5.0.0" } }, "sha512-4X021mpOQYSPR2HzmSMoxSX3wn6zoGpCgUPePdJPTy/IQe0N0vRLooDVZr74uVaUt8UxHLYUrH4WN7DuJq/YqA=="],
118+ "@cel-tui/clew": ["@cel-tui/clew@0.8.2", "", { "peerDependencies": { "typescript": ">=5.0.0" } }, "sha512-7IYKc8Pe+CCUngw9jpgNDc6LgJoPEDUr0Pqu1uNrTdwFMBaiGirV8b5Z/UbQ7/CtIyPnVDyNO2qAY/wOJNGidg=="],
119119
120- "@cel-tui/components": ["@cel-tui/components@0.8.1", "", { "dependencies": { "@cel-tui/clew": "0.8.1", "@cel-tui/core": "0.8.1", "@cel-tui/types": "0.8.1", "yoctomarkdown": "^0.1.0" }, "peerDependencies": { "typescript": ">=5.0.0" } }, "sha512-lAtTk0ECLTrcQrXEtRCrY2/o+nRNP3ygItRcBe1TSa4Je4saAW5FjBRzqbOO/lQ0zhdhaxoWugMdKMRZHcc/Ww=="],
120+ "@cel-tui/components": ["@cel-tui/components@0.8.2", "", { "dependencies": { "@cel-tui/clew": "0.8.2", "@cel-tui/core": "0.8.2", "@cel-tui/types": "0.8.2", "yoctomarkdown": "^0.1.0" }, "peerDependencies": { "typescript": ">=5.0.0" } }, "sha512-mc1CLy/EzPIpK8kxTw4CSH8XMKoXOcqTdoUx158wfFyGNO/rROEjs941Qo/D5k+VhodUlzFMj+PMzQQjrdgpeg=="],
121121
122- "@cel-tui/core": ["@cel-tui/core@0.8.1", "", { "dependencies": { "@cel-tui/types": "0.8.1", "get-east-asian-width": "^1.5.0" }, "peerDependencies": { "typescript": ">=5.0.0" } }, "sha512-ShYX/p7YaD4gCOEEZA7wKxOUQn0NblB1YGEvxqvrZi2TxgA3arUh/+o287RnPYJN5idDNHr0Obe3Aaio6YaJkQ=="],
122+ "@cel-tui/core": ["@cel-tui/core@0.8.2", "", { "dependencies": { "@cel-tui/types": "0.8.2", "get-east-asian-width": "^1.5.0" }, "peerDependencies": { "typescript": ">=5.0.0" } }, "sha512-VMrPiqYHJKpqj1cCgUni8aM4etzG5y60tmsTBcDrhGisbS02GUpv6pmXp95U0O6VVLLYzmHtoXIwAyOTfWNRjA=="],
123123
124- "@cel-tui/types": ["@cel-tui/types@0.8.1", "", { "peerDependencies": { "typescript": ">=5.0.0" } }, "sha512-Z0ehxq2f0nnV5Ia4af7xs0WgqTp9/okfmNVusTG+G5/tfcnH7bTMKbLECLmokx/MqF+a4Gcw0wwpBz3obghFeA=="],
124+ "@cel-tui/types": ["@cel-tui/types@0.8.2", "", { "peerDependencies": { "typescript": ">=5.0.0" } }, "sha512-OwaX9IZHnJO0QJ9TtKx/9LhUG/E9lWds40fkq8kgLOxcb4DHBs2xRKCBoQKOh98zsitD5NLXl7125C6Dlbk+FA=="],
125125
126126 "@google/genai": ["@google/genai@1.50.1", "", { "dependencies": { "google-auth-library": "^10.3.0", "p-retry": "^4.6.2", "protobufjs": "^7.5.4", "ws": "^8.18.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.2" }, "optionalPeers": ["@modelcontextprotocol/sdk"] }, "sha512-YbkX7H9+1Pt8wOt7DDREy8XSoiL6fRDzZQRyaVBarFf8MR3zHGqVdvM4cLbDXqPhxqvegZShgfxb8kw9C7YhAQ=="],
127127
package.json+2−2
@@ -20,8 +20,8 @@
2020 "typescript": "^6.0.3"
2121 },
2222 "dependencies": {
23- "@cel-tui/components": "^0.8.1",
24- "@cel-tui/core": "^0.8.1",
23+ "@cel-tui/components": "^0.8.2",
24+ "@cel-tui/core": "^0.8.2",
2525 "@mariozechner/pi-ai": "^0.70.2",
2626 "diff": "^9.0.0",
2727 "simple-git": "^3.36.0",
src/index.ts+1−2
@@ -1,7 +1,7 @@
11 import { handleArgv } from "./args.ts";
22 import { streamHeadless } from "./headless.ts";
33 import { initTUI } from "./tui.ts";
4-import type { TUIActiveState, TUIState } from "./types.ts";
4+import type { TUIState } from "./types.ts";
55
66 export async function main(): Promise<void> {
77 const options = await handleArgv(process.argv.slice(2));
@@ -20,7 +20,6 @@ export async function main(): Promise<void> {
2020 options,
2121 prompt: "",
2222 messages: [],
23- activeState: "idle" as TUIActiveState,
2423 streaming: false,
2524 stickToBottom: true,
2625 scrollOffset: 0,
src/tui-components.ts+16−5
@@ -91,14 +91,25 @@ export function Spinner() {
9191 }
9292
9393 export function ActivityPill(state: TUIState, spinnerFrame: string) {
94- let label = state.activeState.replaceAll("_", " ");
95- const fg = state.streaming ? theme.bblack : theme.bwhite;
96- const bg = state.streaming ? theme.bwhite : theme.bblack;
94+ let label = "idle";
9795 const frame = state.streaming ? spinnerFrame : "";
9896
9997 if (frame) {
100- label += ` ${frame}`;
98+ label = frame;
10199 }
102100
103- return TextPill(label, fg, bg);
101+ return Text(label);
102+}
103+
104+export function ContextPill(state: TUIState) {
105+ let text = "";
106+ if (!state.contextSize) {
107+ text = "0%";
108+ } else {
109+ const max = state.options.model.contextWindow;
110+ const percent = Math.floor((state.contextSize / max) * 100);
111+ text = `~${percent}%`;
112+ }
113+
114+ return TextPill(text, theme.bblack, theme.bwhite);
104115 }
src/tui-conversation.ts+85−38
@@ -1,58 +1,110 @@
1+import { SyntaxHighlight } from "@cel-tui/components";
12 import { HStack, type Node, Text, VStack } from "@cel-tui/core";
2-import { elapsedTime, relativeTime } from "./shared";
3+import type {
4+ AssistantMessage,
5+ Message,
6+ ToolResultMessage,
7+ UserMessage,
8+} from "@mariozechner/pi-ai";
9+import { estimateTokens, relativeTime } from "./shared";
310 import { TextPill, theme } from "./tui-components";
4-import { memoizedSyntaxHighlight } from "./tui-syntax-highlight";
5-import type { TUIMessage, TUIState } from "./types";
11+import type { TUIState } from "./types";
612
7-function agentMessageNode(msg: TUIMessage): Node {
8- return memoizedSyntaxHighlight(
9- (msg.id ? msg.id : "") + String(msg.timestamp),
10- msg.content,
11- "markdown",
12- );
13+function agentMessageNode(msg: AssistantMessage): Node {
14+ const textBlocks: Node[] = msg.content.map((block) => {
15+ if (block.type === "text") {
16+ return SyntaxHighlight(block.text, "markdown");
17+ }
18+ if (block.type === "thinking") {
19+ if (!block.thinking.length) return Text("");
20+
21+ const tokens = estimateTokens(block.thinking);
22+
23+ return HStack({}, [
24+ HStack({ width: 4 }, []),
25+ Text(`Thinking... (~${tokens} tokens)`, {
26+ fgColor: theme.bblack,
27+ italic: true,
28+ }),
29+ ]);
30+ }
31+
32+ let text = "";
33+ let node: Node | undefined;
34+ if ("path" in block.arguments) {
35+ text = block.arguments.path;
36+ node = Text(text);
37+ } else if ("command" in block.arguments) {
38+ text = block.arguments.command;
39+ node = SyntaxHighlight(text, "bash");
40+ } else if ("prompt" in block.arguments) {
41+ text = block.arguments.prompt;
42+ node = SyntaxHighlight(text, "markdown");
43+ } else {
44+ node = Text("Unknown tool");
45+ }
46+
47+ return VStack({ padding: { x: 4 } }, [
48+ TextPill(block.name, theme.white, theme.bblack),
49+ node,
50+ ]);
51+ });
52+
53+ return VStack({ gap: 1 }, textBlocks);
1354 }
1455
15-function userMessageNode(msg: TUIMessage): Node {
56+function userMessageNode(msg: UserMessage): Node {
57+ let text = "";
58+ if (typeof msg.content === "string") {
59+ text = msg.content;
60+ } else {
61+ text = msg.content
62+ .filter((b) => b.type === "text")
63+ .map((b) => b.text)
64+ .join("\n");
65+ }
66+
1667 return VStack(
1768 {
1869 padding: { x: 1, y: 1 },
1970 bgColor: theme.bblack,
2071 fgColor: theme.white,
2172 },
22- [
23- memoizedSyntaxHighlight(
24- msg.id ?? String(msg.timestamp),
25- msg.content,
26- "markdown",
27- ),
28- ],
73+ [SyntaxHighlight(text, "markdown")],
2974 );
3075 }
3176
32-function toolMessageNode(msg: TUIMessage): Node {
77+function toolMessageNode(msg: ToolResultMessage): Node {
78+ let textBlocks = msg.content
79+ .filter((b) => b.type === "text")
80+ .map((b) => b.text)
81+ .join("\n");
82+
83+ const newlines = textBlocks.split("\n");
84+ const max = 4;
85+ if (newlines.length > max) {
86+ textBlocks = `...\n${newlines.slice(-max).join("\n")}`;
87+ }
88+
89+ const charsPerLine = 100;
90+ if (textBlocks.length > max * charsPerLine) {
91+ textBlocks = `...${textBlocks.slice(-(max * charsPerLine))}`;
92+ }
93+
3394 return VStack({ gap: 1 }, [
34- memoizedSyntaxHighlight(
35- msg.id ?? String(msg.timestamp),
36- msg.header ?? "",
37- msg.label === "bash" ? "bash" : "markdown",
38- ),
39- Text(msg.content, { wrap: "word", fgColor: theme.bblack }),
95+ Text(textBlocks, { wrap: "word", fgColor: theme.bblack }),
4096 ]);
4197 }
4298
43-function conversationMessageNode(msg: TUIMessage): Node {
44- const dur = msg.durationMs
45- ? `Took ${elapsedTime(msg.durationMs / 1000)}`
46- : "-";
47-
99+function conversationMessageNode(msg: Message): Node {
48100 const body =
49- msg.role === "agent"
101+ msg.role === "assistant"
50102 ? agentMessageNode(msg)
51103 : msg.role === "user"
52104 ? userMessageNode(msg)
53- : msg.role === "tool"
105+ : msg.role === "toolResult"
54106 ? toolMessageNode(msg)
55- : Text(msg.content, { wrap: "word", fgColor: theme.bwhite });
107+ : Text("Unknown message?", { wrap: "word", fgColor: theme.bwhite });
56108
57109 return VStack({ gap: 1 }, [
58110 body,
@@ -61,17 +113,12 @@ function conversationMessageNode(msg: TUIMessage): Node {
61113 fgColor: theme.bblack,
62114 italic: true,
63115 }),
64- Text(dur, {
65- fgColor: theme.bblack,
66- italic: true,
67- }),
68- TextPill(msg.label ?? msg.role, theme.bwhite, theme.bblack),
116+ TextPill(msg.role, theme.bwhite, theme.bblack),
69117 ]),
70118 ]);
71119 }
72120
73121 export function Conversation(state: TUIState) {
74- // TODO: We need inteligent caching?
75122 return VStack(
76123 {
77124 flex: 1,
src/tui-state.ts+0−77
@@ -1,77 +0,0 @@
1-import type { ToolCall, ToolResultMessage } from "@mariozechner/pi-ai";
2-import { estimateTokens, secureRandomString, takeTail } from "./shared";
3-import type { TUIMessage } from "./types";
4-
5-// Create the TUIState message for context tool call and result.
6-export function createTUIToolMessage(
7- source: ToolCall | ToolResultMessage,
8- existing?: Partial<TUIMessage>,
9-): TUIMessage {
10- // This truncation is TUI only. The file is also
11- // truncated at tool level to avoid big files being
12- // sent to the llm. We truncate that even further for the user.
13- // We only show the tail of the file, which includes if the file
14- // was truncated at tool level to the user.
15-
16- // Join text if there is more than one block.
17- const showLines = 10;
18- const content = "content" in source ? source.content : [];
19- const text = content.length
20- ? content
21- .map((c) => (c.type === "text" ? c.text : ""))
22- .filter((c) => Boolean(c))
23- .join("\n")
24- : (existing?.content ?? "");
25- // Grab the tail
26- let tail = takeTail(text.split("\n"), showLines).join("\n");
27- // Some commands output without newlines tons of chars.
28- // if needed to take roughly X lines at 100 chars worth of tail.
29- if (tail.length > showLines * 100) {
30- tail = tail.slice(showLines * 100 * -1);
31- }
32-
33- // Now the similar cut is needed in arguments, but here we care about
34- // seeing the start of the command, like `cd bla/ && cat ...`
35- const argsMaxLength = 100 * showLines; // estimated by 100 char line width times X lines.
36- let args = existing?.header ?? "Writing...";
37-
38- // Shell tool call
39- if ("arguments" in source && "command" in source.arguments) {
40- args =
41- source.arguments?.command?.length > argsMaxLength
42- ? source.arguments.command.substring(0, argsMaxLength)
43- : source.arguments.command;
44- }
45-
46- // Task tool call
47- if ("arguments" in source && "prompt" in source.arguments) {
48- args =
49- source.arguments?.prompt?.length > argsMaxLength
50- ? source.arguments.prompt.substring(0, argsMaxLength)
51- : source.arguments.prompt;
52- }
53-
54- // Edit tool call
55- if ("arguments" in source && "path" in source.arguments) {
56- const before = source.arguments.oldText;
57- const after = source.arguments.newText;
58- const tokensWritten = estimateTokens(
59- [source.arguments.path, before, after].join(""),
60- );
61- args = `Wrote ~${tokensWritten} tokens.`;
62- }
63-
64- const msg: TUIMessage = {
65- id: "id" in source ? source.id : (existing?.id ?? secureRandomString(8)),
66- timestamp:
67- "timestamp" in source
68- ? source.timestamp
69- : (existing?.timestamp ?? Date.now()),
70- role: "tool",
71- label: "name" in source ? source.name : (existing?.label ?? ""),
72- header: args,
73- content: tail,
74- durationMs: existing?.durationMs ? existing.durationMs : 0,
75- };
76- return msg;
77-}
src/tui-syntax-highlight.ts+0−54
@@ -1,54 +0,0 @@
1-import {
2- SyntaxHighlight,
3- type SyntaxHighlightProps,
4-} from "@cel-tui/components";
5-import type { ContainerNode } from "@cel-tui/types";
6-
7-type CacheEntry = {
8- content: string;
9- language: string;
10- themeKey: string;
11- node: ContainerNode;
12-};
13-
14-// We don't care about cache size for now. When we have sessions
15-// We need to clear cache between sessions.
16-const cache = new Map<string, CacheEntry>();
17-
18-function getThemeKey(props?: SyntaxHighlightProps): string {
19- return JSON.stringify(props?.theme ?? null);
20-}
21-
22-export function memoizedSyntaxHighlight(
23- messageKey: string,
24- content: string,
25- language = "markdown",
26- props?: SyntaxHighlightProps,
27-): ContainerNode {
28- const themeKey = getThemeKey(props);
29- const cached = cache.get(messageKey);
30-
31- if (
32- cached &&
33- cached.content === content &&
34- cached.language === language &&
35- cached.themeKey === themeKey
36- ) {
37- return cached.node;
38- }
39-
40- const node = SyntaxHighlight(content, language, props);
41-
42- cache.set(messageKey, {
43- content,
44- language,
45- themeKey,
46- node,
47- });
48-
49- return node;
50-}
51-
52-export function clearSyntaxHighlightCache(): void {
53- cache.clear();
54-}
src/tui.ts+58−152
@@ -9,15 +9,20 @@ import type {
99 } from "@mariozechner/pi-ai";
1010 import { MAIN_PROMPT, streamAgent } from "./agent";
1111 import { getApiKey } from "./oauth";
12-import { estimateTokens, secureRandomString } from "./shared";
12+import { estimateTokens } from "./shared";
1313 import { bash, runBashTool } from "./tool-bash";
1414 import { edit, runEditTool } from "./tool-edit";
1515 import { runTaskTool, task } from "./tool-task";
16-import { ActivityPill, Spinner, TextPill, theme } from "./tui-components";
16+import {
17+ ActivityPill,
18+ ContextPill,
19+ Spinner,
20+ TextPill,
21+ theme,
22+} from "./tui-components";
1723 import { Conversation } from "./tui-conversation";
1824 import { Editor } from "./tui-editor";
19-import { createTUIToolMessage } from "./tui-state";
20-import type { ToolAndRunner, TUIMessage, TUIState } from "./types";
25+import type { ToolAndRunner, TUIState } from "./types";
2126
2227 function clearOrAbort(state: TUIState) {
2328 // Are we mid stream? Abort it.
@@ -28,36 +33,21 @@ function clearOrAbort(state: TUIState) {
2833 // Is the user clearing a state prompt?
2934 if (state.prompt?.length) {
3035 state.prompt = "";
31- cel.render();
3236 }
3337 }
3438
35-function ContextPill(state: TUIState) {
36- let text = "";
37- if (!state.context) {
38- text = "0%";
39- } else {
40- const current = estimateTokens(JSON.stringify(state.context));
41- const max = state.options.model.contextWindow;
42- const percent = Math.floor((current / max) * 100);
43- text = `~${percent}%`;
44- }
45-
46- return TextPill(text, theme.bblack, theme.bwhite);
47-}
48-
4939 export function initTUI(state: TUIState, leave: (s: string) => void) {
5040 const cwd = basename(process.cwd());
5141 const { spinnerEvery, currentSpinner } = Spinner();
5242
53- // Spinner and animations timer.
43+ // Stable 60fps rendering.
5444 // This ensure Xfps, and excessive calls get coalesced in cel-tui.
55- const fps = 30;
45+ const fps = 60;
5646 const baseFramerateIntervalId = setInterval(() => {
5747 if (state.streaming) {
5848 spinnerEvery();
59- cel.render();
6049 }
50+ cel.render();
6151 }, 1000 / fps);
6252
6353 cel.init(new ProcessTerminal());
@@ -97,7 +87,6 @@ export function initTUI(state: TUIState, leave: (s: string) => void) {
9787 (value: string) => {
9888 // onChange
9989 state.prompt = value;
100- cel.render();
10190 },
10291 (key: string) => {
10392 // onKeyPress
@@ -139,156 +128,73 @@ export async function streamTUI(state: TUIState) {
139128 },
140129 },
141130 ];
142- const userPrompt = {
131+
132+ const userMessage: Message = {
143133 role: "user",
144134 content: state.prompt || "",
145135 timestamp: Date.now(),
146- id: secureRandomString(8),
147136 };
148- state.messages.push(userPrompt as TUIMessage);
149- let messages: Message[] = [userPrompt as Message];
150- if (state.context) {
151- messages = [...state.context.messages, ...messages];
152- }
137+ state.messages.push(userMessage);
138+ const existingMessages: Message[] = [...state.messages];
139+
153140 state.prompt = "";
154141 cel.render();
155142
156- const onStream = (ev: AssistantMessageEvent, context: Context) => {
157- state.context = context;
143+ let partial: AssistantMessage | null = null;
158144
159- // TODO: Improve `src/tui-state.ts` so we can progressively build the ui
160- // as the data comes in, instead of relying on the final message.
161- // We can do this with the base stream events and our tool callback.
162- // onComplete should be only cleanup at that point, no messages state updates.
145+ const onStream = (ev: AssistantMessageEvent, ctx: Context) => {
163146 switch (ev.type) {
164- case "text_start":
165- state.activeState = "answering";
166- cel.render();
147+ case "start":
148+ partial = ev.partial;
149+ state.messages.push(partial);
150+ state.contextSize = estimateTokens(JSON.stringify(ctx));
167151 break;
168152
153+ case "text_start":
154+ case "text_delta":
155+ case "text_end":
169156 case "thinking_start":
170- state.activeState = "thinking";
171- cel.render();
172- break;
173-
174- case "toolcall_start": {
175- state.activeState = "calling_tool";
176-
177- // Create initial tool tui messages
178- const newToolCalls = ev.partial.content.filter(
179- (c) => c.type === "toolCall",
180- );
181-
182- for (const call of newToolCalls) {
183- const toolMessage = createTUIToolMessage(call);
184- let found = false;
185- state.messages = state.messages.map((msg) => {
186- if (call.id === msg.id) {
187- found = true;
188- return toolMessage;
189- }
190- return msg;
191- });
192- if (!found) state.messages.push(toolMessage);
157+ case "thinking_delta":
158+ case "thinking_end":
159+ case "toolcall_start":
160+ case "toolcall_delta":
161+ case "toolcall_end":
162+ if (partial) {
163+ partial = ev.partial;
164+ state.messages[state.messages.length - 1] = partial;
165+ state.contextSize = estimateTokens(JSON.stringify(ctx));
193166 }
194-
195- cel.render();
196- break;
197- }
198-
199- case "toolcall_end": {
200- state.activeState = "waiting";
201-
202- // Collect tool calls state
203- const finishedToolCalls = ev.partial.content.filter(
204- (c) => c.type === "toolCall",
205- );
206-
207- // Update tui messages with arguments
208- for (const call of finishedToolCalls) {
209- let updated = false;
210- state.messages = state.messages.map((msg) => {
211- if (call.id === msg.id) {
212- updated = true;
213- return createTUIToolMessage(call, msg);
214- }
215- return msg;
216- });
217- if (!updated) {
218- state.messages.push(createTUIToolMessage(call));
219- }
220- }
221-
222- cel.render();
223- break;
224- }
225-
226- case "done":
227- state.activeState = "waiting";
228- cel.render();
229- break;
230-
231- case "error":
232- state.activeState = "idle";
233167 break;
234168 }
235169 };
236170
237- const onTool = (tool: ToolResultMessage, context: Context) => {
238- // Append the output to the existing TUI messages
239- state.messages = state.messages.map((msg) => {
240- if (tool.toolCallId === msg.id) {
241- return createTUIToolMessage(tool, {
242- ...msg,
243- durationMs: Date.now() - msg.timestamp,
244- });
245- }
246- return msg;
247- });
248- state.context = context;
249- cel.render();
171+ const onTool = (tool: ToolResultMessage, ctx: Context) => {
172+ state.messages.push(tool);
173+ state.contextSize = estimateTokens(JSON.stringify(ctx));
250174 };
251175
252- const onComplete = (msg: AssistantMessage, context: Context) => {
253- const dur = Date.now() - msg.timestamp;
254-
255- if (msg.errorMessage) {
256- state.messages.push({
257- id: secureRandomString(8),
258- role: "agent",
259- content: `Error (${msg.stopReason}): ${msg.errorMessage}`,
260- timestamp: msg.timestamp,
261- durationMs: dur,
262- });
176+ const onComplete = (msg: AssistantMessage, ctx: Context) => {
177+ if (partial) {
178+ state.messages[state.messages.length - 1] = msg;
263179 } else {
264- const text = msg.content
265- .filter((c) => c.type === "text")
266- .map((c) => c.text)
267- .join("\n");
268- state.messages.push({
269- id: secureRandomString(8),
270- role: "agent",
271- content: text,
272- timestamp: msg.timestamp,
273- durationMs: dur,
274- });
180+ state.messages.push(msg);
275181 }
276-
277- state.streaming = false;
278- state.activeState = "idle";
279- state.context = context;
280- cel.render();
182+ state.contextSize = estimateTokens(JSON.stringify(ctx));
281183 };
282184
283- await streamAgent(
284- apiKey,
285- tools,
286- MAIN_PROMPT,
287- messages,
288- state.options,
289- state.abortController,
290- onStream,
291- onTool,
292- onComplete,
293- );
185+ try {
186+ await streamAgent(
187+ apiKey,
188+ tools,
189+ MAIN_PROMPT,
190+ existingMessages,
191+ state.options,
192+ state.abortController,
193+ onStream,
194+ onTool,
195+ onComplete,
196+ );
197+ } finally {
198+ state.streaming = false;
199+ }
294200 }
src/types.ts+4−22
@@ -1,4 +1,4 @@
1-import type { Context, Model, ThinkingLevel, Tool } from "@mariozechner/pi-ai";
1+import type { Message, Model, ThinkingLevel, Tool } from "@mariozechner/pi-ai";
22 import type { OAuthCredentials } from "@mariozechner/pi-ai/oauth";
33
44 export type CliOptions = {
@@ -8,32 +8,14 @@ export type CliOptions = {
88 jsonOutput?: boolean;
99 };
1010
11-export type TUIActiveState =
12- | "idle"
13- | "waiting"
14- | "thinking"
15- | "answering"
16- | "calling_tool";
17-
18-export type TUIMessage = {
19- content: string;
20- role: "agent" | "tool" | "reasoning" | "user";
21- durationMs?: number;
22- id?: string;
23- timestamp: number;
24- label?: string;
25- header?: string; // Not a great name, this is used for arguments in tool calls.
26-};
27-
2811 export type TUIState = {
2912 options: CliOptions;
3013 prompt: string;
31- messages: TUIMessage[];
32- context?: Context;
33- activeState: TUIActiveState;
34- streaming: boolean;
14+ messages: Message[];
15+ contextSize?: number;
3516 stickToBottom: boolean;
3617 scrollOffset: number;
18+ streaming: boolean;
3719 abortController?: AbortController;
3820 };