From d0a1398e4134cfe9bbcc53a576422a7c502ddb4d Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 18 Nov 2026 20:08:35 +0000 Subject: [PATCH 1/3] fix(cli): ensure agent console exits cleanly on signals and Ctrl-C Wrap the Ink console in runAgentConsoleInk with SIGINT/SIGTERM/SIGHUP handlers, a 2s teardown watchdog, stdin release, and a final process.exit so leaked TTY handles cannot keep the event loop alive (#295). --- .../2026-11-18-fix-agent-console-exit.md | 16 ++ .../2026-11-18-fix-agent-console-exit.md | 12 + .../2026-11-18-fix-agent-console-exit.md | 6 + .../2026-11-18-fix-agent-console-exit.md | 12 + .../2026-11-18-fix-agent-console-exit.md | 17 ++ .../cli/src/commands/agent/console.command.ts | 5 +- .../cli/src/tui/console/runAgentConsole.ts | 137 +++++++++++ .../tests/tui/console/runAgentConsole.test.ts | 226 ++++++++++++++++++ 8 files changed, 429 insertions(+), 2 deletions(-) create mode 100644 docs/ai/design/2026-11-18-fix-agent-console-exit.md create mode 100644 docs/ai/implementation/2026-11-18-fix-agent-console-exit.md create mode 100644 docs/ai/planning/2026-11-18-fix-agent-console-exit.md create mode 100644 docs/ai/requirements/2026-11-18-fix-agent-console-exit.md create mode 100644 docs/ai/testing/2026-11-18-fix-agent-console-exit.md create mode 100644 packages/cli/src/tui/console/runAgentConsole.ts create mode 100644 packages/cli/tests/tui/console/runAgentConsole.test.ts diff --git a/docs/ai/design/2026-11-18-fix-agent-console-exit.md b/docs/ai/design/2026-11-18-fix-agent-console-exit.md new file mode 100644 index 000000000..a9d5345cb --- /dev/null +++ b/docs/ai/design/2026-11-18-fix-agent-console-exit.md @@ -0,0 +1,16 @@ +# Design: agent console lifecycle wrapper + +## Root cause + +The command only awaited Ink `waitUntilExit()` with `exitOnCtrlC: false` (so the TUI can cancel panes on Ctrl-C). There were no CLI-level signal handlers or forced process exit. When Ink teardown stalled or libuv kept TTY handles referenced after unmount, the Node event loop stayed alive and the process ignored further signals. + +## Approach + +Add `runAgentConsoleInk()` beside the console TUI: + +1. Register `SIGINT`/`SIGTERM`/`SIGHUP` → `unmount()` + bounded `waitUntilExit()`. +2. Arm a 2s watchdog during signal teardown; call `process.exit` if Ink does not settle. +3. `releaseConsoleStdin()` disables raw mode, pauses, and unrefs stdin before exit. +4. Normal `q`/Ctrl-C path still resolves `waitUntilExit()`; then `process.exit(0)`. + +`console.command.ts` delegates to this wrapper instead of calling `render()` + `waitUntilExit()` directly. \ No newline at end of file diff --git a/docs/ai/implementation/2026-11-18-fix-agent-console-exit.md b/docs/ai/implementation/2026-11-18-fix-agent-console-exit.md new file mode 100644 index 000000000..122e1bd8e --- /dev/null +++ b/docs/ai/implementation/2026-11-18-fix-agent-console-exit.md @@ -0,0 +1,12 @@ +# Implementation: agent console exit (#295) + +## Changes + +- `packages/cli/src/tui/console/runAgentConsole.ts` — lifecycle owner for Ink console sessions. +- `packages/cli/src/commands/agent/console.command.ts` — uses `runAgentConsoleInk`. +- `packages/cli/tests/tui/console/runAgentConsole.test.ts` — regression tests. + +## Decisions + +- Keep `exitOnCtrlC: false` so pane-level Ctrl-C cancel behavior in `ConsoleApp` is unchanged (#337). +- Force `process.exit` after teardown so leaked stdin/TTY refs cannot pin the event loop (#295). \ No newline at end of file diff --git a/docs/ai/planning/2026-11-18-fix-agent-console-exit.md b/docs/ai/planning/2026-11-18-fix-agent-console-exit.md new file mode 100644 index 000000000..013b0e1ea --- /dev/null +++ b/docs/ai/planning/2026-11-18-fix-agent-console-exit.md @@ -0,0 +1,6 @@ +# Plan: fix agent console exit (#295) + +- [x] Add `runAgentConsole.ts` lifecycle wrapper with signal handlers, watchdog, stdin release. +- [x] Wire `console.command.ts` through the wrapper. +- [x] Unit tests in `packages/cli/tests/tui/console/runAgentConsole.test.ts`. +- [x] Manual PTY smoke (Ctrl-C, `q`, `SIGTERM`, `SIGHUP`). \ No newline at end of file diff --git a/docs/ai/requirements/2026-11-18-fix-agent-console-exit.md b/docs/ai/requirements/2026-11-18-fix-agent-console-exit.md new file mode 100644 index 000000000..89960118e --- /dev/null +++ b/docs/ai/requirements/2026-11-18-fix-agent-console-exit.md @@ -0,0 +1,12 @@ +# Requirements: fix agent console exit (#295) + +## Problem + +`ai-devkit agent console` can ignore Ctrl-C after running for a while, leak `/dev/tty` handles, and keep ~3–4% CPU until `SIGKILL`. `SIGTERM`/`SIGHUP` are not handled gracefully while Ink is active. + +## Acceptance criteria + +- Ctrl-C and `q` exit within 2s with terminal state restored. +- `SIGTERM`, `SIGINT`, and `SIGHUP` unmount Ink and exit within 2s with conventional exit codes. +- After Ink unmount, the process must not rely on the event loop draining (`process.exit` guard). +- Regression tests cover signal mapping, stdin release, watchdog timeout, and normal Ink exit. \ No newline at end of file diff --git a/docs/ai/testing/2026-11-18-fix-agent-console-exit.md b/docs/ai/testing/2026-11-18-fix-agent-console-exit.md new file mode 100644 index 000000000..9933167ad --- /dev/null +++ b/docs/ai/testing/2026-11-18-fix-agent-console-exit.md @@ -0,0 +1,17 @@ +# Testing: agent console exit (#295) + +## Automated + +```bash +cd packages/cli && npx vitest run tests/tui/console/runAgentConsole.test.ts +``` + +Covers `exitCodeForSignal`, `releaseConsoleStdin`, watchdog timing, normal Ink exit, and signal-driven unmount. + +## Manual (PTY) + +Python `pty.fork()` harness against built `packages/cli/dist/cli.js`: + +- 20× random-delay Ctrl-C: 20/20 clean `exit 0` (Linux agent environment). +- 90s idle + `q`: clean exit. +- `SIGTERM`/`SIGHUP` after 2s: process exits with codes 143/129 (not hang). \ No newline at end of file diff --git a/packages/cli/src/commands/agent/console.command.ts b/packages/cli/src/commands/agent/console.command.ts index 1c481fc60..a3145ec52 100644 --- a/packages/cli/src/commands/agent/console.command.ts +++ b/packages/cli/src/commands/agent/console.command.ts @@ -21,12 +21,13 @@ export function registerAgentConsoleCommand(agentCommand: Command): void { import("ink"), import("../../tui/console/ConsoleApp.js"), ]); + const { runAgentConsoleInk } = await import("../../tui/console/runAgentConsole.js"); const manager = createAgentManager(); - const { waitUntilExit } = render( + await runAgentConsoleInk( React.createElement(ConsoleApp, { manager }), AGENT_CONSOLE_RENDER_OPTIONS, + { renderInstance: render }, ); - await waitUntilExit(); }), ); } diff --git a/packages/cli/src/tui/console/runAgentConsole.ts b/packages/cli/src/tui/console/runAgentConsole.ts new file mode 100644 index 000000000..ea805ba82 --- /dev/null +++ b/packages/cli/src/tui/console/runAgentConsole.ts @@ -0,0 +1,137 @@ +import process from "node:process"; +import type { Instance, RenderOptions } from "ink"; +import type { ReactElement } from "react"; + +/** Wall-clock limit for Ink teardown before we force-exit anyway (#295). */ +export const CONSOLE_EXIT_WATCHDOG_MS = 2_000; + +/** Map a termination signal to a conventional CLI exit code. */ +export function exitCodeForSignal(signal: NodeJS.Signals): number { + switch (signal) { + case "SIGINT": + return 130; + case "SIGTERM": + return 143; + case "SIGHUP": + return 129; + default: + return 1; + } +} + +/** Best-effort stdin teardown so leaked TTY refs cannot keep the loop alive. */ +export function releaseConsoleStdin(stdin: NodeJS.ReadStream = process.stdin): void { + if (!stdin.isTTY || typeof stdin.setRawMode !== "function") { + return; + } + try { + stdin.setRawMode(false); + } catch { + // Stream may already be closed after SIGHUP. + } + stdin.pause(); + stdin.unref(); +} + +export interface ConsoleExitWatchdog { + arm(onTimeout: () => void): void; + disarm(): void; +} + +/** Arm a one-shot watchdog around Ink unmount; used by tests via injection. */ +export function createConsoleExitWatchdog( + ms: number = CONSOLE_EXIT_WATCHDOG_MS, +): ConsoleExitWatchdog { + let handle: ReturnType | undefined; + return { + arm(onTimeout) { + disarmWatchdog(); + handle = setTimeout(onTimeout, ms); + handle.unref?.(); + }, + disarm() { + disarmWatchdog(); + }, + }; + + function disarmWatchdog() { + if (handle !== undefined) { + clearTimeout(handle); + handle = undefined; + } + } +} + +export interface RunAgentConsoleInkOptions { + renderInstance: (app: ReactElement, options: RenderOptions) => Instance; + createWatchdog?: () => ConsoleExitWatchdog; +} + +/** + * Owns Ink instance lifecycle for `agent console`: signal-driven exit, + * bounded wait on `waitUntilExit`, stdin release, and a final `process.exit` + * so the CLI never depends on the event loop draining on its own (#295). + */ +export async function runAgentConsoleInk( + app: ReactElement, + renderOptions: RenderOptions, + { renderInstance, createWatchdog = createConsoleExitWatchdog }: RunAgentConsoleInkOptions, +): Promise { + const instance = renderInstance(app, renderOptions); + const watchdog = createWatchdog(); + let tearingDown = false; + let exitCode = 0; + + const forceProcessExit = (code: number): void => { + releaseConsoleStdin(); + // eslint-disable-next-line n/no-process-exit -- deliberate console shutdown (#295) + process.exit(code); + }; + + const teardown = async (code: number): Promise => { + if (tearingDown) return; + tearingDown = true; + exitCode = code; + instance.unmount(); + watchdog.arm(() => { + try { + forceProcessExit(code); + } catch { + // Tests may stub process.exit to throw; production never returns. + } + }); + try { + await instance.waitUntilExit(); + } catch { + // Ink reports exit(errors) via rejection; still shut down. + } finally { + watchdog.disarm(); + } + forceProcessExit(code); + }; + + const signals: NodeJS.Signals[] = ["SIGINT", "SIGTERM", "SIGHUP"]; + const onSignal = (signal: NodeJS.Signals) => { + void teardown(exitCodeForSignal(signal)).catch(() => { + // process.exit ends the CLI; tests may stub it to throw. + }); + }; + for (const signal of signals) { + process.once(signal, onSignal); + } + + try { + await instance.waitUntilExit(); + } catch { + exitCode = 1; + } finally { + for (const signal of signals) { + process.removeListener(signal, onSignal); + } + watchdog.disarm(); + if (!tearingDown) { + tearingDown = true; + forceProcessExit(exitCode); + } + } +} diff --git a/packages/cli/tests/tui/console/runAgentConsole.test.ts b/packages/cli/tests/tui/console/runAgentConsole.test.ts new file mode 100644 index 000000000..aa72d81d4 --- /dev/null +++ b/packages/cli/tests/tui/console/runAgentConsole.test.ts @@ -0,0 +1,226 @@ +import { EventEmitter } from "node:events"; +import process from "node:process"; +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import type { Instance } from "ink"; +import type { ReactElement } from "react"; +import { + CONSOLE_EXIT_WATCHDOG_MS, + createConsoleExitWatchdog, + exitCodeForSignal, + releaseConsoleStdin, + runAgentConsoleInk, + type ConsoleExitWatchdog, +} from "../../../src/tui/console/runAgentConsole.js"; + +describe("exitCodeForSignal", () => { + it("maps common shutdown signals to conventional exit codes", () => { + expect(exitCodeForSignal("SIGINT")).toBe(130); + expect(exitCodeForSignal("SIGTERM")).toBe(143); + expect(exitCodeForSignal("SIGHUP")).toBe(129); + }); +}); + +describe("releaseConsoleStdin", () => { + it("disables raw mode, pauses, and unrefs a TTY stdin", () => { + const setRawMode = vi.fn(); + const pause = vi.fn(); + const unref = vi.fn(); + const stdin = { + isTTY: true, + setRawMode, + pause, + unref, + } as unknown as NodeJS.ReadStream; + + releaseConsoleStdin(stdin); + + expect(setRawMode).toHaveBeenCalledWith(false); + expect(pause).toHaveBeenCalled(); + expect(unref).toHaveBeenCalled(); + }); + + it("no-ops when stdin is not a TTY", () => { + const stdin = { isTTY: false } as NodeJS.ReadStream; + expect(() => releaseConsoleStdin(stdin)).not.toThrow(); + }); +}); + +describe("createConsoleExitWatchdog", () => { + it("fires once after the configured delay", () => { + vi.useFakeTimers(); + const onTimeout = vi.fn(); + const watchdog = createConsoleExitWatchdog(500); + watchdog.arm(onTimeout); + expect(onTimeout).not.toHaveBeenCalled(); + vi.advanceTimersByTime(499); + expect(onTimeout).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + expect(onTimeout).toHaveBeenCalledOnce(); + vi.useRealTimers(); + }); + + it("can be disarmed before firing", () => { + vi.useFakeTimers(); + const onTimeout = vi.fn(); + const watchdog = createConsoleExitWatchdog(500); + watchdog.arm(onTimeout); + watchdog.disarm(); + vi.advanceTimersByTime(1000); + expect(onTimeout).not.toHaveBeenCalled(); + vi.useRealTimers(); + }); + + it("defaults to the console exit watchdog budget", () => { + expect(CONSOLE_EXIT_WATCHDOG_MS).toBe(2000); + vi.useFakeTimers(); + const onTimeout = vi.fn(); + createConsoleExitWatchdog().arm(onTimeout); + vi.advanceTimersByTime(CONSOLE_EXIT_WATCHDOG_MS); + expect(onTimeout).toHaveBeenCalledOnce(); + vi.useRealTimers(); + }); +}); + +class ProcessExitForTest extends Error { + constructor(readonly code: number) { + super(`process.exit(${code})`); + } +} + +describe("runAgentConsoleInk", () => { + const exitSpy = vi.spyOn(process, "exit").mockImplementation((code: number) => { + throw new ProcessExitForTest(code); + }); + + beforeEach(() => { + exitSpy.mockClear(); + }); + + afterEach(() => { + process.removeAllListeners("SIGINT"); + process.removeAllListeners("SIGTERM"); + process.removeAllListeners("SIGHUP"); + }); + + function createMockInstance(): Instance { + let resolveExit: (() => void) | undefined; + const exitPromise = new Promise((resolve) => { + resolveExit = resolve; + }); + const waitUntilExit = vi.fn(() => exitPromise); + const unmount = vi.fn(() => { + resolveExit?.(); + }); + return { + rerender: vi.fn(), + unmount, + waitUntilExit, + waitUntilRenderFlush: vi.fn(), + cleanup: vi.fn(), + clear: vi.fn(), + }; + } + + function createHarness(instance: Instance, watchdog?: ConsoleExitWatchdog) { + const renderInstance = vi.fn(() => instance); + const emitter = new EventEmitter(); + const createWatchdog = (): ConsoleExitWatchdog => + watchdog ?? { + arm(onTimeout) { + emitter.once("timeout", onTimeout); + }, + disarm() { + emitter.removeAllListeners("timeout"); + }, + }; + return { + renderInstance, + emitter, + run: () => runAgentConsoleInk({} as ReactElement, {}, { renderInstance, createWatchdog }), + }; + } + + it("renders the app and exits when Ink finishes", async () => { + let resolveExit: (() => void) | undefined; + const instance: Instance = { + rerender: vi.fn(), + unmount: vi.fn(), + waitUntilExit: vi.fn( + () => + new Promise((resolve) => { + resolveExit = resolve; + queueMicrotask(() => resolve()); + }), + ), + waitUntilRenderFlush: vi.fn(), + cleanup: vi.fn(), + clear: vi.fn(), + }; + const { renderInstance, run } = createHarness(instance); + await expect(run()).rejects.toBeInstanceOf(ProcessExitForTest); + expect(renderInstance).toHaveBeenCalledOnce(); + expect(instance.unmount).not.toHaveBeenCalled(); + expect(resolveExit).toBeDefined(); + expect(exitSpy).toHaveBeenCalledWith(0); + }); + + function invokeLatestSignalHandler(signal: NodeJS.Signals): void { + const handler = process.listeners(signal).at(-1); + if (typeof handler !== "function") { + throw new Error(`no handler for ${signal}`); + } + (handler as (name: NodeJS.Signals) => void)(signal); + } + + it("unmounts and exits with 130 when SIGINT is received", async () => { + const instance = createMockInstance(); + const { run } = createHarness(instance); + const running = run(); + await Promise.resolve(); + invokeLatestSignalHandler("SIGINT"); + await Promise.resolve(); + expect(instance.unmount).toHaveBeenCalledOnce(); + expect(exitSpy).toHaveBeenCalledWith(130); + void running; + }); + + it("unmounts and exits with 143 when SIGTERM is received", async () => { + const instance = createMockInstance(); + const { run } = createHarness(instance); + const running = run(); + await Promise.resolve(); + invokeLatestSignalHandler("SIGTERM"); + await Promise.resolve(); + expect(instance.unmount).toHaveBeenCalledOnce(); + expect(exitSpy).toHaveBeenCalledWith(143); + void running; + }); + + it("force-exits when Ink teardown exceeds the watchdog", async () => { + vi.useFakeTimers(); + const instance: Instance = { + rerender: vi.fn(), + unmount: vi.fn(), + waitUntilExit: vi.fn(() => new Promise(() => {})), + waitUntilRenderFlush: vi.fn(), + cleanup: vi.fn(), + clear: vi.fn(), + }; + const renderInstance = vi.fn(() => instance); + const running = runAgentConsoleInk( + {} as ReactElement, + {}, + { + renderInstance, + createWatchdog: () => createConsoleExitWatchdog(500), + }, + ); + await Promise.resolve(); + invokeLatestSignalHandler("SIGINT"); + await vi.advanceTimersByTimeAsync(500); + expect(instance.unmount).toHaveBeenCalledOnce(); + expect(exitSpy).toHaveBeenCalledWith(130); + void running; + vi.useRealTimers(); + }); +}); From 028ea2eabf06ff143c4c99ee5bb838abf42f5c15 Mon Sep 17 00:00:00 2001 From: Hoang Nguyen Date: Thu, 26 Nov 2026 15:55:06 +0100 Subject: [PATCH 2/3] refactor(cli): simplify agent console exit lifecycle and harden signal teardown --- .../2026-11-18-fix-agent-console-exit.md | 2 +- .../cli/src/commands/agent/console.command.ts | 18 +- .../cli/src/tui/console/runAgentConsole.ts | 133 ++++---- .../tests/tui/console/runAgentConsole.test.ts | 286 ++++++++++-------- 4 files changed, 224 insertions(+), 215 deletions(-) diff --git a/docs/ai/testing/2026-11-18-fix-agent-console-exit.md b/docs/ai/testing/2026-11-18-fix-agent-console-exit.md index 9933167ad..1863bca3d 100644 --- a/docs/ai/testing/2026-11-18-fix-agent-console-exit.md +++ b/docs/ai/testing/2026-11-18-fix-agent-console-exit.md @@ -6,7 +6,7 @@ cd packages/cli && npx vitest run tests/tui/console/runAgentConsole.test.ts ``` -Covers `exitCodeForSignal`, `releaseConsoleStdin`, watchdog timing, normal Ink exit, and signal-driven unmount. +Covers `SIGNAL_EXIT_CODES`, `releaseConsoleStdin`, watchdog timing, normal Ink exit, error propagation, and signal-driven unmount. ## Manual (PTY) diff --git a/packages/cli/src/commands/agent/console.command.ts b/packages/cli/src/commands/agent/console.command.ts index a3145ec52..936fde7bc 100644 --- a/packages/cli/src/commands/agent/console.command.ts +++ b/packages/cli/src/commands/agent/console.command.ts @@ -15,13 +15,17 @@ export function registerAgentConsoleCommand(agentCommand: Command): void { } // The TUI pulls in react/ink/yoga — keep it out of the eager graph // so non-TUI commands don't pay the module cost. - const [{ default: React }, { render }, { AGENT_CONSOLE_RENDER_OPTIONS, ConsoleApp }] = - await Promise.all([ - import("react"), - import("ink"), - import("../../tui/console/ConsoleApp.js"), - ]); - const { runAgentConsoleInk } = await import("../../tui/console/runAgentConsole.js"); + const [ + { default: React }, + { render }, + { AGENT_CONSOLE_RENDER_OPTIONS, ConsoleApp }, + { runAgentConsoleInk }, + ] = await Promise.all([ + import("react"), + import("ink"), + import("../../tui/console/ConsoleApp.js"), + import("../../tui/console/runAgentConsole.js"), + ]); const manager = createAgentManager(); await runAgentConsoleInk( React.createElement(ConsoleApp, { manager }), diff --git a/packages/cli/src/tui/console/runAgentConsole.ts b/packages/cli/src/tui/console/runAgentConsole.ts index ea805ba82..226525286 100644 --- a/packages/cli/src/tui/console/runAgentConsole.ts +++ b/packages/cli/src/tui/console/runAgentConsole.ts @@ -5,19 +5,14 @@ import type { ReactElement } from "react"; /** Wall-clock limit for Ink teardown before we force-exit anyway (#295). */ export const CONSOLE_EXIT_WATCHDOG_MS = 2_000; -/** Map a termination signal to a conventional CLI exit code. */ -export function exitCodeForSignal(signal: NodeJS.Signals): number { - switch (signal) { - case "SIGINT": - return 130; - case "SIGTERM": - return 143; - case "SIGHUP": - return 129; - default: - return 1; - } -} +export const SIGNAL_EXIT_CODES = { + SIGINT: 130, + SIGTERM: 143, + SIGHUP: 129, +} as const satisfies Partial>; + +type ShutdownSignal = keyof typeof SIGNAL_EXIT_CODES; +const SHUTDOWN_SIGNALS = Object.keys(SIGNAL_EXIT_CODES) as ShutdownSignal[]; /** Best-effort stdin teardown so leaked TTY refs cannot keep the loop alive. */ export function releaseConsoleStdin(stdin: NodeJS.ReadStream = process.stdin): void { @@ -33,38 +28,9 @@ export function releaseConsoleStdin(stdin: NodeJS.ReadStream = process.stdin): v stdin.unref(); } -export interface ConsoleExitWatchdog { - arm(onTimeout: () => void): void; - disarm(): void; -} - -/** Arm a one-shot watchdog around Ink unmount; used by tests via injection. */ -export function createConsoleExitWatchdog( - ms: number = CONSOLE_EXIT_WATCHDOG_MS, -): ConsoleExitWatchdog { - let handle: ReturnType | undefined; - return { - arm(onTimeout) { - disarmWatchdog(); - handle = setTimeout(onTimeout, ms); - handle.unref?.(); - }, - disarm() { - disarmWatchdog(); - }, - }; - - function disarmWatchdog() { - if (handle !== undefined) { - clearTimeout(handle); - handle = undefined; - } - } -} - export interface RunAgentConsoleInkOptions { renderInstance: (app: ReactElement, options: RenderOptions) => Instance; - createWatchdog?: () => ConsoleExitWatchdog; + watchdogMs?: number; } /** @@ -75,63 +41,74 @@ export interface RunAgentConsoleInkOptions { export async function runAgentConsoleInk( app: ReactElement, renderOptions: RenderOptions, - { renderInstance, createWatchdog = createConsoleExitWatchdog }: RunAgentConsoleInkOptions, + { renderInstance, watchdogMs = CONSOLE_EXIT_WATCHDOG_MS }: RunAgentConsoleInkOptions, ): Promise { const instance = renderInstance(app, renderOptions); - const watchdog = createWatchdog(); - let tearingDown = false; - let exitCode = 0; + let signalExitCode: number | undefined; + let watchdog: ReturnType | undefined; + + const cleanup = (): void => { + for (const signal of SHUTDOWN_SIGNALS) { + process.off(signal, onSignal); + } + if (watchdog !== undefined) { + clearTimeout(watchdog); + watchdog = undefined; + } + }; const forceProcessExit = (code: number): void => { + cleanup(); releaseConsoleStdin(); - // eslint-disable-next-line n/no-process-exit -- deliberate console shutdown (#295) process.exit(code); }; - const teardown = async (code: number): Promise => { - if (tearingDown) return; - tearingDown = true; - exitCode = code; - instance.unmount(); - watchdog.arm(() => { + const onSignal = (signal: ShutdownSignal): void => { + if (signalExitCode !== undefined) return; + const code = SIGNAL_EXIT_CODES[signal]; + signalExitCode = code; + + watchdog = setTimeout(() => { try { forceProcessExit(code); } catch { // Tests may stub process.exit to throw; production never returns. } - }); + }, watchdogMs); + watchdog.unref?.(); + try { - await instance.waitUntilExit(); + instance.unmount(); } catch { - // Ink reports exit(errors) via rejection; still shut down. - } finally { - watchdog.disarm(); + try { + forceProcessExit(code); + } catch { + // Tests may stub process.exit to throw; production never returns. + } } - forceProcessExit(code); }; - const signals: NodeJS.Signals[] = ["SIGINT", "SIGTERM", "SIGHUP"]; - const onSignal = (signal: NodeJS.Signals) => { - void teardown(exitCodeForSignal(signal)).catch(() => { - // process.exit ends the CLI; tests may stub it to throw. - }); - }; - for (const signal of signals) { - process.once(signal, onSignal); + for (const signal of SHUTDOWN_SIGNALS) { + process.on(signal, onSignal); } + let hasExitError = false; + let exitError: unknown; try { await instance.waitUntilExit(); - } catch { - exitCode = 1; + } catch (error) { + hasExitError = true; + exitError = error; } finally { - for (const signal of signals) { - process.removeListener(signal, onSignal); - } - watchdog.disarm(); - if (!tearingDown) { - tearingDown = true; - forceProcessExit(exitCode); - } + cleanup(); + } + + if (signalExitCode !== undefined) { + forceProcessExit(signalExitCode); + } + if (hasExitError) { + releaseConsoleStdin(); + throw exitError; } + forceProcessExit(0); } diff --git a/packages/cli/tests/tui/console/runAgentConsole.test.ts b/packages/cli/tests/tui/console/runAgentConsole.test.ts index aa72d81d4..5e1c18b1d 100644 --- a/packages/cli/tests/tui/console/runAgentConsole.test.ts +++ b/packages/cli/tests/tui/console/runAgentConsole.test.ts @@ -1,22 +1,21 @@ -import { EventEmitter } from "node:events"; import process from "node:process"; -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from "vitest"; import type { Instance } from "ink"; import type { ReactElement } from "react"; import { CONSOLE_EXIT_WATCHDOG_MS, - createConsoleExitWatchdog, - exitCodeForSignal, + SIGNAL_EXIT_CODES, releaseConsoleStdin, runAgentConsoleInk, - type ConsoleExitWatchdog, } from "../../../src/tui/console/runAgentConsole.js"; -describe("exitCodeForSignal", () => { - it("maps common shutdown signals to conventional exit codes", () => { - expect(exitCodeForSignal("SIGINT")).toBe(130); - expect(exitCodeForSignal("SIGTERM")).toBe(143); - expect(exitCodeForSignal("SIGHUP")).toBe(129); +describe("SIGNAL_EXIT_CODES", () => { + it("maps shutdown signals to conventional exit codes", () => { + expect(SIGNAL_EXIT_CODES).toEqual({ + SIGINT: 130, + SIGTERM: 143, + SIGHUP: 129, + }); }); }); @@ -39,45 +38,27 @@ describe("releaseConsoleStdin", () => { expect(unref).toHaveBeenCalled(); }); - it("no-ops when stdin is not a TTY", () => { - const stdin = { isTTY: false } as NodeJS.ReadStream; - expect(() => releaseConsoleStdin(stdin)).not.toThrow(); - }); -}); - -describe("createConsoleExitWatchdog", () => { - it("fires once after the configured delay", () => { - vi.useFakeTimers(); - const onTimeout = vi.fn(); - const watchdog = createConsoleExitWatchdog(500); - watchdog.arm(onTimeout); - expect(onTimeout).not.toHaveBeenCalled(); - vi.advanceTimersByTime(499); - expect(onTimeout).not.toHaveBeenCalled(); - vi.advanceTimersByTime(1); - expect(onTimeout).toHaveBeenCalledOnce(); - vi.useRealTimers(); - }); + it("still pauses and unrefs when setRawMode throws (e.g. after SIGHUP)", () => { + const setRawMode = vi.fn(() => { + throw new Error("EBADF"); + }); + const pause = vi.fn(); + const unref = vi.fn(); + const stdin = { + isTTY: true, + setRawMode, + pause, + unref, + } as unknown as NodeJS.ReadStream; - it("can be disarmed before firing", () => { - vi.useFakeTimers(); - const onTimeout = vi.fn(); - const watchdog = createConsoleExitWatchdog(500); - watchdog.arm(onTimeout); - watchdog.disarm(); - vi.advanceTimersByTime(1000); - expect(onTimeout).not.toHaveBeenCalled(); - vi.useRealTimers(); + expect(() => releaseConsoleStdin(stdin)).not.toThrow(); + expect(pause).toHaveBeenCalled(); + expect(unref).toHaveBeenCalled(); }); - it("defaults to the console exit watchdog budget", () => { - expect(CONSOLE_EXIT_WATCHDOG_MS).toBe(2000); - vi.useFakeTimers(); - const onTimeout = vi.fn(); - createConsoleExitWatchdog().arm(onTimeout); - vi.advanceTimersByTime(CONSOLE_EXIT_WATCHDOG_MS); - expect(onTimeout).toHaveBeenCalledOnce(); - vi.useRealTimers(); + it("no-ops when stdin is not a TTY", () => { + const stdin = { isTTY: false } as NodeJS.ReadStream; + expect(() => releaseConsoleStdin(stdin)).not.toThrow(); }); }); @@ -88,8 +69,8 @@ class ProcessExitForTest extends Error { } describe("runAgentConsoleInk", () => { - const exitSpy = vi.spyOn(process, "exit").mockImplementation((code: number) => { - throw new ProcessExitForTest(code); + const exitSpy = vi.spyOn(process, "exit").mockImplementation((code) => { + throw new ProcessExitForTest(typeof code === "number" ? code : 0); }); beforeEach(() => { @@ -97,21 +78,35 @@ describe("runAgentConsoleInk", () => { }); afterEach(() => { - process.removeAllListeners("SIGINT"); - process.removeAllListeners("SIGTERM"); - process.removeAllListeners("SIGHUP"); + vi.useRealTimers(); + }); + + afterAll(() => { + exitSpy.mockRestore(); }); - function createMockInstance(): Instance { - let resolveExit: (() => void) | undefined; - const exitPromise = new Promise((resolve) => { + function createMockInstance(overrides?: { + onUnmount?: (resolveExit: () => void, rejectExit: (err: unknown) => void) => void; + }): { + instance: Instance; + resolveExit: () => void; + rejectExit: (err: unknown) => void; + } { + let resolveExit!: () => void; + let rejectExit!: (err: unknown) => void; + const exitPromise = new Promise((resolve, reject) => { resolveExit = resolve; + rejectExit = reject; }); const waitUntilExit = vi.fn(() => exitPromise); const unmount = vi.fn(() => { - resolveExit?.(); + if (overrides?.onUnmount) { + overrides.onUnmount(resolveExit, rejectExit); + } else { + resolveExit(); + } }); - return { + const instance: Instance = { rerender: vi.fn(), unmount, waitUntilExit, @@ -119,108 +114,141 @@ describe("runAgentConsoleInk", () => { cleanup: vi.fn(), clear: vi.fn(), }; + return { instance, resolveExit, rejectExit }; } - function createHarness(instance: Instance, watchdog?: ConsoleExitWatchdog) { - const renderInstance = vi.fn(() => instance); - const emitter = new EventEmitter(); - const createWatchdog = (): ConsoleExitWatchdog => - watchdog ?? { - arm(onTimeout) { - emitter.once("timeout", onTimeout); - }, - disarm() { - emitter.removeAllListeners("timeout"); - }, - }; + function invokeLatestSignalHandler(signal: NodeJS.Signals): void { + const handler = process.listeners(signal).at(-1); + if (typeof handler !== "function") { + throw new Error(`no handler for ${signal}`); + } + (handler as (name: NodeJS.Signals) => void)(signal); + } + + function listenerCounts() { return { - renderInstance, - emitter, - run: () => runAgentConsoleInk({} as ReactElement, {}, { renderInstance, createWatchdog }), + SIGINT: process.listenerCount("SIGINT"), + SIGTERM: process.listenerCount("SIGTERM"), + SIGHUP: process.listenerCount("SIGHUP"), }; } - it("renders the app and exits when Ink finishes", async () => { - let resolveExit: (() => void) | undefined; - const instance: Instance = { - rerender: vi.fn(), - unmount: vi.fn(), - waitUntilExit: vi.fn( - () => - new Promise((resolve) => { - resolveExit = resolve; - queueMicrotask(() => resolve()); - }), - ), - waitUntilRenderFlush: vi.fn(), - cleanup: vi.fn(), - clear: vi.fn(), - }; - const { renderInstance, run } = createHarness(instance); - await expect(run()).rejects.toBeInstanceOf(ProcessExitForTest); + it("renders the app, cleans up signal listeners, and exits 0 when Ink finishes", async () => { + const before = listenerCounts(); + const { instance, resolveExit } = createMockInstance(); + const renderInstance = vi.fn(() => instance); + + const running = runAgentConsoleInk({} as ReactElement, {}, { renderInstance }); + resolveExit(); + + await expect(running).rejects.toMatchObject({ code: 0 }); expect(renderInstance).toHaveBeenCalledOnce(); expect(instance.unmount).not.toHaveBeenCalled(); - expect(resolveExit).toBeDefined(); expect(exitSpy).toHaveBeenCalledWith(0); + expect(listenerCounts()).toEqual(before); }); - function invokeLatestSignalHandler(signal: NodeJS.Signals): void { - const handler = process.listeners(signal).at(-1); - if (typeof handler !== "function") { - throw new Error(`no handler for ${signal}`); - } - (handler as (name: NodeJS.Signals) => void)(signal); - } + it("rethrows Ink exit errors instead of swallowing them", async () => { + const before = listenerCounts(); + const { instance, rejectExit } = createMockInstance(); + const renderInstance = vi.fn(() => instance); + const boom = new Error("render failure"); + + const running = runAgentConsoleInk({} as ReactElement, {}, { renderInstance }); + rejectExit(boom); - it("unmounts and exits with 130 when SIGINT is received", async () => { - const instance = createMockInstance(); - const { run } = createHarness(instance); - const running = run(); - await Promise.resolve(); + await expect(running).rejects.toBe(boom); + expect(exitSpy).not.toHaveBeenCalled(); + expect(listenerCounts()).toEqual(before); + }); + + it.each([ + ["SIGINT", 130], + ["SIGTERM", 143], + ["SIGHUP", 129], + ] as const)("unmounts on %s and exits with %d", async (signal, expectedCode) => { + const before = listenerCounts(); + const { instance } = createMockInstance(); + const renderInstance = vi.fn(() => instance); + + const running = runAgentConsoleInk({} as ReactElement, {}, { renderInstance }); + invokeLatestSignalHandler(signal); + + await expect(running).rejects.toMatchObject({ code: expectedCode }); + expect(instance.unmount).toHaveBeenCalledOnce(); + expect(exitSpy).toHaveBeenCalledWith(expectedCode); + expect(listenerCounts()).toEqual(before); + }); + + it("ignores duplicate signals while tearing down", async () => { + const before = listenerCounts(); + const { instance, resolveExit } = createMockInstance({ + onUnmount: () => { + // Keep waitUntilExit pending until we explicitly resolve it. + }, + }); + const renderInstance = vi.fn(() => instance); + + const running = runAgentConsoleInk({} as ReactElement, {}, { renderInstance }); + invokeLatestSignalHandler("SIGTERM"); + invokeLatestSignalHandler("SIGTERM"); invokeLatestSignalHandler("SIGINT"); - await Promise.resolve(); + resolveExit(); + + await expect(running).rejects.toMatchObject({ code: 143 }); expect(instance.unmount).toHaveBeenCalledOnce(); - expect(exitSpy).toHaveBeenCalledWith(130); - void running; + expect(exitSpy).toHaveBeenCalledWith(143); + expect(listenerCounts()).toEqual(before); }); - it("unmounts and exits with 143 when SIGTERM is received", async () => { - const instance = createMockInstance(); - const { run } = createHarness(instance); - const running = run(); - await Promise.resolve(); + it("force-exits immediately if instance.unmount() throws synchronously", async () => { + const before = listenerCounts(); + const { instance, resolveExit } = createMockInstance({ + onUnmount: () => { + throw new Error("unmount crashed"); + }, + }); + const renderInstance = vi.fn(() => instance); + + const running = runAgentConsoleInk({} as ReactElement, {}, { renderInstance }); invokeLatestSignalHandler("SIGTERM"); - await Promise.resolve(); + expect(instance.unmount).toHaveBeenCalledOnce(); expect(exitSpy).toHaveBeenCalledWith(143); - void running; + expect(listenerCounts()).toEqual(before); + + // Clean up the pending promise from the test harness. + resolveExit(); + await expect(running).rejects.toMatchObject({ code: 143 }); }); - it("force-exits when Ink teardown exceeds the watchdog", async () => { + it("force-exits when Ink teardown exceeds the watchdog budget", async () => { vi.useFakeTimers(); - const instance: Instance = { - rerender: vi.fn(), - unmount: vi.fn(), - waitUntilExit: vi.fn(() => new Promise(() => {})), - waitUntilRenderFlush: vi.fn(), - cleanup: vi.fn(), - clear: vi.fn(), - }; + const before = listenerCounts(); + const { instance, resolveExit } = createMockInstance({ + onUnmount: () => { + // Simulate hung teardown where waitUntilExit never settles on its own. + }, + }); const renderInstance = vi.fn(() => instance); + const running = runAgentConsoleInk( {} as ReactElement, {}, - { - renderInstance, - createWatchdog: () => createConsoleExitWatchdog(500), - }, + { renderInstance, watchdogMs: CONSOLE_EXIT_WATCHDOG_MS }, ); - await Promise.resolve(); invokeLatestSignalHandler("SIGINT"); - await vi.advanceTimersByTimeAsync(500); + + await vi.advanceTimersByTimeAsync(CONSOLE_EXIT_WATCHDOG_MS - 1); + expect(exitSpy).not.toHaveBeenCalled(); + + await vi.advanceTimersByTimeAsync(1); expect(instance.unmount).toHaveBeenCalledOnce(); expect(exitSpy).toHaveBeenCalledWith(130); - void running; - vi.useRealTimers(); + expect(listenerCounts()).toEqual(before); + + // Settle the promise so no pending promise leaks across tests. + resolveExit(); + await expect(running).rejects.toMatchObject({ code: 130 }); }); }); From 75bc29f9bd43fce1fa3ead08c021e2189e4f2f96 Mon Sep 17 00:00:00 2001 From: Hoang Nguyen Date: Thu, 26 Nov 2026 16:19:31 +0100 Subject: [PATCH 3/3] refactor(cli): remove redundant comments in agent console exit helpers --- .../cli/src/tui/console/runAgentConsole.ts | 29 +++++++------------ .../tests/tui/console/runAgentConsole.test.ts | 10 ++----- 2 files changed, 12 insertions(+), 27 deletions(-) diff --git a/packages/cli/src/tui/console/runAgentConsole.ts b/packages/cli/src/tui/console/runAgentConsole.ts index 226525286..25c2dd1ef 100644 --- a/packages/cli/src/tui/console/runAgentConsole.ts +++ b/packages/cli/src/tui/console/runAgentConsole.ts @@ -2,7 +2,6 @@ import process from "node:process"; import type { Instance, RenderOptions } from "ink"; import type { ReactElement } from "react"; -/** Wall-clock limit for Ink teardown before we force-exit anyway (#295). */ export const CONSOLE_EXIT_WATCHDOG_MS = 2_000; export const SIGNAL_EXIT_CODES = { @@ -14,7 +13,6 @@ export const SIGNAL_EXIT_CODES = { type ShutdownSignal = keyof typeof SIGNAL_EXIT_CODES; const SHUTDOWN_SIGNALS = Object.keys(SIGNAL_EXIT_CODES) as ShutdownSignal[]; -/** Best-effort stdin teardown so leaked TTY refs cannot keep the loop alive. */ export function releaseConsoleStdin(stdin: NodeJS.ReadStream = process.stdin): void { if (!stdin.isTTY || typeof stdin.setRawMode !== "function") { return; @@ -33,11 +31,6 @@ export interface RunAgentConsoleInkOptions { watchdogMs?: number; } -/** - * Owns Ink instance lifecycle for `agent console`: signal-driven exit, - * bounded wait on `waitUntilExit`, stdin release, and a final `process.exit` - * so the CLI never depends on the event loop draining on its own (#295). - */ export async function runAgentConsoleInk( app: ReactElement, renderOptions: RenderOptions, @@ -63,28 +56,26 @@ export async function runAgentConsoleInk( process.exit(code); }; + const exitFromCallback = (code: number): void => { + try { + forceProcessExit(code); + } catch { + // Tests may stub process.exit to throw; production never returns. + } + }; + const onSignal = (signal: ShutdownSignal): void => { if (signalExitCode !== undefined) return; const code = SIGNAL_EXIT_CODES[signal]; signalExitCode = code; - watchdog = setTimeout(() => { - try { - forceProcessExit(code); - } catch { - // Tests may stub process.exit to throw; production never returns. - } - }, watchdogMs); + watchdog = setTimeout(() => exitFromCallback(code), watchdogMs); watchdog.unref?.(); try { instance.unmount(); } catch { - try { - forceProcessExit(code); - } catch { - // Tests may stub process.exit to throw; production never returns. - } + exitFromCallback(code); } }; diff --git a/packages/cli/tests/tui/console/runAgentConsole.test.ts b/packages/cli/tests/tui/console/runAgentConsole.test.ts index 5e1c18b1d..1cbff6949 100644 --- a/packages/cli/tests/tui/console/runAgentConsole.test.ts +++ b/packages/cli/tests/tui/console/runAgentConsole.test.ts @@ -183,9 +183,7 @@ describe("runAgentConsoleInk", () => { it("ignores duplicate signals while tearing down", async () => { const before = listenerCounts(); const { instance, resolveExit } = createMockInstance({ - onUnmount: () => { - // Keep waitUntilExit pending until we explicitly resolve it. - }, + onUnmount: () => {}, }); const renderInstance = vi.fn(() => instance); @@ -217,7 +215,6 @@ describe("runAgentConsoleInk", () => { expect(exitSpy).toHaveBeenCalledWith(143); expect(listenerCounts()).toEqual(before); - // Clean up the pending promise from the test harness. resolveExit(); await expect(running).rejects.toMatchObject({ code: 143 }); }); @@ -226,9 +223,7 @@ describe("runAgentConsoleInk", () => { vi.useFakeTimers(); const before = listenerCounts(); const { instance, resolveExit } = createMockInstance({ - onUnmount: () => { - // Simulate hung teardown where waitUntilExit never settles on its own. - }, + onUnmount: () => {}, }); const renderInstance = vi.fn(() => instance); @@ -247,7 +242,6 @@ describe("runAgentConsoleInk", () => { expect(exitSpy).toHaveBeenCalledWith(130); expect(listenerCounts()).toEqual(before); - // Settle the promise so no pending promise leaks across tests. resolveExit(); await expect(running).rejects.toMatchObject({ code: 130 }); });