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