xonecas.io
64875
Mc

mini-coder / commit 64c439a

feat: performance improvements and nicer spinner

xonecas2026-04-24 64c439a9fcdc93b8256523497bf6c9b07369b581 parent 2b99259

6 files changed

src/agent.ts+28−2
@@ -1,3 +1,5 @@
1+import { homedir } from "node:os";
2+import { join } from "node:path";
13 import {
24 type AssistantMessage,
35 type AssistantMessageEvent,
@@ -14,11 +16,32 @@ export const TASK_PROMPT = `# You are "mini-coder", an elite coding agent.
1416 Behaviour guidelines:
1517
1618 - Answer all user questions without guessing, or assuming. Use recent online information and your training data combined for a complete answer.
19+- Once you've gathered enough information to complete the request, stop exploring.
1720 - When completing a task, ensure that you fulfill the contract **exactly**.
21+- Use temp directory for temp files, scripts or anything that doesn't match the requested ouput.
1822 - Tone: use a jovial but motivated colleague persona. Be less verbose and more concise. You are working with software engineers, act appropriate, no fluff, only direct talk.
1923 `;
2024
21-// TODO: `AGENTS.md` support: find it in current folder and a global one. (`.agents/AGENTS.md` || ~/.AGENTS.md)
25+// `AGENTS.md` support: find it in current folder (.AGENTS.md) and a global one. (`.agents/AGENTS.md`)
26+export async function getAGENTSFiles() {
27+ const content: string[] = [];
28+
29+ const globalPath = join(homedir(), ".agents/AGENTS.md");
30+ const globalFile = Bun.file(globalPath);
31+
32+ if (await globalFile.exists()) {
33+ content.push(await globalFile.text());
34+ }
35+
36+ const localPath = join(process.cwd(), "AGENTS.md");
37+ const localFile = Bun.file(localPath);
38+
39+ if (await localFile.exists()) {
40+ content.push(await localFile.text());
41+ }
42+
43+ return content.join("\n\n");
44+}
2245
2346 export async function streamAgent(
2447 apiKey: string,
@@ -30,8 +53,11 @@ export async function streamAgent(
3053 toolsFn?: (tool: ToolResultMessage) => void,
3154 completeFn?: (msg: AssistantMessage, context: Context) => void,
3255 ) {
56+ const agentsContent = await getAGENTSFiles();
57+ const completeSystemPrompt = `${systemPrompt}\n${agentsContent}`;
58+
3359 const context: Context = {
34- systemPrompt,
60+ systemPrompt: completeSystemPrompt,
3561 messages,
3662 tools: tools.map((t) => t.tool),
3763 };
src/shared.ts+4−0
@@ -73,3 +73,7 @@ export function onceEvery<T extends unknown[]>(
7373 export function takeTail<T>(arr: T[], x: number): T[] {
7474 return x <= 0 ? [] : arr.slice(-x);
7575 }
76+
77+export function extimateTokens(text: string): number {
78+ return Math.ceil(text.length / 4);
79+}
src/tool-bash.ts+2−0
@@ -21,6 +21,8 @@ Best practices using this tool:
2121 - Avoid overly complex one-liners, readability matters.
2222 - Quote filenames: use \`"$file"\` not \`$file\`
2323 - Be careful with spaces in filenames
24+
25+Current working directory: ${process.cwd()}
2426 `;
2527
2628 export const bash: Tool = {
src/tui-conversation.ts+142−38
@@ -1,10 +1,29 @@
1-import { cel, HStack, Text, VStack } from "@cel-tui/core";
1+import {
2+ HStack,
3+ measureContentHeight,
4+ type Node,
5+ Text,
6+ VStack,
7+} from "@cel-tui/core";
28 import { elapsedTime, relativeTime } from "./shared";
39 import { TextPill, theme } from "./tui-components";
410 import { memoizedSyntaxHighlight } from "./tui-syntax-highlight";
511 import type { TUIMessage, TUIState } from "./types";
612
7-function agentMessageNode(msg: TUIMessage) {
13+const gap = 1;
14+
15+type ConversationLayout = {
16+ messages: TUIMessage[];
17+ count: number;
18+ width: number;
19+ heights: number[];
20+ tops: number[];
21+ totalHeight: number;
22+};
23+
24+let cachedLayout: ConversationLayout | undefined;
25+
26+function agentMessageNode(msg: TUIMessage): Node {
827 return memoizedSyntaxHighlight(
928 (msg.id ? msg.id : "") + String(msg.timestamp),
1029 msg.content,
@@ -12,7 +31,7 @@ function agentMessageNode(msg: TUIMessage) {
1231 );
1332 }
1433
15-function userMessageNode(msg: TUIMessage) {
34+function userMessageNode(msg: TUIMessage): Node {
1635 return VStack(
1736 {
1837 padding: { x: 1, y: 1 },
@@ -29,7 +48,7 @@ function userMessageNode(msg: TUIMessage) {
2948 );
3049 }
3150
32-function toolMessageNode(msg: TUIMessage) {
51+function toolMessageNode(msg: TUIMessage): Node {
3352 return VStack({ gap: 1 }, [
3453 memoizedSyntaxHighlight(
3554 msg.id ?? String(msg.timestamp),
@@ -40,50 +59,135 @@ function toolMessageNode(msg: TUIMessage) {
4059 ]);
4160 }
4261
62+function conversationMessageNode(msg: TUIMessage): Node {
63+ const dur = msg.durationMs
64+ ? `Took ${elapsedTime(msg.durationMs / 1000)}`
65+ : "-";
66+
67+ const body =
68+ msg.role === "agent"
69+ ? agentMessageNode(msg)
70+ : msg.role === "user"
71+ ? userMessageNode(msg)
72+ : msg.role === "tool"
73+ ? toolMessageNode(msg)
74+ : Text(msg.content, { wrap: "word", fgColor: theme.bwhite });
75+
76+ return VStack({ gap: 1 }, [
77+ body,
78+ HStack({ gap: 1, justifyContent: "end" }, [
79+ Text(`${relativeTime(msg.timestamp)} ago.`, {
80+ fgColor: theme.bblack,
81+ italic: true,
82+ }),
83+ Text(dur, {
84+ fgColor: theme.bblack,
85+ italic: true,
86+ }),
87+ TextPill(msg.label ?? msg.role, theme.bwhite, theme.bblack),
88+ ]),
89+ ]);
90+}
91+
92+function getConversationLayout(
93+ messages: TUIMessage[],
94+ width: number,
95+): ConversationLayout {
96+ if (
97+ cachedLayout &&
98+ cachedLayout.messages === messages &&
99+ cachedLayout.count === messages.length &&
100+ cachedLayout.width === width
101+ ) {
102+ return cachedLayout;
103+ }
104+
105+ const heights = messages.map((msg) =>
106+ measureContentHeight(conversationMessageNode(msg), { width }),
107+ );
108+
109+ const tops: number[] = [];
110+ let totalHeight = 0;
111+
112+ for (let i = 0; i < heights.length; i++) {
113+ tops.push(totalHeight);
114+ totalHeight += heights[i];
115+ if (i < heights.length - 1) {
116+ totalHeight += gap;
117+ }
118+ }
119+
120+ cachedLayout = {
121+ messages,
122+ count: messages.length,
123+ width,
124+ heights,
125+ tops,
126+ totalHeight,
127+ };
128+
129+ return cachedLayout;
130+}
131+
43132 export function Conversation(state: TUIState) {
44- // TODO: use scroll callbacks to make the conversation a virtual list,
45- // only showing a 12 messages window based the scroll position.
46- // currently we just don't show earlier messages :(
133+ // The root viewport only adds padding.x = 1 on each side.
134+ const width = Math.max(20, (process.stdout.columns ?? 80) - 2);
135+ const viewportEstimate = Math.max(10, (process.stdout.rows ?? 24) - 8);
136+ const overscan = viewportEstimate;
137+ const { heights, tops, totalHeight } = getConversationLayout(
138+ state.messages,
139+ width,
140+ );
141+
142+ const scrollTop = state.stickToBottom
143+ ? Math.max(0, totalHeight - viewportEstimate)
144+ : Math.max(0, Math.min(state.scrollOffset, totalHeight));
145+
146+ const minY = Math.max(0, scrollTop - overscan);
147+ const maxY = scrollTop + viewportEstimate + overscan;
148+
149+ let start = 0;
150+ while (start < heights.length && tops[start] + heights[start] <= minY) {
151+ start++;
152+ }
153+
154+ let end = start;
155+ while (end < heights.length && tops[end] < maxY) {
156+ end++;
157+ }
158+
159+ // Always render at least one item when possible.
160+ if (end === start && end < heights.length) {
161+ end++;
162+ }
163+
164+ const children: Node[] = [];
165+
166+ // Spacer before first visible item.
167+ if (start > 0) {
168+ children.push(VStack({ height: tops[start] - gap }, []));
169+ }
170+
171+ children.push(
172+ ...state.messages.slice(start, end).map(conversationMessageNode),
173+ );
174+
175+ // Spacer after last visible item.
176+ if (end < heights.length) {
177+ children.push(VStack({ height: totalHeight - tops[end] }, []));
178+ }
179+
47180 return VStack(
48181 {
49182 flex: 1,
50- gap: 1,
183+ gap,
51184 overflow: "scroll",
52185 scrollOffset: state.stickToBottom ? Infinity : state.scrollOffset,
53186 onScroll(offset, maxOffset) {
54187 state.scrollOffset = offset;
55188 state.stickToBottom = offset >= maxOffset;
56- cel.render();
57189 },
58190 },
59- [
60- ...state.messages.slice(-12).map((msg) => {
61- const dur = msg.durationMs
62- ? `Took ${elapsedTime(msg.durationMs / 1000)}`
63- : "-";
64-
65- return VStack({ gap: 1 }, [
66- msg.role === "agent"
67- ? agentMessageNode(msg)
68- : msg.role === "user"
69- ? userMessageNode(msg)
70- : msg.role === "tool"
71- ? toolMessageNode(msg)
72- : Text(msg.content, { wrap: "word", fgColor: theme.bwhite }),
73-
74- HStack({ gap: 1, justifyContent: "end" }, [
75- Text(`${relativeTime(msg.timestamp)} ago.`, {
76- fgColor: theme.bblack,
77- italic: true,
78- }),
79- Text(dur, {
80- fgColor: theme.bblack,
81- italic: true,
82- }),
83- TextPill(msg.label ?? msg.role, theme.bwhite, theme.bblack),
84- ]),
85- ]);
86- }),
87- ],
191+ children,
88192 );
89193 }
src/tui-syntax-highlight.ts+2−9
@@ -11,8 +11,9 @@ type CacheEntry = {
1111 node: ContainerNode;
1212 };
1313
14+// We don't care about cache size for now. When we have sessions
15+// We need to clear cache between sessions.
1416 const cache = new Map<string, CacheEntry>();
15-const MAX_ENTRIES = 200;
1617
1718 function getThemeKey(props?: SyntaxHighlightProps): string {
1819 return JSON.stringify(props?.theme ?? null);
@@ -45,14 +46,6 @@ export function memoizedSyntaxHighlight(
4546 node,
4647 });
4748
48- // tiny FIFO cap so cache doesn't grow forever
49- if (cache.size > MAX_ENTRIES) {
50- const oldestKey = cache.keys().next().value;
51- if (oldestKey !== undefined) {
52- cache.delete(oldestKey);
53- }
54- }
55-
5649 return node;
5750 }
5851
src/tui.ts+41−5
@@ -15,15 +15,51 @@ export function initTUI(state: TUIState, leave: (s: string) => void) {
1515 const cwd = basename(process.cwd());
1616
1717 // TODO: move to components, have a function return the everyFn and current spinner
18- const spinnerFrames = ["⠤", "⠆", "⠒", "⠰"];
18+ const spinnerFrames = [
19+ "⠁",
20+ "⠂",
21+ "⠄",
22+ "⡀",
23+ "⡈",
24+ "⡐",
25+ "⡠",
26+ "⣀",
27+ "⣁",
28+ "⣂",
29+ "⣄",
30+ "⣌",
31+ "⣔",
32+ "⣤",
33+ "⣥",
34+ "⣦",
35+ "⣮",
36+ "⣶",
37+ "⣷",
38+ "⣿",
39+ "⡿",
40+ "⠿",
41+ "⢟",
42+ "⠟",
43+ "⡛",
44+ "⠛",
45+ "⠫",
46+ "⢋",
47+ "⠋",
48+ "⠍",
49+ "⡉",
50+ "⠉",
51+ "⠑",
52+ "⠡",
53+ "⢁",
54+ ];
1955 let spinnerTick = 0;
20- const spinnerEvery = onceEvery(5, () => spinnerTick++);
56+ const spinnerEvery = onceEvery(4, () => spinnerTick++);
2157 const currentSpinner = () =>
2258 spinnerFrames[spinnerTick % spinnerFrames.length];
2359
2460 // Because we don't render often, the ui feels unresponsive at times.
25- // This ensure 60fps, and excessive calls get coalesced in cel-tui.
26- const fps = 60;
61+ // This ensure Xfps, and excessive calls get coalesced in cel-tui.
62+ const fps = 30;
2763 const baseFramerateIntervalId = setInterval(() => {
2864 if (state.streaming) {
2965 spinnerEvery();
@@ -57,7 +93,7 @@ export function initTUI(state: TUIState, leave: (s: string) => void) {
5793 VStack({ flex: 1 }, []),
5894 TextPill(state.activeState, theme.bwhite, theme.bblack),
5995 state.streaming
60- ? TextPill(currentSpinner(), theme.bblack, theme.bwhite)
96+ ? TextPill(currentSpinner(), theme.black, theme.white)
6197 : TextPill(currentSpinner(), theme.bwhite, theme.bblack),
6298 ]),