xonecas.io
64875
Mc

mini-coder / commit b8ef12d

fix: ctrl+c could still exit forcefully in some edge cases, and probably

still does.

Sean2026-02-23 b8ef12d69957a1139a1dd0b2362fc08959152880 parent 46de3d2

4 files changed

TODO.md+0−6
@@ -1,11 +1,5 @@
11 # TODO
22
3-## Image paste
4-
5-- Best effort try to find the base64 encoded image or the path to the file.
6-- Update `@` so it can also match images.
7-- Clone opencode's repo and check how they do it
8-
93 ## Gemini models sometimes get stuck "thinking" forever
104
115 I've seen it a couple times, where after a tool call, gemini 3.1 pro will get stuck
src/agent/agent.test.ts+108−0
@@ -103,3 +103,111 @@ describe("hasRalphSignal", () => {
103103 expect(hasRalphSignal("I finished the task.")).toBe(false);
104104 });
105105 });
106+
107+// ─── SIGINT handling ──────────────────────────────────────────────────────────
108+//
109+// Behaviour contract (from mini-coder-idea.md):
110+// • First Ctrl+C during an active turn → cancel the turn, return to prompt.
111+// • Second Ctrl+C (or Ctrl+C when no turn is active) → exit the process.
112+//
113+// Architecture:
114+// registerTerminalCleanup() (output.ts) registers a "cleanup" handler that
115+// calls process.exit(130) ONLY when listenerCount("SIGINT") === 1.
116+// processUserInput() (agent.ts) registers a per-turn "abort" handler as the
117+// VERY FIRST synchronous action — before any await — so that Ctrl+C at any
118+// point during the turn (including the async preamble) is intercepted here.
119+//
120+// Note: registerTerminalCleanup() itself cannot be called in tests because it
121+// registers a handler that calls process.exit(), which would kill the runner.
122+// These tests exercise the identical conditional logic with a safe stand-in.
123+
124+describe("SIGINT handling — registerTerminalCleanup + processUserInput contract", () => {
125+ // Mirrors the exact conditional in registerTerminalCleanup's SIGINT handler.
126+ // The real handler calls process.exit(130) instead of log.push("would-exit").
127+ function makeCleanupHandler(log: string[]) {
128+ return () => {
129+ if (process.listenerCount("SIGINT") > 1) {
130+ log.push("skipped");
131+ return;
132+ }
133+ log.push("would-exit");
134+ };
135+ }
136+
137+ test("cleanup handler skips exit while an abort handler is registered", () => {
138+ const log: string[] = [];
139+ const cleanup = makeCleanupHandler(log);
140+ process.on("SIGINT", cleanup);
141+
142+ const abort = () => {
143+ log.push("abort-fired");
144+ process.removeListener("SIGINT", abort);
145+ };
146+ process.on("SIGINT", abort);
147+
148+ process.emit("SIGINT");
149+
150+ process.removeListener("SIGINT", cleanup);
151+ expect(log).toEqual(["skipped", "abort-fired"]);
152+ });
153+
154+ test("cleanup handler exits when it is the sole listener", () => {
155+ const log: string[] = [];
156+ const cleanup = makeCleanupHandler(log);
157+ process.on("SIGINT", cleanup);
158+
159+ process.emit("SIGINT");
160+
161+ process.removeListener("SIGINT", cleanup);
162+ expect(log).toEqual(["would-exit"]);
163+ });
164+
165+ test("abort handler registered before any await covers the async preamble", () => {
166+ // processUserInput registers onSigInt synchronously at the TOP of the
167+ // function (before resolveFileRefs / takeSnapshot awaits). This test
168+ // confirms that a SIGINT fired during those awaits is caught by the abort
169+ // handler rather than escaping to the cleanup handler and exiting.
170+ const log: string[] = [];
171+ const cleanup = makeCleanupHandler(log);
172+ process.on("SIGINT", cleanup);
173+
174+ // Abort handler is in place before any await fires
175+ const abort = () => {
176+ log.push("abort-fired");
177+ process.removeListener("SIGINT", abort);
178+ };
179+ process.on("SIGINT", abort);
180+
181+ // SIGINT fires mid-preamble (simulated synchronously)
182+ process.emit("SIGINT");
183+
184+ process.removeListener("SIGINT", cleanup);
185+ process.removeListener("SIGINT", abort);
186+
187+ // Cleanup skips (listenerCount=2); abort intercepts → no exit
188+ expect(log).toEqual(["skipped", "abort-fired"]);
189+ });
190+
191+ test("second SIGINT after turn abort exits — intentional per-spec behaviour", () => {
192+ // After the first Ctrl+C the abort handler removes itself (listenerCount→1).
193+ // A subsequent Ctrl+C should exit (spec: "Second time it exits the app").
194+ const log: string[] = [];
195+ const cleanup = makeCleanupHandler(log);
196+ process.on("SIGINT", cleanup);
197+
198+ const abort = () => {
199+ log.push("abort-fired");
200+ process.removeListener("SIGINT", abort);
201+ };
202+ process.on("SIGINT", abort);
203+
204+ process.emit("SIGINT"); // first — aborts the turn
205+ expect(log).toEqual(["skipped", "abort-fired"]);
206+ log.length = 0;
207+
208+ process.emit("SIGINT"); // second — exits
209+ process.removeListener("SIGINT", cleanup);
210+
211+ expect(log).toEqual(["would-exit"]);
212+ });
213+});
src/agent/agent.ts+21−9
@@ -472,6 +472,18 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
472472 text: string,
473473 pastedImages: ImageAttachment[] = [],
474474 ): Promise<string> {
475+ // Register the abort handler FIRST — before any await — so that Ctrl+C during
476+ // the async preamble (resolveFileRefs, takeSnapshot) is intercepted here rather
477+ // than falling through to the cleanup handler which exits the process.
478+ const abortController = new AbortController();
479+ let wasAborted = false;
480+ const onSigInt = () => {
481+ wasAborted = true;
482+ abortController.abort();
483+ process.removeListener("SIGINT", onSigInt);
484+ };
485+ process.on("SIGINT", onSigInt);
486+
475487 // Resolve @file references — may expand image refs into additional attachments
476488 const { text: resolvedText, images: refImages } = await resolveFileRefs(
477489 text,
@@ -489,6 +501,15 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
489501 // touching git stash or the user's working tree state.
490502 const snapped = await takeSnapshot(cwd, session.id, thisTurn);
491503
504+ // If CTRL+C was pressed during the async preamble, bail out gracefully
505+ // before touching session state or calling the LLM.
506+ if (wasAborted) {
507+ process.removeListener("SIGINT", onSigInt);
508+ if (snapped) deleteSnapshot(session.id, thisTurn);
509+ turnIndex--;
510+ return "";
511+ }
512+
492513 const coreContent = planMode
493514 ? `${resolvedText}\n\n<system-message>PLAN MODE ACTIVE: Help the user gather context for the plan -- READ ONLY</system-message>`
494515 : ralphMode
@@ -518,15 +539,6 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
518539 const llm = resolveModel(currentModel);
519540 const systemPrompt = buildSystemPrompt(cwd);
520541
521- const abortController = new AbortController();
522- let wasAborted = false;
523- const onSigInt = () => {
524- wasAborted = true;
525- abortController.abort();
526- process.removeListener("SIGINT", onSigInt);
527- };
528- process.on("SIGINT", onSigInt);
529-
530542 let lastAssistantText = "";
531543 // Tracks whether the turn was fully committed (assistant messages saved).
532544 // Used by rollbackTurn() to avoid double-rolling-back.
src/tools/shell.ts+1−1
@@ -28,7 +28,7 @@ export interface ShellOutput {
2828 timedOut: boolean;
2929 }
3030
31-const MAX_OUTPUT_BYTES = 100_000; // 100KB per stream
31+const MAX_OUTPUT_BYTES = 10_000; // 10KB per stream
3232
3333 export const shellTool: ToolDef<ShellInput, ShellOutput> = {
3434 name: "shell",