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