xonecas.io
64875
Mc

mini-coder / commit 022d66b

fix: ctrl+c during LLM turn — use raw stdin byte 0x03 instead of SIGINT

The previous approach registered a SIGINT handler in processUserInput()
and relied on listenerCount() to let it run before the cleanup handler
that calls process.exit(). This never actually worked reliably in Bun:
SIGINT delivery in Bun is inconsistent, especially with stdin involved.

The correct fix: keep stdin in raw mode during the LLM turn and listen
for byte 0x03 directly. In raw mode the OS sends Ctrl+C as the literal
byte 0x03 to stdin instead of raising SIGINT. We use a dedicated 'data'
listener (not the shared ReadableStream reader) so watchForInterrupt()
and readline() never race for the same bytes.

Changes:
- input.ts: add watchForInterrupt(abortController) — sets raw mode,
  resumes stdin, attaches a 'data' handler that aborts on 0x03, returns
  a stop() cleanup to call in finally{}
- agent.ts: processUserInput() calls watchForInterrupt() instead of
  process.on('SIGINT', ...), stop() in finally
- output.ts: simplify SIGINT handler — remove listenerCount guard since
  no per-turn SIGINT listeners are registered any more
- agent.test.ts: replace SIGINT contract tests with AbortController
  wiring tests (the actual stdin/TTY path can't be unit-tested)

Sean2026-02-28 022d66b3bb601dcbebb124621fc1fea9d6940062 parent 2efc379

5 files changed

TODO.md+6−19
@@ -1,27 +1,14 @@
11 # TODO
22
3-## Resuming sessions is not working:
3+## Agent get's stuck on thinking
44
5-```
6-❯ bun run dev -c
7-$ bun run src/index.ts -c
8-
9- mc mini-coder · vunknown
10- zen/gemini-3.1-pro · /Users/seancaetanomartin/src/mini-coder
11- /help for commands · ctrl+d to exit
12-
13-· Resumed session mm60qesy-dyr0s (zen/gemini-3.1-pro)
14-· MCP: connected exa
15-gemini-3.1-pro mm60qesy ~/src/mini-coder ⎇ main
16-▶ No tool calls, what are you doing, answer me.
17-◆ I apologize for the confusion. Since this is the start of our session, I haven't actually made any tool calls or unrelated changes yet! I am ready to focus exclusively on your request: investigating how to stream subagent activity to the main output and writing a plan to tackle it.
18-
19-Let me search the codebase to understand how subagents are currently executed and how their output is collected. Once I find the relevant code, I'll put together a plan for how we can stream their activity instead of waiting for completion.
20-```
5+- When using Google models, there is a rare occurence where the LLM seems to be stuck on thinking. There is no output for several minutes, and the only solution is to use CTRL+c to interrupt.
6+- This is not a infinite reasoning loop, there are requests being made, the app is "stuck", or "hanguing".
7+- Setting a thinkingConfig is also not a fix, 8000 is the default.
218
22-## Streaming subagent activity
9+## Help agent edits error less:
2310
24-Id like to have the subgent output, activity to be streamed to the main output. Right now we wait for the subagent to be complete to print all at once
11+- Agents sometimes include `|` at the end of the hash, this is because how we display the hashed to them, let's check if the anchor last char is `|` and strip it if it instead of letting it error.
2512
2613 ## Implement WebContent and WebSearch using exa.ai api
2714
src/agent/agent.test.ts+36−101
@@ -104,110 +104,45 @@ describe("hasRalphSignal", () => {
104104 });
105105 });
106106
107-// ─── SIGINT handling ──────────────────────────────────────────────────────────
107+// ─── Ctrl+C / interrupt handling ──────────────────────────────────────────────
108108 //
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.
109+// Behaviour contract:
110+// • During an LLM turn, Ctrl+C cancels the turn and returns to the prompt.
111+// • Ctrl+C when no turn is active exits the process.
112112 //
113113 // 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.
114+// watchForInterrupt() (input.ts) sets stdin to raw mode and listens for
115+// byte 0x03 (Ctrl+C) directly — no SIGINT involved. This sidesteps Bun's
116+// unreliable SIGINT delivery when stdin is in raw mode.
117+// registerTerminalCleanup() (output.ts) handles SIGINT for the idle case
118+// (non-TTY, subprocesses sending SIGINT, etc.) and simply calls process.exit.
119119 //
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"]);
120+// These tests verify the AbortController / abort-signal wiring independently
121+// of the actual TTY/stdin machinery.
122+
123+describe("interrupt via AbortController", () => {
124+ test("aborting the controller sets wasAborted via signal listener", () => {
125+ const controller = new AbortController();
126+ let wasAborted = false;
127+ controller.signal.addEventListener("abort", () => {
128+ wasAborted = true;
129+ });
130+ expect(wasAborted).toBe(false);
131+ controller.abort();
132+ expect(wasAborted).toBe(true);
133+ });
134+
135+ test("abort is idempotent — repeated aborts do not throw", () => {
136+ const controller = new AbortController();
137+ controller.abort();
138+ expect(() => controller.abort()).not.toThrow();
139+ expect(controller.signal.aborted).toBe(true);
140+ });
141+
142+ test("signal.aborted reflects abort state correctly", () => {
143+ const controller = new AbortController();
144+ expect(controller.signal.aborted).toBe(false);
145+ controller.abort();
146+ expect(controller.signal.aborted).toBe(true);
212147 });
213148 });
src/agent/agent.ts+9−11
@@ -8,7 +8,7 @@ import {
88 isImageFilename,
99 loadImageFile,
1010 } from "../cli/image-types.ts";
11-import { readline, type InputResult } from "../cli/input.ts";
11+import { readline, type InputResult, watchForInterrupt } from "../cli/input.ts";
1212 import {
1313 PREFIX,
1414 Spinner,
@@ -487,17 +487,15 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
487487 text: string,
488488 pastedImages: ImageAttachment[] = [],
489489 ): Promise<string> {
490- // Register the abort handler FIRST — before any await — so that Ctrl+C during
491- // the async preamble (resolveFileRefs, takeSnapshot) is intercepted here rather
492- // than falling through to the cleanup handler which exits the process.
490+ // Watch for Ctrl+C by reading raw stdin bytes. This is more reliable than
491+ // SIGINT listeners in Bun: when stdin is in raw mode, the OS sends 0x03
492+ // directly instead of raising a signal that Bun may intercept or swallow.
493493 const abortController = new AbortController();
494494 let wasAborted = false;
495- const onSigInt = () => {
495+ abortController.signal.addEventListener("abort", () => {
496496 wasAborted = true;
497- abortController.abort();
498- process.removeListener("SIGINT", onSigInt);
499- };
500- process.on("SIGINT", onSigInt);
497+ });
498+ const stopWatcher = watchForInterrupt(abortController);
501499
502500 // Resolve @file/skill references (agent refs are left as-is for the LLM)
503501 const { text: resolvedText, images: refImages } = await resolveFileRefs(
@@ -542,7 +540,7 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
542540 // message and a stub assistant reply so the turn stays in history.
543541 // /undo is the only way to erase a turn.
544542 if (wasAborted) {
545- process.removeListener("SIGINT", onSigInt);
543+ stopWatcher();
546544 const stubMsg: CoreMessage = {
547545 role: "assistant",
548546 content: "[interrupted]",
@@ -639,7 +637,7 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
639637 rollbackTurn();
640638 throw err;
641639 } finally {
642- process.removeListener("SIGINT", onSigInt);
640+ stopWatcher();
643641 // Stop the ralph loop on Ctrl+C or any unexpected throw, so the user
644642 // gets back to the prompt rather than resuming with a stale ralphMode=true.
645643 if (wasAborted) ralphMode = false;
src/cli/input.ts+36−0
@@ -183,6 +183,42 @@ async function readKey(reader: StreamReader): Promise<string> {
183183 return new TextDecoder().decode(value);
184184 }
185185
186+// ─── Interrupt watcher (used during LLM turns) ────────────────────────────────
187+// While the LLM is streaming we keep stdin in raw mode so that Ctrl+C arrives
188+// as byte 0x03. We listen directly on process.stdin via a dedicated 'data'
189+// handler — NOT via the shared ReadableStream reader — so that the watcher and
190+// readline() never race for the same bytes. The caller must call the returned
191+// stop() in a finally block.
192+
193+export function watchForInterrupt(
194+ abortController: AbortController,
195+): () => void {
196+ if (!process.stdin.isTTY) return () => {};
197+
198+ const onData = (chunk: Buffer) => {
199+ for (const byte of chunk) {
200+ if (byte === 0x03) {
201+ // Ctrl+C received — abort and clean up immediately.
202+ cleanup();
203+ abortController.abort();
204+ return;
205+ }
206+ }
207+ };
208+
209+ const cleanup = () => {
210+ process.stdin.removeListener("data", onData);
211+ process.stdin.setRawMode(false);
212+ process.stdin.pause();
213+ };
214+
215+ process.stdin.setRawMode(true);
216+ process.stdin.resume();
217+ process.stdin.on("data", onData);
218+
219+ return cleanup;
220+}
221+
186222 // ─── Paste handling ───────────────────────────────────────────────────────────
187223
188224 const PASTE_SENTINEL = "\x00PASTE\x00";
src/cli/output.ts+0−3
@@ -42,9 +42,6 @@ export function registerTerminalCleanup(): void {
4242 process.exit(143);
4343 });
4444 process.on("SIGINT", () => {
45- // If another handler is registered (e.g. processUserInput's abort handler),
46- // let it handle the interrupt — don't exit the process.
47- if (process.listenerCount("SIGINT") > 1) return;
4845 cleanup();
4946 process.exit(130);
5047 });