xonecas.io
64875
Mc

mini-coder / commit 98d67dd

fix: roll back orphaned user messages on failed turns

If streamText throws or returns no assistant messages, the user message
was already persisted to the DB, creating consecutive user messages that
permanently break the session (ModelMessage[] schema validation).

- Extract rollbackTurn() idempotent helper (turnRolledBack guard prevents
  double-pop of snapshotStack when else-branch rolls back then catch fires)
- deleteLastTurn() now accepts explicit turnIndex to delete the exact turn
  rather than relying on MAX(turn_index) — avoids deleting the wrong row
- rollbackTurn() calls deleteSnapshot() to clean up snapshot rows written
  by takeSnapshot() before the try block (was a per-failed-turn storage leak)
- turnIndex-- comment explains why the > 0 guard is unnecessary here

Sean2026-02-23 98d67dd2db437491311d3631508ba6bdd529bf13 parent 8c8126f

2 files changed

src/agent/agent.ts+28−0
@@ -29,6 +29,7 @@ import {
2929 import {
3030 deleteAllSnapshots,
3131 deleteLastTurn,
32+ deleteSnapshot,
3233 getConfigDir,
3334 getMaxTurnIndex,
3435 listMcpServers,
@@ -494,6 +495,24 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
494495 process.on("SIGINT", onSigInt);
495496
496497 let lastAssistantText = "";
498+ // Tracks whether the turn was fully committed (assistant messages saved).
499+ // Used by rollbackTurn() to avoid double-rolling-back.
500+ let turnRolledBack = false;
501+
502+ // Roll back the user message saved before the LLM call, so a failed turn
503+ // doesn't leave two consecutive user messages that would permanently break
504+ // the session by failing ModelMessage[] schema validation.
505+ const rollbackTurn = () => {
506+ if (turnRolledBack) return;
507+ turnRolledBack = true;
508+ coreHistory.pop();
509+ session.messages.pop();
510+ deleteLastTurn(session.id, thisTurn);
511+ if (snapped) deleteSnapshot(session.id, thisTurn);
512+ snapshotStack.pop();
513+ turnIndex--; // safe: thisTurn = turnIndex++ so turnIndex >= 1 here
514+ };
515+
497516 try {
498517 // Always push so the stack stays aligned 1:1 with turns. A null entry means
499518 // the tree was clean at snapshot time — /undo will roll back conversation
@@ -521,6 +540,11 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
521540 coreHistory.push(...newMessages);
522541 session.messages.push(...newMessages);
523542 saveMessages(session.id, newMessages, thisTurn);
543+ } else {
544+ // Turn produced no assistant reply (e.g. schema validation error or
545+ // abort). Roll back the user message so the next user input doesn't
546+ // create two consecutive user messages.
547+ rollbackTurn();
524548 }
525549
526550 // Collect all assistant text from this turn so the ralph loop can detect
@@ -531,6 +555,10 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
531555 totalOut += outputTokens;
532556 lastContextTokens = contextTokens;
533557 touchActiveSession(session);
558+ } catch (err) {
559+ // Unexpected throw (network failure, etc.). Roll back if not already done.
560+ rollbackTurn();
561+ throw err;
534562 } finally {
535563 process.removeListener("SIGINT", onSigInt);
536564 // Stop the ralph loop on Ctrl+C or any unexpected throw, so the user
src/session/db.ts+8−7
@@ -229,16 +229,17 @@ export function getMaxTurnIndex(sessionId: string): number {
229229 }
230230
231231 /**
232- * Delete all messages belonging to the most recent turn.
232+ * Delete all messages belonging to a specific turn (when `turnIndex` is
233+ * provided) or the most recent turn (when omitted).
233234 * Returns true if anything was deleted.
234235 */
235-export function deleteLastTurn(sessionId: string): boolean {
236- const maxTurn = getMaxTurnIndex(sessionId);
237- if (maxTurn < 0) return false;
238- const db = getDb();
239- db.run("DELETE FROM messages WHERE session_id = ? AND turn_index = ?", [
236+export function deleteLastTurn(sessionId: string, turnIndex?: number): boolean {
237+ const target =
238+ turnIndex !== undefined ? turnIndex : getMaxTurnIndex(sessionId);
239+ if (target < 0) return false;
240+ getDb().run("DELETE FROM messages WHERE session_id = ? AND turn_index = ?", [
240241 sessionId,
241- maxTurn,
242+ target,
242243 ]);
243244 return true;
244245 }