@@ -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 }