xonecas.io
64875
Mc

mini-coder / commit d3862f1

fix(cli): interrupt custom-command subagents with ESC

xonecas2026-03-13 d3862f127b2ee74691c01c3fec80b4d2eeb3f460 parent 4cc8769

9 files changed

TODO.md+1−1
@@ -1,7 +1,7 @@
11 # TODO
22
3-- Newline missing after spinner, new content is appended starting on the same line as the spinner line.
43 - ESC doesn't interrupt subagents created by custom commands, example: can't interrupt a review agent
4+- Surface to the user when compacting happens in a structured output
55
66 ---
77
src/agent/agent.ts+2−2
@@ -209,8 +209,8 @@ export async function initAgent(opts: AgentOptions): Promise<{
209209 runner.planMode = v;
210210 },
211211 cwd,
212- runSubagent: (prompt, agentName?, model?) =>
213- runSubagent(prompt, agentName, model),
212+ runSubagent: (prompt, agentName?, model?, abortSignal?) =>
213+ runSubagent(prompt, agentName, model, abortSignal),
214214
215215 get activeAgent() {
216216 return activeAgentName;
src/agent/subagent-runner.ts+41−0
@@ -79,6 +79,7 @@ export function createSubagentRunner(
7979 prompt: string,
8080 agentName?: string,
8181 modelOverride?: string,
82+ abortSignal?: AbortSignal,
8283 ): Promise<SubagentOutput> => {
8384 if (subagentDepth >= MAX_SUBAGENT_DEPTH) {
8485 throw new Error(
@@ -87,6 +88,13 @@ export function createSubagentRunner(
8788 );
8889 }
8990
91+ if (abortSignal?.aborted) {
92+ throw new DOMException(
93+ "Subagent execution was interrupted",
94+ "AbortError",
95+ );
96+ }
97+
9098 const model = modelOverride ?? getCurrentModel();
9199 const cmd = [
92100 ...getMcCommand(),
@@ -114,6 +122,20 @@ export function createSubagentRunner(
114122
115123 activeProcs.add(proc);
116124
125+ let aborted = false;
126+ const onAbort = () => {
127+ aborted = true;
128+ try {
129+ proc.kill("SIGTERM");
130+ } catch {
131+ /* process may have already exited */
132+ }
133+ };
134+
135+ if (abortSignal) {
136+ abortSignal.addEventListener("abort", onAbort);
137+ }
138+
117139 try {
118140 const [text, stdout, stderr] = await Promise.all([
119141 Bun.file(proc.stdio[3] as number).text(),
@@ -121,6 +143,14 @@ export function createSubagentRunner(
121143 consumeTail(proc.stderr),
122144 proc.exited,
123145 ]);
146+
147+ if (aborted || abortSignal?.aborted) {
148+ throw new DOMException(
149+ "Subagent execution was interrupted",
150+ "AbortError",
151+ );
152+ }
153+
124154 const diagnostics = formatSubagentDiagnostics(stdout, stderr);
125155
126156 const trimmed = text.trim();
@@ -156,7 +186,18 @@ export function createSubagentRunner(
156186 if (agentName) output.agentName = agentName;
157187
158188 return output;
189+ } catch (error) {
190+ if (aborted || abortSignal?.aborted) {
191+ throw new DOMException(
192+ "Subagent execution was interrupted",
193+ "AbortError",
194+ );
195+ }
196+ throw error;
159197 } finally {
198+ if (abortSignal) {
199+ abortSignal.removeEventListener("abort", onAbort);
200+ }
160201 activeProcs.delete(proc);
161202 }
162203 };
src/cli/commands.ts+18−2
@@ -1,4 +1,5 @@
11 import * as c from "yoctocolors";
2+import { isAbortError } from "../agent/agent-helpers.ts";
23 import type { ThinkingEffort } from "../llm-api/providers.ts";
34 import { fetchAvailableModels } from "../llm-api/providers.ts";
45 import {
@@ -6,15 +7,16 @@ import {
67 listMcpServers,
78 upsertMcpServer,
89 } from "../session/db/index.ts";
9-
1010 import { loadAgents } from "./agents.ts";
1111 import {
1212 type CustomCommand,
1313 expandTemplate,
1414 loadCustomCommands,
1515 } from "./custom-commands.ts";
16+import { watchForCancel } from "./input.ts";
1617 import { renderMarkdown } from "./markdown.ts";
1718 import { PREFIX, write, writeln } from "./output.ts";
19+
1820 import { loadSkills } from "./skills.ts";
1921
2022 // ─── Types ────────────────────────────────────────────────────────────────────
@@ -462,6 +464,7 @@ async function handleCustomCommand(
462464 writeln(`${PREFIX.info} ${label} ${src}`);
463465 writeln();
464466
467+ // context: fork (Claude Code) or subtask: true (OpenCode) → isolated subagent.
465468 // context: fork (Claude Code) or subtask: true (OpenCode) → isolated subagent.
466469 // Default: run inline in the current conversation.
467470 const fork = cmd.context === "fork" || cmd.subtask === true;
@@ -470,9 +473,18 @@ async function handleCustomCommand(
470473 return { type: "inject-user-message", text: prompt };
471474 }
472475
476+ const abortController = new AbortController();
477+ const stopWatcher = watchForCancel(abortController, {
478+ allowSubagentEsc: true,
479+ });
473480 try {
474481 ctx.startSpinner("subagent");
475- const output = await ctx.runSubagent(prompt, cmd.agent, cmd.model);
482+ const output = await ctx.runSubagent(
483+ prompt,
484+ cmd.agent,
485+ cmd.model,
486+ abortController.signal,
487+ );
476488
477489 write(renderMarkdown(output.result));
478490 writeln();
@@ -482,9 +494,13 @@ async function handleCustomCommand(
482494 text: `/${cmd.name} output:\n\n${output.result}\n\n<system-message>Summarize the findings above to the user.</system-message>`,
483495 };
484496 } catch (e) {
497+ if (isAbortError(e as Error)) {
498+ return { type: "handled" };
499+ }
485500 writeln(`${PREFIX.error} /${cmd.name} failed: ${String(e)}`);
486501 return { type: "handled" };
487502 } finally {
503+ stopWatcher();
488504 ctx.stopSpinner();
489505 }
490506 }
src/cli/input.test.ts+29−0
@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test";
22 import {
33 buildPromptDisplay,
44 expandInputBuffer,
5+ getSubagentControlAction,
56 getTurnControlAction,
67 pasteLabel,
78 pruneInputPasteTokens,
@@ -139,3 +140,31 @@ describe("getTurnControlAction", () => {
139140 expect(getTurnControlAction(new Uint8Array([0x61, 0x62, 0x63]))).toBeNull();
140141 });
141142 });
143+
144+describe("getSubagentControlAction", () => {
145+ test("treats any ESC-containing sequence as cancel", () => {
146+ expect(getSubagentControlAction(new Uint8Array([0x1b]))).toBe("cancel");
147+ expect(getSubagentControlAction(new Uint8Array([0x1b, 0x66]))).toBe(
148+ "cancel",
149+ );
150+ expect(getSubagentControlAction(new Uint8Array([0x1b, 0x1b]))).toBe(
151+ "cancel",
152+ );
153+ expect(getSubagentControlAction(new Uint8Array([0x1b, 0x5b, 0x41]))).toBe(
154+ "cancel",
155+ );
156+ expect(getSubagentControlAction(new Uint8Array([0x1b, 0x4f, 0x50]))).toBe(
157+ "cancel",
158+ );
159+ expect(getSubagentControlAction(new Uint8Array([0x61, 0x1b, 0x62]))).toBe(
160+ "cancel",
161+ );
162+ });
163+
164+ test("returns quit on Ctrl+C", () => {
165+ expect(getSubagentControlAction(new Uint8Array([0x03]))).toBe("quit");
166+ expect(
167+ getSubagentControlAction(new Uint8Array([0x1b, 0x5b, 0x41, 0x03])),
168+ ).toBe("quit");
169+ });
170+});
src/cli/input.ts+28−3
@@ -192,7 +192,6 @@ async function readKey(reader: StreamReader): Promise<string> {
192192 // handler — NOT via the shared ReadableStream reader — so that the watcher and
193193 // readline() never race for the same bytes. The caller must call the returned
194194 // stop() in a finally block.
195-
196195 export function getTurnControlAction(
197196 chunk: Uint8Array,
198197 ): "cancel" | "quit" | null {
@@ -206,6 +205,25 @@ export function getTurnControlAction(
206205 return null;
207206 }
208207
208+export function getSubagentControlAction(
209+ chunk: Uint8Array,
210+): "cancel" | "quit" | null {
211+ // During custom-command subagent runs there is no interactive line editing,
212+ // so any ESC byte should interrupt (terminals may encode ESC as multi-byte
213+ // CSI/SS3 or other escape-prefixed sequences).
214+ for (const byte of chunk) {
215+ if (byte === CTRL_C_BYTE) return "quit";
216+ }
217+ for (const byte of chunk) {
218+ if (byte === ESC_BYTE) return "cancel";
219+ }
220+ return null;
221+}
222+
223+type WatchForCancelOptions = {
224+ allowSubagentEsc?: boolean;
225+};
226+
209227 function exitOnCtrlC(opts?: {
210228 printNewline?: boolean;
211229 disableBracketedPaste?: boolean;
@@ -219,7 +237,10 @@ function exitOnCtrlC(opts?: {
219237 process.exit(130);
220238 }
221239
222-export function watchForCancel(abortController: AbortController): () => void {
240+export function watchForCancel(
241+ abortController: AbortController,
242+ options?: WatchForCancelOptions,
243+): () => void {
223244 if (!terminal.isTTY) return () => {};
224245
225246 const onCancel = () => {
@@ -227,8 +248,12 @@ export function watchForCancel(abortController: AbortController): () => void {
227248 abortController.abort();
228249 };
229250
251+ const getAction = options?.allowSubagentEsc
252+ ? getSubagentControlAction
253+ : getTurnControlAction;
254+
230255 const onData = (chunk: Buffer) => {
231- const action = getTurnControlAction(chunk);
256+ const action = getAction(chunk);
232257 if (action === "cancel") {
233258 onCancel();
234259 return;
src/cli/spinner.test.ts+21−1
@@ -1,5 +1,5 @@
11 import { describe, expect, test } from "bun:test";
2-import { SPINNER_FRAMES } from "./spinner.ts";
2+import { SPINNER_FRAMES, Spinner } from "./spinner.ts";
33
44 const BRAILLE_BASE = 0x2800;
55 const BRAILLE_DOT_7 = 1 << 6;
@@ -15,3 +15,23 @@ describe("SPINNER_FRAMES", () => {
1515 }
1616 });
1717 });
18+
19+describe("Spinner", () => {
20+ test("moves cursor to a new line when stopped", () => {
21+ const originalWrite = process.stderr.write;
22+ let stderr = "";
23+ process.stderr.write = ((text: string) => {
24+ stderr += text;
25+ return true;
26+ }) as typeof process.stderr.write;
27+
28+ try {
29+ const spinner = new Spinner();
30+ spinner.start("thinking");
31+ spinner.stop();
32+ expect(stderr).toContain("\n");
33+ } finally {
34+ process.stderr.write = originalWrite;
35+ }
36+ });
37+});
src/cli/spinner.ts+1−1
@@ -19,7 +19,7 @@ export class Spinner {
1919 if (!this.timer) return;
2020 clearInterval(this.timer);
2121 this.timer = null;
22- process.stderr.write("\r\x1B[2K\x1B[?25h");
22+ process.stderr.write("\r\x1B[2K\x1B[?25h\n");
2323 }
2424
2525 update(label: string): void {
src/cli/types.ts+1−0
@@ -31,6 +31,7 @@ export interface CommandContext {
3131 prompt: string,
3232 agentName?: string,
3333 model?: string,
34+ abortSignal?: AbortSignal,
3435 ) => Promise<SubagentOutput>;
3536
3637 activeAgent: string | null;