xonecas.io
64875
Mc

mini-coder / commit ab382fc

feat: lazily create sessions and exclude ui messages from turns

xonecas2026-04-06 ab382fc3e6a352e24a49bab916d9c372596b0968 parent d7d0171

6 files changed

TODO.md+0−6
@@ -9,12 +9,6 @@ The spec.md and code are the sources of truth, not this file, don't assume anyth
99
1010 ### Core behavior
1111
12-- [ ] **No empty sessions** — startup should render the UI without creating a DB session. Create the session only when the user sends the first message. `/new` should reset in-memory conversation state and defer session creation until the next user message.
13-
14-- [ ] **UI messages are not conversational turns** (`session.ts`, `ui.ts`) — persisted UI messages must not participate in turn numbering. Update the schema/logic so UI messages store `turn = NULL`, stay visible in history, are excluded from model context, and survive `/undo`.
15-
16-- [ ] **`/undo` must only remove the last conversational turn** (`ui.ts`, `session.ts`) — after the UI-message turn model is fixed, make `/undo` remove only the last user message and its assistant/tool results, while leaving persisted UI messages untouched.
17-
1812 - [ ] **End-to-end streaming in the UI** (`ui.ts`) — completed assistant/tool messages should remain visible in the conversation log as soon as they happen, without waiting for the full loop to finish and reload from the DB. The current state/event flow drops already-produced assistant text during tool-use turns.
1913
2014 - [ ] **Implement `/skill:name` submission flow** (`ui.ts`) — strip the prefix from input, prepend the selected skill body to the user message, and send the rest of the user text as the instruction.
src/index.ts+7−16
@@ -37,13 +37,11 @@ import {
3737 } from "./prompt.ts";
3838 import {
3939 computeStats,
40- createSession,
4140 filterModelMessages,
42- loadMessages,
41+ type loadMessages,
4342 openDatabase,
4443 type Session,
4544 type SessionStats,
46- truncateSessions,
4745 } from "./session.ts";
4846 import {
4947 loadSettings,
@@ -83,7 +81,7 @@ const SETTINGS_PATH = join(DATA_DIR, "settings.json");
8381 export { DEFAULT_SHOW_REASONING, DEFAULT_VERBOSE } from "./settings.ts";
8482
8583 /** Maximum sessions to keep per CWD. */
86-const MAX_SESSIONS_PER_CWD = 20;
84+export const MAX_SESSIONS_PER_CWD = 20;
8785
8886 // ---------------------------------------------------------------------------
8987 // OAuth credential persistence
@@ -293,8 +291,8 @@ function getSkillScanPaths(cwd: string, gitRoot: string | null): string[] {
293291 export interface AppState {
294292 /** Open database handle. */
295293 db: ReturnType<typeof openDatabase>;
296- /** Current session. */
297- session: Session;
294+ /** Current session, created lazily on the first user message. */
295+ session: Session | null;
298296 /** Current model, or `null` if no providers are available yet. */
299297 model: Model<string> | null;
300298 /** Current effort level. */
@@ -372,17 +370,10 @@ export async function init(): Promise<AppState> {
372370 // Load plugins
373371 const pluginEntries = loadPluginConfig(PLUGIN_CONFIG_PATH);
374372
375- // Open database and create session
373+ // Open database. Sessions are created lazily on the first user message.
376374 const db = openDatabase(DB_PATH);
377375 const effort = startup.effort;
378- const modelLabel = model ? `${model.provider}/${model.id}` : undefined;
379- const session = createSession(db, {
380- cwd: canonicalCwd,
381- model: modelLabel,
382- effort,
383- });
384- truncateSessions(db, canonicalCwd, MAX_SESSIONS_PER_CWD);
385- const messages = loadMessages(db, session.id);
376+ const messages: ReturnType<typeof loadMessages> = [];
386377 const stats = computeStats(messages);
387378
388379 // Init plugins
@@ -403,7 +394,7 @@ export async function init(): Promise<AppState> {
403394
404395 return {
405396 db,
406- session,
397+ session: null,
407398 model,
408399 effort,
409400 messages,
src/session.test.ts+65−0
@@ -212,6 +212,35 @@ describe("message persistence and turn numbering", () => {
212212 db.close();
213213 });
214214
215+ test("UI messages store turn as NULL and do not consume conversational turn numbers", () => {
216+ const db = openDatabase(":memory:");
217+ const session = createSession(db, { cwd: "/tmp/test" });
218+
219+ const uiTurn = appendMessage(db, session.id, makeUiMessage("Help output"));
220+ const firstUserTurn = appendMessage(db, session.id, makeUser("hello"));
221+ const ignoredUiTurn = appendMessage(
222+ db,
223+ session.id,
224+ makeUiMessage("More help"),
225+ firstUserTurn,
226+ );
227+ const secondUserTurn = appendMessage(db, session.id, makeUser("next"));
228+
229+ const turns = db
230+ .query<{ turn: number | null }, [string]>(
231+ "SELECT turn FROM messages WHERE session_id = ? ORDER BY id",
232+ )
233+ .all(session.id)
234+ .map((row) => row.turn);
235+
236+ expect(uiTurn).toBeNull();
237+ expect(ignoredUiTurn).toBeNull();
238+ expect(firstUserTurn).toBe(1);
239+ expect(secondUserTurn).toBe(2);
240+ expect(turns).toEqual([null, 1, null, 2]);
241+ db.close();
242+ });
243+
215244 test("appendMessage updates session updated_at", () => {
216245 const db = openDatabase(":memory:");
217246 const session = createSession(db, { cwd: "/tmp/test" });
@@ -274,6 +303,42 @@ describe("undo", () => {
274303 db.close();
275304 });
276305
306+ test("undoLastTurn keeps UI messages because they are not part of conversational turns", () => {
307+ const db = openDatabase(":memory:");
308+ const session = createSession(db, { cwd: "/tmp/test" });
309+
310+ appendMessage(db, session.id, makeUiMessage("Help output"));
311+ const t1 = appendMessage(db, session.id, makeUser("first"));
312+ appendMessage(db, session.id, makeAssistant("reply1"), t1);
313+ appendMessage(db, session.id, makeUiMessage("OAuth progress"));
314+ const t2 = appendMessage(db, session.id, makeUser("second"));
315+ appendMessage(db, session.id, makeAssistant("reply2"), t2);
316+ appendMessage(db, session.id, makeUiMessage("Still visible"));
317+
318+ const removed = undoLastTurn(db, session.id);
319+ expect(removed).toBe(true);
320+
321+ const msgs = loadMessages(db, session.id);
322+ expect(msgs).toHaveLength(5);
323+ expect(msgs.map((msg) => msg.role)).toEqual([
324+ "ui",
325+ "user",
326+ "assistant",
327+ "ui",
328+ "ui",
329+ ]);
330+ expect((msgs[0] as ReturnType<typeof makeUiMessage>).content).toBe(
331+ "Help output",
332+ );
333+ expect((msgs[3] as ReturnType<typeof makeUiMessage>).content).toBe(
334+ "OAuth progress",
335+ );
336+ expect((msgs[4] as ReturnType<typeof makeUiMessage>).content).toBe(
337+ "Still visible",
338+ );
339+ db.close();
340+ });
341+
277342 test("undoLastTurn returns false on empty session", () => {
278343 const db = openDatabase(":memory:");
279344 const session = createSession(db, { cwd: "/tmp/test" });
src/session.ts+66−7
@@ -132,7 +132,7 @@ CREATE INDEX IF NOT EXISTS idx_sessions_cwd ON sessions(cwd);
132132 CREATE TABLE IF NOT EXISTS messages (
133133 id INTEGER PRIMARY KEY AUTOINCREMENT,
134134 session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
135- turn INTEGER NOT NULL,
135+ turn INTEGER,
136136 data TEXT NOT NULL,
137137 created_at INTEGER NOT NULL
138138 );
@@ -326,7 +326,26 @@ export function filterModelMessages(
326326 }
327327
328328 /**
329- * Append a message to a session's history.
329+ * Append a UI-only message to a session's history.
330+ *
331+ * UI messages are persisted with `turn = NULL` so they remain visible in
332+ * history without participating in conversational turn numbering or `/undo`.
333+ *
334+ * @param db - Open database handle.
335+ * @param sessionId - The session to append to.
336+ * @param message - The UI-only message to persist.
337+ * @param turn - Ignored for UI messages.
338+ * @returns `null`, since UI messages do not belong to conversational turns.
339+ */
340+export function appendMessage(
341+ db: Database,
342+ sessionId: string,
343+ message: UiMessage,
344+ turn?: number,
345+): null;
346+
347+/**
348+ * Append a conversational message to a session's history.
330349 *
331350 * Turn numbering rules:
332351 * - When `turn` is **omitted**, a new turn is started with `MAX(turn) + 1`
@@ -339,20 +358,60 @@ export function filterModelMessages(
339358 *
340359 * @param db - Open database handle.
341360 * @param sessionId - The session to append to.
342- * @param message - A persisted message (pi-ai message or internal UI message).
361+ * @param message - A model-visible pi-ai message.
343362 * @param turn - Explicit turn number to join. Omit to start a new turn.
344- * @returns The turn number the message was stored with.
363+ * @returns The conversational turn number the message was stored with.
364+ */
365+export function appendMessage(
366+ db: Database,
367+ sessionId: string,
368+ message: Message,
369+ turn?: number,
370+): number;
371+
372+/**
373+ * Append a persisted message to a session's history.
374+ *
375+ * UI messages always store `turn = NULL`. Conversational messages either start
376+ * a new turn or join an existing one, depending on `turn`.
377+ *
378+ * @param db - Open database handle.
379+ * @param sessionId - The session to append to.
380+ * @param message - Persisted message to store.
381+ * @param turn - Explicit conversational turn to join.
382+ * @returns The assigned conversational turn number, or `null` for UI messages.
383+ */
384+export function appendMessage(
385+ db: Database,
386+ sessionId: string,
387+ message: PersistedMessage,
388+ turn?: number,
389+): number | null;
390+
391+/**
392+ * Append a persisted message to a session's history.
393+ *
394+ * UI messages always store `turn = NULL`. Conversational messages either start
395+ * a new turn or join an existing one, depending on `turn`.
396+ *
397+ * @param db - Open database handle.
398+ * @param sessionId - The session to append to.
399+ * @param message - Persisted message to store.
400+ * @param turn - Explicit conversational turn to join.
401+ * @returns The assigned conversational turn number, or `null` for UI messages.
345402 */
346403 export function appendMessage(
347404 db: Database,
348405 sessionId: string,
349406 message: PersistedMessage,
350407 turn?: number,
351-): number {
408+): number | null {
352409 const now = Date.now();
353410
354- let effectiveTurn: number;
355- if (turn !== undefined) {
411+ let effectiveTurn: number | null;
412+ if (isUiMessage(message)) {
413+ effectiveTurn = null;
414+ } else if (turn !== undefined) {
356415 effectiveTurn = turn;
357416 } else {
358417 const row = db.query<MaxTurnRow, [string]>(SQL.maxTurn).get(sessionId);
src/ui.test.ts+93−4
@@ -86,14 +86,20 @@ function createTempDir(): string {
8686 return dir;
8787 }
8888
89+function countSessions(state: Pick<AppState, "db">): number {
90+ const row = state.db
91+ .query<{ count: number }, []>("SELECT COUNT(*) as count FROM sessions")
92+ .get();
93+ return row?.count ?? 0;
94+}
95+
8996 function createTestState(): AppState {
9097 const db = openDatabase(":memory:");
9198 const cwd = "/tmp/mini-coder-ui-test";
92- const session = createSession(db, { cwd });
9399 const settingsPath = join(createTempDir(), "settings.json");
94100 return {
95101 db,
96- session,
102+ session: null,
97103 model: null,
98104 effort: "medium",
99105 messages: [],
@@ -344,7 +350,7 @@ describe("ui rendering", () => {
344350 expect(text).toContain("Running...");
345351 });
346352
347- test("/help appends a persisted UI message to the conversation log", () => {
353+ test("/help before the first user message does not create a session", () => {
348354 const state = createTestState();
349355
350356 try {
@@ -355,6 +361,8 @@ describe("ui rendering", () => {
355361 children: buildConversationLog(state),
356362 });
357363
364+ expect(state.session).toBeNull();
365+ expect(countSessions(state)).toBe(0);
358366 expect(state.messages).toHaveLength(1);
359367 expect(state.messages[0]?.role).toBe("ui");
360368 expect(logText.some((line) => line.includes("Commands:"))).toBe(true);
@@ -363,6 +371,82 @@ describe("ui rendering", () => {
363371 }
364372 });
365373
374+ test("first user message creates the session lazily", async () => {
375+ const faux = registerFauxProvider();
376+ const state = createTestState();
377+ const originalPath = process.env.PATH;
378+ process.env.PATH = `${process.env.PATH ?? ""}:/usr/bin:/bin`;
379+ state.cwd = process.cwd();
380+ state.canonicalCwd = process.cwd();
381+ state.model = faux.getModel();
382+ faux.setResponses([fauxAssistantMessage("Done.")]);
383+
384+ try {
385+ expect(state.session).toBeNull();
386+ expect(countSessions(state)).toBe(0);
387+
388+ handleInput("hello", state);
389+
390+ await waitFor(() => state.session !== null);
391+ expect(countSessions(state)).toBe(1);
392+
393+ const sessionId = state.session?.id;
394+ if (!sessionId) {
395+ throw new Error("Expected a session to be created");
396+ }
397+
398+ await waitFor(() =>
399+ loadMessages(state.db, sessionId).some(
400+ (message) => message.role === "assistant",
401+ ),
402+ );
403+ } finally {
404+ process.env.PATH = originalPath;
405+ faux.unregister();
406+ state.db.close();
407+ }
408+ });
409+
410+ test("/new clears the active session and defers replacement session creation", async () => {
411+ const faux = registerFauxProvider();
412+ const state = createTestState();
413+ const originalPath = process.env.PATH;
414+ process.env.PATH = `${process.env.PATH ?? ""}:/usr/bin:/bin`;
415+ state.cwd = process.cwd();
416+ state.canonicalCwd = process.cwd();
417+ state.model = faux.getModel();
418+ const previousSession = createSession(state.db, {
419+ cwd: state.canonicalCwd,
420+ });
421+ state.session = previousSession;
422+ faux.setResponses([fauxAssistantMessage("Fresh session.")]);
423+
424+ try {
425+ expect(countSessions(state)).toBe(1);
426+
427+ handleInput("/new", state);
428+
429+ expect(state.session).toBeNull();
430+ expect(state.messages).toEqual([]);
431+ expect(state.stats).toEqual({
432+ totalInput: 0,
433+ totalOutput: 0,
434+ totalCost: 0,
435+ });
436+ expect(countSessions(state)).toBe(1);
437+
438+ handleInput("hello again", state);
439+
440+ await waitFor(() => state.session !== null);
441+ expect(countSessions(state)).toBe(2);
442+ expect(state.session?.id).not.toBe(previousSession.id);
443+ } finally {
444+ process.env.PATH = originalPath;
445+ faux.unregister();
446+ state.db.close();
447+ }
448+ });
449+
366450 test("completed assistant messages remain visible after a turn finishes", async () => {
367451 const faux = registerFauxProvider();
368452 const state = createTestState();
@@ -375,8 +459,13 @@ describe("ui rendering", () => {
375459
376460 try {
377461 handleInput("hello", state);
462+ await waitFor(() => state.session !== null);
463+ const sessionId = state.session?.id;
464+ if (!sessionId) {
465+ throw new Error("Expected a session to be created");
466+ }
378467 await waitFor(() =>
379- loadMessages(state.db, state.session.id).some(
468+ loadMessages(state.db, sessionId).some(
380469 (message) => message.role === "assistant",
381470 ),
382471 );
src/ui.ts+56−28
@@ -40,6 +40,7 @@ import {
4040 buildPrompt,
4141 buildToolList,
4242 getAvailableModels,
43+ MAX_SESSIONS_PER_CWD,
4344 saveOAuthCredentials,
4445 shutdown,
4546 } from "./index.ts";
@@ -53,6 +54,7 @@ import {
5354 forkSession,
5455 listSessions,
5556 loadMessages,
57+ truncateSessions,
5658 type UiMessage,
5759 undoLastTurn,
5860 } from "./session.ts";
@@ -1244,11 +1246,12 @@ function handleSessionCommand(state: AppState): void {
12441246 return;
12451247 }
12461248
1249+ const currentSessionId = state.session?.id ?? null;
12471250 const items = sessions.map((s) => {
12481251 const date = new Date(s.updatedAt);
12491252 const dateStr = formatSessionDate(date);
12501253 const model = s.model ?? "no model";
1251- const current = s.id === state.session.id ? " (current)" : "";
1254+ const current = s.id === currentSessionId ? " (current)" : "";
12521255 return {
12531256 label: `${dateStr} ${model}${current}`,
12541257 value: s.id,
@@ -1263,7 +1266,7 @@ function handleSessionCommand(state: AppState): void {
12631266 focused: true,
12641267 highlightColor: state.theme.accentText,
12651268 onSelect: (sessionId) => {
1266- if (sessionId !== state.session.id) {
1269+ if (sessionId !== currentSessionId) {
12671270 const picked = sessions.find((s) => s.id === sessionId);
12681271 if (picked) {
12691272 state.session = picked;
@@ -1304,37 +1307,60 @@ function openInBrowser(url: string): void {
13041307 }
13051308
13061309 /**
1307- * Append a persisted UI-only info message to the conversation log.
1310+ * Ensure the app has an active persisted session.
1311+ *
1312+ * Creates the session lazily on the first user message and backfills any
1313+ * pre-session UI messages currently shown in the log.
1314+ *
1315+ * @param state - Application state.
1316+ * @returns The active persisted session.
1317+ */
1318+function ensureSession(state: AppState): NonNullable<AppState["session"]> {
1319+ if (state.session) {
1320+ return state.session;
1321+ }
1322+
1323+ const modelLabel = state.model
1324+ ? `${state.model.provider}/${state.model.id}`
1325+ : undefined;
1326+ const session = createSession(state.db, {
1327+ cwd: state.canonicalCwd,
1328+ model: modelLabel,
1329+ effort: state.effort,
1330+ });
1331+ truncateSessions(state.db, state.canonicalCwd, MAX_SESSIONS_PER_CWD);
1332+ state.session = session;
1333+
1334+ for (const message of state.messages) {
1335+ appendMessage(state.db, session.id, message);
1336+ }
1337+
1338+ return session;
1339+}
1340+
1341+/**
1342+ * Append a UI-only info message to the conversation log.
1343+ *
1344+ * When no persisted session exists yet, the message stays in memory and is
1345+ * backfilled if the user later starts a session by sending a message.
13081346 *
13091347 * @param text - Display text to append.
13101348 * @param state - Application state.
1311- * @param turn - Optional turn number to join.
1312- * @returns The turn number the UI message was stored with.
13131349 */
1314-function appendInfoMessage(
1315- text: string,
1316- state: AppState,
1317- turn?: number,
1318-): number {
1350+function appendInfoMessage(text: string, state: AppState): void {
13191351 const msg = createUiMessage(text);
1320- const effectiveTurn = appendMessage(state.db, state.session.id, msg, turn);
1352+ if (state.session) {
1353+ appendMessage(state.db, state.session.id, msg);
1354+ }
13211355 state.messages.push(msg);
13221356 stickToBottom = true;
13231357 cel.render();
1324- return effectiveTurn;
13251358 }
13261359
1327-/** Handle the /new command: start a new session. */
1360+/** Handle the /new command: clear the current in-memory session state. */
13281361 function handleNewCommand(state: AppState): void {
13291362 if (state.running) return;
1330- const modelLabel = state.model
1331- ? `${state.model.provider}/${state.model.id}`
1332- : undefined;
1333- state.session = createSession(state.db, {
1334- cwd: state.canonicalCwd,
1335- model: modelLabel,
1336- effort: state.effort,
1337- });
1363+ state.session = null;
13381364 state.messages = [];
13391365 state.stats = { totalInput: 0, totalOutput: 0, totalCost: 0 };
13401366 stickToBottom = true;
@@ -1343,7 +1369,7 @@ function handleNewCommand(state: AppState): void {
13431369
13441370 /** Handle the /fork command: fork the current session. */
13451371 function handleForkCommand(state: AppState): void {
1346- if (state.running) return;
1372+ if (state.running || !state.session) return;
13471373 const forked = forkSession(state.db, state.session.id);
13481374 state.session = forked;
13491375 state.messages = loadMessages(state.db, forked.id);
@@ -1357,6 +1383,9 @@ function handleUndoCommand(state: AppState): void {
13571383 if (state.running && state.abortController) {
13581384 state.abortController.abort();
13591385 }
1386+ if (!state.session) {
1387+ return;
1388+ }
13601389 const removed = undoLastTurn(state.db, state.session.id);
13611390 if (removed) {
13621391 state.messages = loadMessages(state.db, state.session.id);
@@ -1733,6 +1762,7 @@ export function handleInput(raw: string, state: AppState): void {
17331762 async function submitMessage(text: string, state: AppState): Promise<void> {
17341763 if (!text.trim() || !state.model || state.running) return;
17351764
1765+ const session = ensureSession(state);
17361766 const userMessage: Message = {
17371767 role: "user",
17381768 content: text,
@@ -1740,7 +1770,7 @@ async function submitMessage(text: string, state: AppState): Promise<void> {
17401770 };
17411771
17421772 // Append user message — returns the auto-assigned turn number
1743- const turn = appendMessage(state.db, state.session.id, userMessage);
1773+ const turn = appendMessage(state.db, session.id, userMessage);
17441774 state.messages.push(userMessage);
17451775 stickToBottom = true;
17461776 cel.render();
@@ -1764,7 +1794,7 @@ async function submitMessage(text: string, state: AppState): Promise<void> {
17641794 try {
17651795 await runAgentLoop({
17661796 db: state.db,
1767- sessionId: state.session.id,
1797+ sessionId: session.id,
17681798 turn,
17691799 model: state.model,
17701800 systemPrompt,
@@ -1772,14 +1802,12 @@ async function submitMessage(text: string, state: AppState): Promise<void> {
17721802 toolHandlers,
17731803 messages: filterModelMessages(state.messages),
17741804 cwd: state.cwd,
1775- apiKey: state.model
1776- ? state.providers.get(state.model.provider)
1777- : undefined,
1805+ apiKey: state.providers.get(state.model.provider),
17781806 effort: state.effort,
17791807 signal: state.abortController.signal,
17801808 onEvent: (event) => handleAgentEvent(event, state),
17811809 });
1782- state.messages = loadMessages(state.db, state.session.id);
1810+ state.messages = loadMessages(state.db, session.id);
17831811 state.stats = computeStats(state.messages);
17841812 } finally {
17851813 state.running = false;