Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs/ai/design/2026-11-18-fix-agent-console-exit.md
Original file line number Diff line number Diff line change
@@ -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.
12 changes: 12 additions & 0 deletions docs/ai/implementation/2026-11-18-fix-agent-console-exit.md
Original file line number Diff line number Diff line change
@@ -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).
6 changes: 6 additions & 0 deletions docs/ai/planning/2026-11-18-fix-agent-console-exit.md
Original file line number Diff line number Diff line change
@@ -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`).
12 changes: 12 additions & 0 deletions docs/ai/requirements/2026-11-18-fix-agent-console-exit.md
Original file line number Diff line number Diff line change
@@ -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.
17 changes: 17 additions & 0 deletions docs/ai/testing/2026-11-18-fix-agent-console-exit.md
Original file line number Diff line number Diff line change
@@ -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).
21 changes: 13 additions & 8 deletions packages/cli/src/commands/agent/console.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}),
);
}
105 changes: 105 additions & 0 deletions packages/cli/src/tui/console/runAgentConsole.ts
Original file line number Diff line number Diff line change
@@ -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<Record<NodeJS.Signals, number>>;

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<void> {
const instance = renderInstance(app, renderOptions);
let signalExitCode: number | undefined;
let watchdog: ReturnType<typeof setTimeout> | 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);
}
Loading
Loading