xonecas.io
64875
Mc

mini-coder / commit 5a94d8c

feat: UI polish

xonecas2026-04-29 5a94d8cdc3d0bbaa424c2ddbc71fe662dcffe8b5 parent 68286a9

7 files changed

TODO.md+126−0
@@ -1,3 +1,129 @@
11 # Human's TODO list.
22
33 > This file is managed by the user, only edit if asked to.
4+
5+## TODO: Better prompts, tools descriptions and reminder prompt engineering.
6+
7+```
8+Prioritize technical accuracy and truthfulness over validating the user's beliefs.
9+Focus on facts and problem-solving, providing direct, objective technical info
10+without any unnecessary superlatives, praise, or emotional validation.
11+```
12+
13+---
14+
15+# [Agent Name] Agent Prompt
16+
17+## Role
18+[Define the agent's role, persona, and objective concisely.]
19+Example: You are an expert Data Analyst. You write SQL queries to answer questions from the marketing department.
20+
21+## Tool Usage
22+[Provide supplementary instructions on how/when to use specific tools.]
23+*Note: Detailed technical specifications should be defined in the tool's description settings, but high-level logic goes here.*
24+
25+## Input / Output
26+### Input Variables
27+- `{{variable_name}}`: [Description of the variable]
28+
29+### Output Goals
30+- [Definition of the final deliverable]
31+
32+## Task Flow
33+1. [Task Name]
34+ - [Specific steps and decision criteria]
35+2. [Task Name]
36+ - [Specific steps and decision criteria]
37+
38+## Constraints & Rules
39+- [Prohibitions and constraints]
40+- [Tone and Manner instructions]
41+
42+---
43+
44+# The Six Prompting Techniques That Power Modern Coding Agents
45+
46+I've been teaching a class at Stanford on AI-based software development practices and put together a lecture on the essential prompting techniques every
47+software developer should know. Thought this would be helpful for the community:
48+
49+**K-shot:** Ask the LLM to do a task but provide examples of how to do it. Best when dealing with languages or frameworks that the LLM may not have seen
50+in its training data. Experiment with the number of examples to use but 1-5 is usually quite performant.
51+
52+```text
53+BEFORE:
54+Write a for-loop iterating over a list of strings using the naming convention in our repo.
55+
56+AFTER:
57+Write a for-loop iterating over a list of strings using the naming convention in our repo. Here are some examples of how we typically format variable
58+names. <example> var StRaRrAy = [‘cat’, ‘dog’, ‘wombat’] </example> <example> def func CaPiTaLiZeStR = () => {} </example>
59+```
60+
61+**Chain-of-thought:** Ask an LLM to do a task but prompt it to show its reasoning steps by either providing examples of logical traces or asking it to
62+"think step-by-step."
63+
64+```text
65+BEFORE:
66+Write a function to check if a number is a perfect cube and a perfect square.
67+
68+AFTER:
69+I want to write a function to check if a number is a perfect cube and a perfect square. Make sure to provide your reasoning first. Here are some examples
70+of how to provide reasoning for a coding task. <example> Write a function that finds the maximum element in a list. Steps: Initialize a variable with the
71+first element. Traverse the list, comparing… </example> <example> Write a function that checks is a number is a palindrome Steps: Take the number. Reverse
72+the elements in the numbers. Check if … </example
73+```
74+
75+**Self-consistency.** Ask an LLM to do a task but prompt it to produce multiple outputs and then take the majority output. To use a traditional machine
76+learning analogy, this is like an LLM form of model ensembling.
77+
78+```text
79+BEFORE:
80+What’s the root cause for this error: Traceback (most recent call last): File "example.py", line 3, in <module> print(nums[i]) IndexError: list index out
81+of range
82+
83+AFTER:
84+What’s the root cause for this error: Traceback (most recent call last): File "example.py", line 3, in <module> print(nums[i]) IndexError: list index out
85+of range --> Prompt 5x
86+--> Take majority result
87+```
88+
89+**Tool-use.** Allows an LLM to interact with the real-world by querying APIs, external data sources, and other resources. Helps reduce LLM hallucinations
90+and make them more fully autonomous.
91+
92+```text
93+BEFORE:
94+After you have fixed this IndexError can you ensure that the CI tests still pass?
95+
96+AFTER:
97+Fix the IndexError. Ensure the CI tests still pass once you have made the fix. Here are the available tools. <tools> pytest -s /path/to/unit_tests pytest
98+-v /path/to/integration_tests </tools>
99+```
100+
101+**Retrieval Augmented Generation.** Infuses the LLM with relevant contextual data like source files, functions, and symbols from code. Also provides
102+interpretability and citations in responses. This is one of the most commonly used techniques in modern AI coding platforms like Windsurf, Cursor, Claude
103+Code.
104+
105+```text
106+BEFORE:
107+Extend the UserAuthService class to check that the client provides a valid OAuth token.
108+
109+AFTER:
110+I want to extend the UserAuthService class to check that the client provides a valid OAuth token. Here is how the UserAuthService works now:
111+<code_snippet> def issue_oauth_token(): …. </code_snippet> Here is the path to the requests-oauthlib documentation: <url>
112+https://requests-oauthlib.readthedocs.io/en/latest/</url>
113+```
114+
115+**Reflexion.** Have an LLM reflect on its output after performing a task, then feed its reflection on what it observes back to it for a follow-on prompt.
116+
117+```text
118+BEFORE:
119+Ensure that the company_location column can handle string and json representations.
120+
121+AFTER:
122+Extend the logic for company_location to be able to handle string and json representations
123+--> OBSERVE
124+The unit tests for the company_location type aren’t passing.
125+--> REFLECT
126+It appears that the unit tests for company_location are throwing a JSONDecodeError.
127+--> EXTEND PROMPT
128+I am extending the company_location column. I must ensure that when a string is provided as input it doesn’t throw a JSONDecodeError.
129+```
src/session.ts+44−13
@@ -1,9 +1,9 @@
11 import { mkdir } from "node:fs/promises";
22 import { join } from "node:path";
3+import type { Message } from "@mariozechner/pi-ai";
34 import { Value } from "typebox/value";
45 import { SESSIONS_DIR } from "./shared";
5-import { Session, SessionSchema } from "./types";
6-import { Message } from "@mariozechner/pi-ai";
6+import { type Session, SessionSchema } from "./types";
77
88 // TODO: sessions are json files in SESSIONS_DIR inside of DATA_DIR, use a 10 length `secureRandomString()` for the ids.
99
@@ -20,19 +20,50 @@ export async function getSession(id: string): Promise<Session | undefined> {
2020 }
2121
2222 const sessionJson = await file.text();
23- const parsed = JSON.parse(sessionJson) as unknown
24- const valid = Value.Check(
25- SessionSchema,
26- parsed
27- );
23+ const parsed = JSON.parse(sessionJson) as unknown;
24+ const valid = Value.Check(SessionSchema, parsed);
2825
2926 if (valid) return parsed;
3027 return;
3128 }
3229
30+function latestMessageTimestamp(session: Session): number {
31+ return Math.max(0, ...session.messages.map((message) => message.timestamp));
32+}
33+
34+export async function listSessionsForCwd(): Promise<Session[]> {
35+ const sessions: Session[] = [];
36+ const sessionFiles = new Bun.Glob("*.json");
37+ const cwd = process.cwd();
38+
39+ try {
40+ for await (const entry of sessionFiles.scan({
41+ cwd: SESSIONS_DIR,
42+ dot: true,
43+ })) {
44+ try {
45+ const sessionJson = await Bun.file(join(SESSIONS_DIR, entry)).text();
46+ const parsed = JSON.parse(sessionJson) as unknown;
47+
48+ if (Value.Check(SessionSchema, parsed) && cwd === parsed.cwd) {
49+ sessions.push(parsed);
50+ }
51+ } catch {
52+ // Ignore invalid session files.
53+ }
54+ }
55+ } catch {
56+ return [];
57+ }
58+
59+ return sessions.sort(
60+ (a, b) => latestMessageTimestamp(b) - latestMessageTimestamp(a),
61+ );
62+}
63+
3364 export async function saveSession(s: Session) {
34- await ensureSessionsDir()
35- const file = Bun.file(join(SESSIONS_DIR, `${s.id}.json`))
65+ await ensureSessionsDir();
66+ const file = Bun.file(join(SESSIONS_DIR, `${s.id}.json`));
3667 await Bun.write(file, JSON.stringify(s));
3768 }
3869
@@ -40,8 +71,8 @@ export async function saveSession(s: Session) {
4071 export async function updateSession(id: string, messages: Message[]) {
4172 const existing = await getSession(id);
4273 if (existing) {
43- existing.messages = [...existing.messages, ...messages]
44- await saveSession(existing)
74+ existing.messages = [...existing.messages, ...messages];
75+ await saveSession(existing);
4576 return;
4677 }
4778
@@ -49,7 +80,7 @@ export async function updateSession(id: string, messages: Message[]) {
4980 id,
5081 cwd: process.cwd(),
5182 messages,
52- }
83+ };
5384
5485 await saveSession(s);
55-}
86+}
src/tui-components.ts+7−2
@@ -28,8 +28,13 @@ export const theme = {
2828 bwhite: "color15" as Color,
2929 };
3030
31-export function TextPill(content: string, fgColor: Color, bgColor: Color) {
32- return HStack({ gap: 1 }, [
31+export function TextPill(
32+ content: string,
33+ fgColor: Color,
34+ bgColor: Color,
35+ size?: number | undefined,
36+) {
37+ return HStack({ gap: 1, width: size }, [
3338 HStack({ bgColor, padding: { x: 1 } }, [
3439 Text(content, { bold: true, fgColor }),
3540 ]),
src/tui-conversation.ts+23−1
@@ -165,11 +165,33 @@ const randColor = colors[Math.floor(Math.random() * colors.length)];
165165
166166 export function emptyState(): Node {
167167 return HStack({ flex: 1, alignItems: "center" }, [
168- VStack({ flex: 1, alignItems: "center" }, [
168+ VStack({ flex: 1, alignItems: "center", gap: 1 }, [
169169 HStack({ gap: 1 }, [
170170 Text("mini"),
171171 TextPill("coder", theme.black, randColor),
172172 ]),
173+ VStack({ gap: 1 }, [
174+ HStack({ gap: 1 }, [
175+ TextPill("/new", randColor, theme.bblack, 13),
176+ Text("Start a new session from the input box.", {
177+ fgColor: theme.bblack,
178+ }),
179+ ]),
180+ HStack({ gap: 1 }, [
181+ TextPill("ctrl+p", randColor, theme.bblack, 13),
182+ Text("Menu for session history, and settings.", {
183+ fgColor: theme.bblack,
184+ }),
185+ ]),
186+ HStack({ gap: 1 }, [
187+ TextPill("ESC", randColor, theme.bblack, 13),
188+ Text("Abort agent response.", { fgColor: theme.bblack }),
189+ ]),
190+ HStack({ gap: 1 }, [
191+ TextPill("ctrl+c|d|q", randColor, theme.bblack, 13),
192+ Text("Quit.", { fgColor: theme.bblack }),
193+ ]),
194+ ]),
173195 ]),
174196 ]);
175197 }
src/tui-overlay.ts+71−6
@@ -5,8 +5,9 @@ import {
55 type ThinkingLevel,
66 } from "@mariozechner/pi-ai";
77 import { getOAuthProviders } from "@mariozechner/pi-ai/oauth";
8+import { listSessionsForCwd } from "./session";
89 import { TextPill, theme } from "./tui-components";
9-import type { SelectOptions, SelectState, TUIState } from "./types";
10+import type { SelectOptions, SelectState, Session, TUIState } from "./types";
1011
1112 export function SelectOverlay(
1213 value: string,
@@ -133,13 +134,24 @@ export function useSelectOverlay(initialOptions: SelectOptions) {
133134 if (key === "enter") {
134135 const previousList = s.list;
135136 const previousBaseList = baseList;
137+ const applySelectionResult = () => {
138+ if (s.list !== previousList) {
139+ baseList = s.list;
140+ } else {
141+ s.list = previousBaseList;
142+ s.selected = s.list.length ? s.list[0].value : "";
143+ }
144+ };
145+
136146 s.value = "";
137- initialOptions.onSelect(s);
138- if (s.list !== previousList) {
139- baseList = s.list;
147+ const result = initialOptions.onSelect(s);
148+ if (result instanceof Promise) {
149+ result.then(applySelectionResult).catch(() => {
150+ s.list = previousBaseList;
151+ s.selected = s.list.length ? s.list[0].value : "";
152+ });
140153 } else {
141- s.list = previousBaseList;
142- s.selected = s.list.length ? s.list[0].value : "";
154+ applySelectionResult();
143155 }
144156 return false;
145157 }
@@ -168,6 +180,23 @@ export function useSelectOverlay(initialOptions: SelectOptions) {
168180 );
169181 }
170182
183+function sessionLabel(session: Session): string {
184+ const firstUserMessage = session.messages.find(
185+ (message) => message.role === "user",
186+ );
187+ if (!firstUserMessage) return session.id;
188+
189+ const text =
190+ typeof firstUserMessage.content === "string"
191+ ? firstUserMessage.content
192+ : firstUserMessage.content
193+ .map((block) => (block.type === "text" ? block.text : ""))
194+ .join(" ");
195+ const snippet = text.trim().replace(/\s+/g, " ").slice(0, 80);
196+
197+ return snippet || session.id;
198+}
199+
171200 export function mainMenu(state: TUIState) {
172201 type MenuPane = Omit<SelectOptions, "onCancel" | "onSelect">;
173202
@@ -190,12 +219,27 @@ export function mainMenu(state: TUIState) {
190219 value: v.id,
191220 }));
192221
222+ let currentSessions: Session[] = [];
223+
224+ const sessionsPane = async (): Promise<MenuPane> => {
225+ currentSessions = await listSessionsForCwd();
226+ return {
227+ label: "sessions",
228+ filter: "",
229+ list: currentSessions.map((session) => ({
230+ label: sessionLabel(session),
231+ value: session.id,
232+ })),
233+ };
234+ };
235+
193236 const mainPane: MenuPane = {
194237 label: "main",
195238 filter: state.prompt.length ? state.prompt : "",
196239 list: [
197240 { label: "models and providers", value: "providers" },
198241 { label: "reasoning effort", value: "effort" },
242+ { label: "sessions", value: "sessions" },
199243 ],
200244 };
201245 const providersPane: MenuPane = {
@@ -223,6 +267,7 @@ export function mainMenu(state: TUIState) {
223267 const resetMenu = (s: SelectState) => {
224268 currentPane = mainPane;
225269 selectedProvider = undefined;
270+ currentSessions = [];
226271 s.value = "";
227272 s.label = mainPane.label ? mainPane.label.toUpperCase() : "SELECT";
228273 s.list = mainPane.list;
@@ -240,11 +285,30 @@ export function mainMenu(state: TUIState) {
240285 if (!s.selected) return;
241286
242287 if (currentPane.label === "main") {
288+ if (s.selected === "sessions") {
289+ return sessionsPane().then((pane) => {
290+ openPane(s, pane);
291+ });
292+ }
293+
243294 const nextPane = panes.find((pane) => pane.label === s.selected);
244295 if (nextPane) openPane(s, nextPane);
245296 return;
246297 }
247298
299+ if (currentPane.label === "sessions") {
300+ const session = currentSessions.find((v) => v.id === s.selected);
301+ if (!session) return;
302+
303+ state.sessionId = session.id;
304+ state.messages = session.messages;
305+ state.prompt = "";
306+ state.scrollOffset = 0;
307+ state.stickToBottom = true;
308+ closeMenu(s);
309+ return;
310+ }
311+
248312 if (currentPane.label === "providers") {
249313 const provider = oauthProviders.find((v) => v.id === s.selected);
250314 if (!provider) return;
@@ -283,6 +347,7 @@ export function mainMenu(state: TUIState) {
283347 onCancel: () => {
284348 currentPane = mainPane;
285349 selectedProvider = undefined;
350+ currentSessions = [];
286351 state.overlay = false;
287352 },
288353 });
src/tui.ts+5−3
@@ -6,6 +6,7 @@ import {
66 insertToolUsageReminder,
77 MAIN_PROMPT,
88 } from "./prompt";
9+import { updateSession } from "./session";
910 import { estimateTokens, secureRandomString } from "./shared";
1011 import { bash, runBashTool } from "./tool-bash";
1112 import { edit, runEditTool } from "./tool-edit";
@@ -23,7 +24,6 @@ import { Conversation, emptyState } from "./tui-conversation";
2324 import { Editor } from "./tui-editor";
2425 import { mainMenu } from "./tui-overlay";
2526 import type { AgentContex, ToolAndRunner, TUIState } from "./types";
26-import { updateSession } from "./session";
2727
2828 // TODO: move all git things to `git.ts`
2929 const git = simpleGit();
@@ -88,7 +88,9 @@ export function initTUI(state: TUIState, leave: (s: string) => void) {
8888 if (state.prompt === ":n" || state.prompt === "/new") {
8989 state.sessionId = undefined;
9090 state.messages = [];
91- state.prompt = ""
91+ state.prompt = "";
92+ state.scrollOffset = 0;
93+ state.stickToBottom = true;
9294 return false;
9395 }
9496 const submit = async () => {
@@ -208,7 +210,7 @@ async function streamAgentTUI(state: TUIState) {
208210 const id = secureRandomString(10);
209211 state.sessionId = id;
210212 }
211- await updateSession(state.sessionId, state.messages)
213+ await updateSession(state.sessionId, state.messages);
212214 }
213215
214216 try {
src/types.ts+2−2
@@ -71,7 +71,7 @@ type SavedOAuthAuth = OAuthCredentials & {
7171 };
7272 export type SavedOAuthCreds = Record<string, SavedOAuthAuth>;
7373
74-export const MessageSchema = Type.Unsafe<Message>;
74+export const MessageSchema = Type.Unsafe<Message>({});
7575 export const SessionSchema = Type.Object({
7676 id: Type.String(),
7777 cwd: Type.String(),
@@ -159,6 +159,6 @@ export type SelectOptions = {
159159 filter: string;
160160 list: { label: string; value: string }[];
161161 label?: string | undefined;
162- onSelect: (s: SelectState) => void;
162+ onSelect: (s: SelectState) => void | Promise<void>;
163163 onCancel: () => void;
164164 };