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 00000000..a9d5345c --- /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 00000000..122e1bd8 --- /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 00000000..013b0e1e --- /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 00000000..89960118 --- /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 00000000..1863bca3 --- /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 `SIGNAL_EXIT_CODES`, `releaseConsoleStdin`, watchdog timing, normal Ink exit, error propagation, 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 1c481fc6..936fde7b 100644 --- a/packages/cli/src/commands/agent/console.command.ts +++ b/packages/cli/src/commands/agent/console.command.ts @@ -15,18 +15,23 @@ 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 [ + { 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(); - 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 00000000..25c2dd1e --- /dev/null +++ b/packages/cli/src/tui/console/runAgentConsole.ts @@ -0,0 +1,105 @@ +import process from "node:process"; +import type { Instance, RenderOptions } from "ink"; +import type { ReactElement } from "react"; + +export const CONSOLE_EXIT_WATCHDOG_MS = 2_000; + +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[]; + +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 RunAgentConsoleInkOptions { + renderInstance: (app: ReactElement, options: RenderOptions) => Instance; + watchdogMs?: number; +} + +export async function runAgentConsoleInk( + app: ReactElement, + renderOptions: RenderOptions, + { renderInstance, watchdogMs = CONSOLE_EXIT_WATCHDOG_MS }: RunAgentConsoleInkOptions, +): Promise { + const instance = renderInstance(app, renderOptions); + 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(); + 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(() => exitFromCallback(code), watchdogMs); + watchdog.unref?.(); + + try { + instance.unmount(); + } catch { + exitFromCallback(code); + } + }; + + for (const signal of SHUTDOWN_SIGNALS) { + process.on(signal, onSignal); + } + + let hasExitError = false; + let exitError: unknown; + try { + await instance.waitUntilExit(); + } catch (error) { + hasExitError = true; + exitError = error; + } finally { + 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 new file mode 100644 index 00000000..1cbff694 --- /dev/null +++ b/packages/cli/tests/tui/console/runAgentConsole.test.ts @@ -0,0 +1,248 @@ +import process from "node:process"; +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, + SIGNAL_EXIT_CODES, + releaseConsoleStdin, + runAgentConsoleInk, +} from "../../../src/tui/console/runAgentConsole.js"; + +describe("SIGNAL_EXIT_CODES", () => { + it("maps shutdown signals to conventional exit codes", () => { + expect(SIGNAL_EXIT_CODES).toEqual({ + SIGINT: 130, + SIGTERM: 143, + SIGHUP: 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("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; + + expect(() => releaseConsoleStdin(stdin)).not.toThrow(); + 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(); + }); +}); + +class ProcessExitForTest extends Error { + constructor(readonly code: number) { + super(`process.exit(${code})`); + } +} + +describe("runAgentConsoleInk", () => { + const exitSpy = vi.spyOn(process, "exit").mockImplementation((code) => { + throw new ProcessExitForTest(typeof code === "number" ? code : 0); + }); + + beforeEach(() => { + exitSpy.mockClear(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + afterAll(() => { + exitSpy.mockRestore(); + }); + + 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(() => { + if (overrides?.onUnmount) { + overrides.onUnmount(resolveExit, rejectExit); + } else { + resolveExit(); + } + }); + const instance: Instance = { + rerender: vi.fn(), + unmount, + waitUntilExit, + waitUntilRenderFlush: vi.fn(), + cleanup: vi.fn(), + clear: vi.fn(), + }; + return { instance, resolveExit, rejectExit }; + } + + 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 { + SIGINT: process.listenerCount("SIGINT"), + SIGTERM: process.listenerCount("SIGTERM"), + SIGHUP: process.listenerCount("SIGHUP"), + }; + } + + 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(exitSpy).toHaveBeenCalledWith(0); + expect(listenerCounts()).toEqual(before); + }); + + 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); + + 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: () => {}, + }); + const renderInstance = vi.fn(() => instance); + + const running = runAgentConsoleInk({} as ReactElement, {}, { renderInstance }); + invokeLatestSignalHandler("SIGTERM"); + invokeLatestSignalHandler("SIGTERM"); + invokeLatestSignalHandler("SIGINT"); + resolveExit(); + + await expect(running).rejects.toMatchObject({ code: 143 }); + expect(instance.unmount).toHaveBeenCalledOnce(); + expect(exitSpy).toHaveBeenCalledWith(143); + expect(listenerCounts()).toEqual(before); + }); + + 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"); + + expect(instance.unmount).toHaveBeenCalledOnce(); + expect(exitSpy).toHaveBeenCalledWith(143); + expect(listenerCounts()).toEqual(before); + + resolveExit(); + await expect(running).rejects.toMatchObject({ code: 143 }); + }); + + it("force-exits when Ink teardown exceeds the watchdog budget", async () => { + vi.useFakeTimers(); + const before = listenerCounts(); + const { instance, resolveExit } = createMockInstance({ + onUnmount: () => {}, + }); + const renderInstance = vi.fn(() => instance); + + const running = runAgentConsoleInk( + {} as ReactElement, + {}, + { renderInstance, watchdogMs: CONSOLE_EXIT_WATCHDOG_MS }, + ); + invokeLatestSignalHandler("SIGINT"); + + await vi.advanceTimersByTimeAsync(CONSOLE_EXIT_WATCHDOG_MS - 1); + expect(exitSpy).not.toHaveBeenCalled(); + + await vi.advanceTimersByTimeAsync(1); + expect(instance.unmount).toHaveBeenCalledOnce(); + expect(exitSpy).toHaveBeenCalledWith(130); + expect(listenerCounts()).toEqual(before); + + resolveExit(); + await expect(running).rejects.toMatchObject({ code: 130 }); + }); +});