xonecas.io
64875
Mc

mini-coder / commit 12721b7

fix(interrupt): ESC cancels turn preserving partial response, arrow keys no longer cancel

- ESC during a turn stops the LLM, preserves any partial streamed text in
  history with an interrupt stub appended so the LLM retains context
- Multi-byte ESC sequences (arrow keys, function keys) no longer trigger cancel;
  only a lone ESC byte (0x1B) is treated as cancel
- Ctrl+C always exits the process (never routes through interrupt path)
- SIGINT no longer hijacked by watchForCancel; falls through to the default
  registerCleanup handler (exit 130)
- Ralph mode no longer forcibly disabled on interrupt
- session-runner: removed wasAborted flag, errorStubSaved guard, and all
  abort-specific branching; renderTurn now returns partial messages on abort
  and throws on real errors for a single clean code path
- ESC_BYTE and CTRL_C_BYTE now derived from their string counterparts via
  charCodeAt(0) to make the relationship explicit
- Docs: idea file updated to reflect ESC as cancel key with correct behaviour;
  stale TODO entry removed

xonecas2026-03-10 12721b737e4446dc9a53b4f66b890bb82b5d775b parent 47734c0

9 files changed

TODO.md+2−1
@@ -5,7 +5,8 @@
55 ## Usbaility issues:
66
77 - Subagents are way less competent than the main agent
8-- ESC doesn't interrupt anything, completly not working.
8+
9+
910 - All models: constant reading almost no action, lot's of wasted tokens, using opencode or claude code is a much more action oriented workflow.
1011 - Ralph mode is completly broken, most models just exit the loop without completing anything, or after reading the context.
1112
mini-coder-idea.md+2−1
@@ -24,7 +24,8 @@ conventions and not introduce more specs. (skills.sh installs to `.agents,AGENTS
2424 - Session management and command to create new/resume/list with local sqlite file.
2525 - Seamless shell integration with aliases and completions with `!` in prompt input.
2626 - Reference files, skills, agents from the working directory and global community configs with `@` in prompt input
27-- Gracefully cancel an in-flight LLM request with `ctrl+c` (returns to prompt) and exit with `ctrl+d`. `/undo` last LLM turn.
27+- Press `ESC` at any point during an assistant response to interrupt it: the partial response is preserved in history with an interrupt stub appended (so the LLM retains context), and the user is returned to the prompt silently. `ctrl+c` exits the app. `ctrl+d` (EOF) also exits.
28+
2829 - `glob`, `grep`, `read`, `replace`,`insert`, `create`, `shell`, and `subagent` tools for LLMs
2930 - tool hooks support (do command automatically after certain tools)
3031 - Commands in CLI prompt:
src/agent/agent.test.ts+33−37
@@ -1,4 +1,5 @@
11 import { describe, expect, test } from "bun:test";
2+import { getTurnControlAction } from "../cli/input.ts";
23 import type { CoreMessage } from "../llm-api/turn.ts";
34 import {
45 extractAssistantText,
@@ -108,43 +109,38 @@ describe("hasRalphSignal", () => {
108109 });
109110 });
110111
111-// ─── ESC / Ctrl+C handling ────────────────────────────────────────────────────
112-//
113-// Behaviour contract:
114-// • During an LLM turn, ESC cancels the turn and returns to the prompt.
115-// • Ctrl+C exits the process.
116-//
117-// Architecture:
118-// watchForCancel() (input.ts) sets stdin to raw mode and listens for
119-// byte 0x1B (ESC) to abort the turn, and byte 0x03 (Ctrl+C) to quit.
120-//
121-// These tests verify the AbortController / abort-signal wiring independently
122-// of the actual TTY/stdin machinery.
123-
124-describe("interrupt via AbortController", () => {
125- test("aborting the controller sets wasAborted via signal listener", () => {
126- const controller = new AbortController();
127- let wasAborted = false;
128- controller.signal.addEventListener("abort", () => {
129- wasAborted = true;
130- });
131- expect(wasAborted).toBe(false);
132- controller.abort();
133- expect(wasAborted).toBe(true);
134- });
135-
136- test("abort is idempotent — repeated aborts do not throw", () => {
137- const controller = new AbortController();
138- controller.abort();
139- expect(() => controller.abort()).not.toThrow();
140- expect(controller.signal.aborted).toBe(true);
141- });
142-
143- test("signal.aborted reflects abort state correctly", () => {
144- const controller = new AbortController();
145- expect(controller.signal.aborted).toBe(false);
146- controller.abort();
147- expect(controller.signal.aborted).toBe(true);
112+// ─── getTurnControlAction ─────────────────────────────────────────────────────
113+
114+describe("getTurnControlAction", () => {
115+ test("returns cancel for ESC byte (0x1B)", () => {
116+ expect(getTurnControlAction(Buffer.from([0x1b]))).toBe("cancel");
117+ });
118+
119+ test("returns quit for Ctrl+C byte (0x03)", () => {
120+ expect(getTurnControlAction(Buffer.from([0x03]))).toBe("quit");
121+ });
122+
123+ test("returns null for regular printable bytes", () => {
124+ expect(getTurnControlAction(Buffer.from([0x61]))).toBeNull(); // 'a'
125+ });
126+
127+ test("returns null for multi-byte ESC sequence (arrow keys, function keys)", () => {
128+ // Arrow-up: ESC [ A — should NOT cancel
129+ expect(getTurnControlAction(Buffer.from([0x1b, 0x5b, 0x41]))).toBeNull();
130+ // Arrow-down: ESC [ B
131+ expect(getTurnControlAction(Buffer.from([0x1b, 0x5b, 0x42]))).toBeNull();
132+ });
133+
134+ test("returns null for two-byte ESC sequence", () => {
135+ expect(getTurnControlAction(Buffer.from([0x1b, 0x66]))).toBeNull(); // Alt+f
136+ });
137+
138+ test("returns quit for Ctrl+C even in multi-byte chunk", () => {
139+ expect(getTurnControlAction(Buffer.from([0x61, 0x03, 0x62]))).toBe("quit");
140+ });
141+
142+ test("returns null for empty buffer", () => {
143+ expect(getTurnControlAction(Buffer.from([]))).toBeNull();
148144 });
149145 });
150146
src/agent/session-runner.ts+4−35
@@ -103,10 +103,6 @@ export class SessionRunner {
103103 pastedImages: ImageAttachment[] = [],
104104 ): Promise<string> {
105105 const abortController = new AbortController();
106- let wasAborted = false;
107- abortController.signal.addEventListener("abort", () => {
108- wasAborted = true;
109- });
110106 const stopWatcher = watchForCancel(abortController);
111107
112108 const { text: resolvedText, images: refImages } = await resolveFileRefs(
@@ -139,17 +135,6 @@ export class SessionRunner {
139135 }
140136 : { role: "user", content: coreContent };
141137
142- if (wasAborted) {
143- stopWatcher();
144- const stubMsg = makeInterruptMessage("user");
145- this.session.messages.push(userMsg, stubMsg);
146- saveMessages(this.session.id, [userMsg, stubMsg], thisTurn);
147- this.coreHistory.push(userMsg, stubMsg);
148- this.snapshotStack.push(snapped ? thisTurn : null);
149- touchActiveSession(this.session);
150- return "";
151- }
152-
153138 this.session.messages.push(userMsg);
154139 saveMessages(this.session.id, [userMsg], thisTurn);
155140 this.coreHistory.push(userMsg);
@@ -158,7 +143,6 @@ export class SessionRunner {
158143 const systemPrompt = buildSystemPrompt(this.cwd, this.currentModel);
159144
160145 let lastAssistantText = "";
161- let errorStubSaved = false;
162146
163147 try {
164148 this.snapshotStack.push(snapped ? thisTurn : null);
@@ -185,17 +169,6 @@ export class SessionRunner {
185169 this.coreHistory.push(...newMessages);
186170 this.session.messages.push(...newMessages);
187171 saveMessages(this.session.id, newMessages, thisTurn);
188- if (wasAborted) {
189- const note = makeInterruptMessage("user");
190- this.coreHistory.push(note);
191- this.session.messages.push(note);
192- saveMessages(this.session.id, [note], thisTurn);
193- }
194- } else {
195- const stubMsg = makeInterruptMessage("user");
196- this.coreHistory.push(stubMsg);
197- this.session.messages.push(stubMsg);
198- saveMessages(this.session.id, [stubMsg], thisTurn);
199172 }
200173
201174 lastAssistantText = extractAssistantText(newMessages);
@@ -205,17 +178,13 @@ export class SessionRunner {
205178 this.lastContextTokens = contextTokens;
206179 touchActiveSession(this.session);
207180 } catch (err) {
208- if (!errorStubSaved) {
209- errorStubSaved = true;
210- const stubMsg = makeInterruptMessage("error");
211- this.coreHistory.push(stubMsg);
212- this.session.messages.push(stubMsg);
213- saveMessages(this.session.id, [stubMsg], thisTurn);
214- }
181+ const stubMsg = makeInterruptMessage("error");
182+ this.coreHistory.push(stubMsg);
183+ this.session.messages.push(stubMsg);
184+ saveMessages(this.session.id, [stubMsg], thisTurn);
215185 throw err;
216186 } finally {
217187 stopWatcher();
218- if (wasAborted) this.ralphMode = false;
219188 }
220189
221190 return lastAssistantText;
src/cli/input.test.ts+6−2
@@ -121,9 +121,13 @@ describe("getTurnControlAction", () => {
121121 expect(getTurnControlAction(new Uint8Array([0x03]))).toBe("quit");
122122 });
123123
124- test("uses the first matching control byte in the chunk", () => {
124+ test("only cancels on a lone ESC — multi-byte chunks containing ESC are not cancel", () => {
125+ // [ESC, Ctrl+C]: not a lone ESC, Ctrl+C still fires quit
126+ expect(getTurnControlAction(new Uint8Array([0x1b, 0x03]))).toBe("quit");
127+ // [Ctrl+C, ESC]: Ctrl+C fires quit
125128 expect(getTurnControlAction(new Uint8Array([0x03, 0x1b]))).toBe("quit");
126- expect(getTurnControlAction(new Uint8Array([0x1b, 0x03]))).toBe("cancel");
129+ // Arrow-up sequence ESC [ A: not cancel
130+ expect(getTurnControlAction(new Uint8Array([0x1b, 0x5b, 0x41]))).toBeNull();
127131 });
128132
129133 test("ignores unrelated bytes", () => {
src/cli/input.ts+6−5
@@ -41,8 +41,8 @@ const CTRL_K = "\x0B";
4141 const CTRL_L = "\x0C";
4242 const CTRL_R = "\x12";
4343 const TAB = "\x09";
44-const ESC_BYTE = 0x1b;
45-const CTRL_C_BYTE = 0x03;
44+const ESC_BYTE = ESC.charCodeAt(0);
45+const CTRL_C_BYTE = CTRL_C.charCodeAt(0);
4646
4747 // ─── Types ────────────────────────────────────────────────────────────────────
4848
@@ -196,8 +196,11 @@ async function readKey(reader: StreamReader): Promise<string> {
196196 export function getTurnControlAction(
197197 chunk: Uint8Array,
198198 ): "cancel" | "quit" | null {
199+ // A bare ESC press sends exactly one byte (0x1B). Multi-byte escape
200+ // sequences (arrow keys, function keys, etc.) always follow with more
201+ // bytes in the same chunk, so we only cancel on a lone ESC.
202+ if (chunk.length === 1 && chunk[0] === ESC_BYTE) return "cancel";
199203 for (const byte of chunk) {
200- if (byte === ESC_BYTE) return "cancel";
201204 if (byte === CTRL_C_BYTE) return "quit";
202205 }
203206 return null;
@@ -238,12 +241,10 @@ export function watchForCancel(abortController: AbortController): () => void {
238241
239242 const cleanup = () => {
240243 process.stdin.removeListener("data", onData);
241- terminal.setInterruptHandler(null);
242244 terminal.setRawMode(false);
243245 process.stdin.pause();
244246 };
245247
246- terminal.setInterruptHandler(onCancel);
247248 terminal.setRawMode(true);
248249 process.stdin.resume();
249250 process.stdin.on("data", onData);
src/cli/stream-render.ts+15−1
@@ -1,4 +1,5 @@
11 import * as c from "yoctocolors";
2+import { makeInterruptMessage } from "../agent/agent-helpers.ts";
23 import type { CoreMessage } from "../llm-api/turn.ts";
34 import type { TurnEvent } from "../llm-api/types.ts";
45 import { logError } from "./error-log.ts";
@@ -20,6 +21,8 @@ export async function renderTurn(
2021 let inText = false;
2122 let inReasoning = false;
2223 let rawBuffer = "";
24+ let accumulatedText = "";
25+
2326 let inFence = false;
2427
2528 let inputTokens = 0;
@@ -75,6 +78,8 @@ export async function renderTurn(
7578 inText = true;
7679 }
7780 rawBuffer += event.delta;
81+ accumulatedText += event.delta;
82+
7883 flushCompleteLines();
7984 break;
8085 }
@@ -125,7 +130,15 @@ export async function renderTurn(
125130 (event.error.name === "Error" &&
126131 event.error.message.toLowerCase().includes("abort"));
127132 if (isAbort) {
128- writeln(`${G.warn} ${c.dim("interrupted")}`);
133+ const stub = makeInterruptMessage("user");
134+ const partialContent = accumulatedText
135+ ? `${accumulatedText}${stub.content}`
136+ : (stub.content as string);
137+ const partialMsg: CoreMessage = {
138+ role: "assistant",
139+ content: partialContent,
140+ };
141+ newMessages = [...event.partialMessages, partialMsg];
129142 } else {
130143 logError(event.error, "turn");
131144 const parsed = parseAppError(event.error);
@@ -133,6 +146,7 @@ export async function renderTurn(
133146 if (parsed.hint) {
134147 writeln(` ${c.dim(parsed.hint)}`);
135148 }
149+ throw event.error;
136150 }
137151 break;
138152 }
src/llm-api/turn.ts+6−6
@@ -100,6 +100,8 @@ export async function* runTurn(options: {
100100 // the full conversation history, so later steps have larger prompts).
101101 let contextTokens = 0;
102102
103+ const partialState = { messages: [] as CoreMessage[] };
104+
103105 try {
104106 // OpenAI GPT models use the Responses API (@ai-sdk/openai v3 / ai v6 default),
105107 // which honours `instructions` as the authoritative system prompt. Passing it
@@ -130,8 +132,6 @@ export async function* runTurn(options: {
130132 : {}),
131133 };
132134
133- let finalMessages: CoreMessage[] = [];
134-
135135 const streamOpts: StreamTextOptions = {
136136 model,
137137 messages,
@@ -156,7 +156,8 @@ export async function* runTurn(options: {
156156 response?: { messages?: CoreMessage[] };
157157 messages?: CoreMessage[];
158158 };
159- finalMessages = s.response?.messages ?? s.messages ?? finalMessages;
159+ partialState.messages =
160+ s.response?.messages ?? s.messages ?? partialState.messages;
160161 },
161162 // On the last allowed step, strip all tools so the model is forced to
162163 // respond with text — no more tool calls are possible.
@@ -183,8 +184,6 @@ export async function* runTurn(options: {
183184
184185 // Stream events
185186 for await (const chunk of result.fullStream) {
186- if (signal?.aborted) break;
187-
188187 const c = chunk as StreamChunk;
189188
190189 if (c.type !== "text-delta" && c.type !== "reasoning") {
@@ -269,7 +268,7 @@ export async function* runTurn(options: {
269268 // due to a known bug in @ai-sdk/anthropic's tee() stream usage.
270269 // Since step.response.messages includes the full deduplicated list, the last invocation
271270 // gives us the exact equivalent without waiting on the broken promise.
272- const newMessages = finalMessages;
271+ const newMessages = partialState.messages;
273272
274273 logApiEvent("turn complete", {
275274 newMessagesCount: newMessages.length,
@@ -291,6 +290,7 @@ export async function* runTurn(options: {
291290 yield {
292291 type: "turn-error",
293292 error: err instanceof Error ? err : new Error(String(err)),
293+ partialMessages: partialState.messages,
294294 };
295295 }
296296 }
src/llm-api/types.ts+2−0
@@ -45,6 +45,8 @@ export interface TurnCompleteEvent {
4545 export interface TurnErrorEvent {
4646 type: "turn-error";
4747 error: Error;
48+ /** Messages from completed steps before the error/abort occurred. */
49+ partialMessages: CoreMessage[];
4850 }
4951
5052 export type TurnEvent =