diff --git a/docs/error-catalog.md b/docs/error-catalog.md index c162e2897..9b3eff70f 100644 --- a/docs/error-catalog.md +++ b/docs/error-catalog.md @@ -153,8 +153,8 @@ signal is available. stderr code for the same session id. - **Decide:** use the catalog `retry` column for re-run policy; `no` codes need human/config intervention, `yes` codes are safe to retry after backoff. -- **Zero exit without a code** means success or a Ctrl-C style cancel (exit 130 - / user dismissal). +- **No code** means success (exit 0) or a cancel: exit 130 for Ctrl-C or + SIGINT, 143 for SIGTERM, 129 for SIGHUP. ## Extending the catalog diff --git a/src/__tests__/wizard-abort.test.ts b/src/__tests__/wizard-abort.test.ts index 923a53ac6..3c4175919 100644 --- a/src/__tests__/wizard-abort.test.ts +++ b/src/__tests__/wizard-abort.test.ts @@ -5,6 +5,10 @@ import { registerCleanup, clearCleanup, runCleanups, + wizardCancel, + registerCancelHook, + clearCancel, + installCancelSignals, } from '@utils/wizard-abort'; import { analytics } from '@utils/analytics'; import { ErrorCodes } from '@shared/errors'; @@ -257,6 +261,97 @@ describe('runCleanups', () => { }); }); +describe('wizardCancel', () => { + let exit: MockInstance; + + beforeEach(() => { + vi.clearAllMocks(); + clearCleanup(); + clearCancel(); + mockAnalytics.shutdown = vi.fn().mockResolvedValue(undefined); + exit = vi + .spyOn(process, 'exit') + .mockImplementation(() => undefined as never); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it('runs the cleanups, then the cancel hooks, then analytics, then exits 130', async () => { + const order: string[] = []; + registerCleanup(() => order.push('cleanup')); + registerCancelHook(async () => { + order.push('hook'); + }); + mockAnalytics.shutdown.mockImplementation(async (status) => { + order.push(`analytics:${status}`); + }); + exit.mockImplementation((() => order.push('exit')) as never); + + await wizardCancel('ctrl+c'); + + expect(order).toEqual(['cleanup', 'hook', 'analytics:cancelled', 'exit']); + expect(exit).toHaveBeenCalledExactlyOnceWith(130); + }); + + it.each([ + ['SIGINT', 130], + ['SIGTERM', 143], + ['SIGHUP', 129], + ] as const)( + 'exits %s as 128 plus the signal number', + async (signal, code) => { + await wizardCancel(signal); + expect(exit).toHaveBeenCalledExactlyOnceWith(code); + }, + ); + + it('exits at once on a second cancel while the first is settling', async () => { + registerCancelHook(() => new Promise(() => undefined)); + void wizardCancel('ctrl+c'); + await wizardCancel('ctrl+c'); + expect(exit).toHaveBeenCalledExactlyOnceWith(130); + }); + + it('exits when a cancel hook hangs or throws', async () => { + vi.useFakeTimers(); + registerCancelHook(() => new Promise(() => undefined)); + registerCancelHook(() => { + throw new Error('stream gone'); + }); + const cancelled = wizardCancel('SIGTERM'); + await vi.advanceTimersByTimeAsync(2000); + await cancelled; + expect(exit).toHaveBeenCalledExactlyOnceWith(143); + }); + + it('skips a hook whose remover ran', async () => { + const hook = vi.fn(); + registerCancelHook(hook)(); + await wizardCancel('ctrl+c'); + expect(hook).not.toHaveBeenCalled(); + }); +}); + +describe('installCancelSignals', () => { + afterEach(() => vi.restoreAllMocks()); + + it('routes SIGINT, SIGTERM and SIGHUP to one cancel, and removes them', () => { + const on = vi.spyOn(process, 'on').mockReturnValue(process); + const off = vi.spyOn(process, 'off').mockReturnValue(process); + const remove = installCancelSignals(); + expect(on.mock.calls.map(([signal]) => signal)).toEqual([ + 'SIGINT', + 'SIGTERM', + 'SIGHUP', + ]); + remove(); + expect(off.mock.calls).toEqual(on.mock.calls); + }); +}); + describe('abort() delegates to wizardAbort()', () => { beforeEach(() => { vi.clearAllMocks(); diff --git a/src/lib/programs/__tests__/run-agent-legacy.test.ts b/src/lib/programs/__tests__/run-agent-legacy.test.ts index 1e2703d16..ef71ea3b7 100644 --- a/src/lib/programs/__tests__/run-agent-legacy.test.ts +++ b/src/lib/programs/__tests__/run-agent-legacy.test.ts @@ -4,7 +4,7 @@ import { authenticate } from '@lib/programs/authenticate'; import { runProgramAgent } from '../run-agent-legacy'; import { runAgent, RunOutcome, type RunResult } from '@agent/runner'; import { Harness, Sequence } from '@shared/constants'; -import { buildSession, OutroKind } from '@lib/wizard-session'; +import { buildSession, OutroKind, RunPhase } from '@lib/wizard-session'; import { HostResolution } from '@shared/host-resolution'; import { LoggingUI } from '@ui/logging-ui'; import { InkUI } from '@ui/tui/ink-ui'; @@ -13,7 +13,7 @@ import { WizardStore } from '@ui/tui/store'; import { getUI, setUI } from '@ui'; import { analytics } from '@utils/analytics'; import { initLogFile, logToFile } from '@utils/debug'; -import { wizardAbort } from '@utils/wizard-abort'; +import { clearCancel, wizardAbort, wizardCancel } from '@utils/wizard-abort'; import { ErrorCodes } from '@shared/errors'; import type { ProgramConfig } from '../program-step'; @@ -408,3 +408,71 @@ it('keeps a TUI run a success when its terminal analytics flush fails', async () ); exit.mockRestore(); }); + +describe('a cancel mid-run', () => { + let exit: MockInstance; + + beforeEach(() => { + clearCancel(); + exit = vi + .spyOn(process, 'exit') + .mockImplementation(() => undefined as never); + }); + afterEach(() => exit.mockRestore()); + + it('ends a TUI run as an error and settles its stream before exiting', async () => { + const store = new WizardStore('metrics'); + setUI(new InkUI(store)); + vi.spyOn(store, 'runReadyHooks').mockResolvedValue(undefined); + vi.spyOn(store, 'getGate').mockResolvedValue(undefined); + vi.mocked(startTUI).mockReturnValue({ + store, + unmount: vi.fn(), + waitForSetup: () => Promise.resolve(), + }); + let phaseAtExit: RunPhase | undefined; + exit.mockImplementation((() => { + phaseAtExit = store.session.runPhase; + }) as never); + vi.mocked(runAgent).mockImplementation(async (...args) => { + store.setRunPhase(RunPhase.Running); + await wizardCancel('ctrl+c'); + return finishRun(...args); + }); + + runWizard(program(), { installDir: '/tmp/adapter-test', telemetry: false }); + + await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(130)); + expect(phaseAtExit).toBe(RunPhase.Error); + expect(streamShutdown.mock.invocationCallOrder[0]).toBeLessThan( + exit.mock.invocationCallOrder[0], + ); + expect(analytics.shutdown).toHaveBeenCalledWith('cancelled'); + }); + + it('settles a headless stream and exits 143 on SIGTERM', async () => { + const on = vi.spyOn(process, 'on'); + vi.mocked(runAgent).mockImplementation(async (...args) => { + const sigterm = on.mock.calls.find(([event]) => event === 'SIGTERM'); + await (sigterm?.[1] as () => Promise)(); + return finishRun(...args); + }); + + runNonInteractive( + program(), + { + apiKey: 'phx_test', + projectId: '1', + installDir: '/tmp/adapter-test', + telemetry: false, + }, + 'headless', + ); + + await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(143)); + expect(streamShutdown.mock.invocationCallOrder[0]).toBeLessThan( + exit.mock.invocationCallOrder[0], + ); + on.mockRestore(); + }); +}); diff --git a/src/lib/runners/run-non-interactive.ts b/src/lib/runners/run-non-interactive.ts index 6977ae5f9..836582574 100644 --- a/src/lib/runners/run-non-interactive.ts +++ b/src/lib/runners/run-non-interactive.ts @@ -115,7 +115,12 @@ export function runNonInteractive( const { configureLogFileFromEnvironment, logToFile } = await import( '@utils/debug' ); - const { wizardAbort, WizardError } = await import('@utils/wizard-abort'); + const { + installCancelSignals, + registerCancelHook, + wizardAbort, + WizardError, + } = await import('@utils/wizard-abort'); configureLogFileFromEnvironment(); @@ -240,6 +245,11 @@ export function runNonInteractive( await taskStream.shutdown(2000); }; + const removeCancelSignals = installCancelSignals(); + const removeCancelHook = registerCancelHook(() => + settleStream(RunPhase.Error), + ); + try { if (mode === 'ci') { const { configureGatewayFromCIEnvironment } = await import('@agent'); @@ -371,6 +381,9 @@ export function runNonInteractive( : `Something went wrong: ${errorMessage}\n\nYou can read the documentation at ${docsUrl} to set up manually.${debugInfo}`, error: error as Error, }); + } finally { + removeCancelSignals(); + removeCancelHook(); } })().catch((error: unknown) => { emitWizardError({ diff --git a/src/lib/runners/run-wizard.ts b/src/lib/runners/run-wizard.ts index a3eaa8f5c..b56ead1dd 100644 --- a/src/lib/runners/run-wizard.ts +++ b/src/lib/runners/run-wizard.ts @@ -13,7 +13,7 @@ import { OutroKind, type WizardSession } from '@lib/wizard-session'; import type { TaskStreamPush as TaskStreamPushClass } from '@lib/task-stream/task-stream-push'; import { resolveNoTelemetry } from './resolve-no-telemetry'; import { checkLocalServices, getLocalDev } from '@shared/local-dev'; -import { runCleanups } from '@utils/wizard-abort'; +import { registerCancelHook, runCleanups } from '@utils/wizard-abort'; import { classifyRunFailure, emitWizardError } from '@shared/errors'; import { isRunFailure } from '@ui/mint-failure'; import { getUI } from '@ui'; @@ -77,8 +77,6 @@ export function runWizard( ): void { let tui: ReturnType | null = null; let taskStream: TaskStreamPushClass | null = null; - let onSignal: (() => void) | null = null; - let exitInProgress = false; void (async () => { try { @@ -144,45 +142,6 @@ export function runWizard( activeTui.store.session = session; - // Flush a terminal-phase push on Ctrl-C so the web app sees the - // run ended in error rather than hanging on the last "running" - // snapshot. Registered before the stream exists: Ctrl-C on the intro - // must still restore the terminal and run the cleanups, and there is - // no run to report yet. - let signalled = false; - onSignal = (): void => { - if (signalled || exitInProgress) return; - signalled = true; - logToFile('[run-wizard] signal received, flushing task stream'); - // Run cleanups synchronously first — settings restore is sync fs work - // and must complete even if the stream shutdown below times out. - runCleanups(); - if (activeTui.store.session.runPhase === RunPhase.Running) { - activeTui.store.setRunPhase(RunPhase.Error); - } - const teardown = (): void => { - try { - activeTui.unmount(); - } catch { - // terminal may already be torn down - } - process.exit(130); - }; - const stream = taskStream; - if (!stream) { - teardown(); - return; - } - void stream - .shutdown(2000) - .catch((e) => - logToFile('[run-wizard] task stream shutdown error on signal:', e), - ) - .finally(teardown); - }; - process.on('SIGINT', onSignal); - process.on('SIGTERM', onSignal); - for (;;) { await activeTui.store.runReadyHooks(); // Settle the pre-run screens; `integration-check` is a no-op gate here. @@ -226,6 +185,13 @@ export function runWizard( }); taskStream = activeStream; activeStream.attach(); + // On a cancel, end the run as an error so the web app stops showing it running. + registerCancelHook(async () => { + if (activeTui.store.session.runPhase === RunPhase.Running) { + activeTui.store.setRunPhase(RunPhase.Error); + } + await activeStream.shutdown(2000); + }); await activeTui.store.getGate('integration-check'); await activeTui.store.getGate('health-check'); @@ -288,10 +254,7 @@ export function runWizard( return s.skillsComplete; }); - exitInProgress = true; await activeStream.shutdown(2000); - process.off('SIGINT', onSignal); - process.off('SIGTERM', onSignal); if (runFailed) await analytics.shutdown('error'); activeTui.unmount(); process.exit(runFailed ? 1 : 0); @@ -303,11 +266,6 @@ export function runWizard( runCleanups(); // The task-stream debounce timer keeps the event loop alive, so // we have to drain it before exiting on the error path. - exitInProgress = true; - if (onSignal) { - process.off('SIGINT', onSignal); - process.off('SIGTERM', onSignal); - } if (taskStream) { try { await taskStream.shutdown(2000); diff --git a/src/shared/utils/wizard-abort.ts b/src/shared/utils/wizard-abort.ts index 0a2b8ae30..29f179769 100644 --- a/src/shared/utils/wizard-abort.ts +++ b/src/shared/utils/wizard-abort.ts @@ -3,9 +3,12 @@ * * Sequence: cleanup -> error capture (optional) -> analytics shutdown -> outro -> process.exit * + * A user cancel (ctrl+c, SIGINT, SIGTERM, SIGHUP) exits through `wizardCancel`, with no outro. + * * WizardError (from `@lib/errors`) is a data carrier passed to wizardAbort() for analytics context, never thrown. * The legacy abort() in setup-utils.ts delegates here. */ +import { constants } from 'os'; import { analytics } from './analytics'; import { logToFile } from './debug'; import { getUI } from '@ui'; @@ -55,6 +58,76 @@ export function runCleanups(): void { } } +const CANCEL_SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const; +type CancelSignal = (typeof CANCEL_SIGNALS)[number]; +/** Upper bound on the cancel hooks and the analytics flush, each. */ +const CANCEL_STEP_TIMEOUT_MS = 2000; + +const cancelHooks: Array<() => Promise | void> = []; +let cancelling = false; + +/** Async teardown that only a cancel runs, such as settling a task stream. Returns the remover. */ +export function registerCancelHook(fn: () => Promise | void): () => void { + cancelHooks.push(fn); + return () => { + const index = cancelHooks.indexOf(fn); + if (index >= 0) cancelHooks.splice(index, 1); + }; +} + +export function clearCancel(): void { + cancelHooks.length = 0; + cancelling = false; +} + +const settleWithin = (work: Promise, ms: number): Promise => + new Promise((resolve) => { + const timer = setTimeout(resolve, ms); + void work + .catch(() => undefined) + .finally(() => { + clearTimeout(timer); + resolve(); + }); + }); + +/** The one exit for ctrl+c, SIGINT, SIGTERM and SIGHUP. A second cancel exits at once. */ +export async function wizardCancel( + source: CancelSignal | 'ctrl+c', +): Promise { + // The key is a SIGINT the terminal never sent, so it exits like one: 130. + const signal = source === 'ctrl+c' ? 'SIGINT' : source; + const exitCode = 128 + constants.signals[signal]; + if (cancelling) { + logToFile(`[wizard-cancel] ${source} again, exiting now`); + return process.exit(exitCode); + } + cancelling = true; + logToFile(`[wizard-cancel] ${source}, cancelling`); + + // Sync first: a settings restore must not wait on the network. + runCleanups(); + const hooks = cancelHooks.splice(0); + await settleWithin( + Promise.allSettled(hooks.map((hook) => Promise.resolve().then(hook))), + CANCEL_STEP_TIMEOUT_MS, + ); + await settleWithin(analytics.shutdown('cancelled'), CANCEL_STEP_TIMEOUT_MS); + return process.exit(exitCode); +} + +/** Routes SIGINT, SIGTERM and SIGHUP to `wizardCancel`. Returns the remover. */ +export function installCancelSignals(): () => void { + const handlers = CANCEL_SIGNALS.map((signal) => { + const handler = () => void wizardCancel(signal); + process.on(signal, handler); + return { signal, handler }; + }); + return () => { + for (const { signal, handler } of handlers) process.off(signal, handler); + }; +} + function resolveErrorCode( options: WizardAbortOptions, error: Error | WizardError | undefined, diff --git a/src/ui/tui/__tests__/ctrl-c-cancel.test.tsx b/src/ui/tui/__tests__/ctrl-c-cancel.test.tsx new file mode 100644 index 000000000..13ba1cf8b --- /dev/null +++ b/src/ui/tui/__tests__/ctrl-c-cancel.test.tsx @@ -0,0 +1,35 @@ +import { vi, it, expect, beforeEach, afterEach } from 'vitest'; +import { render, cleanup } from 'ink-testing-library'; +import { WizardStore, Program } from '../store'; +import { ScreenContainer } from '../primitives/ScreenContainer'; +import { wizardCancel } from '@utils/wizard-abort'; + +vi.mock('ink', () => + vi.importActual('../../../../node_modules/ink/build/index.js'), +); +vi.mock('@utils/wizard-abort', async (original) => ({ + ...(await original()), + wizardCancel: vi.fn(), +})); + +beforeEach(() => vi.clearAllMocks()); +afterEach(() => cleanup()); + +const press = async (input: string) => { + const { stdin } = render( + , + ); + // Let ink attach its stdin listener before writing. + await new Promise((resolve) => setTimeout(resolve, 0)); + stdin.write(input); +}; + +it('cancels the wizard on the ctrl+c key, like a SIGINT', async () => { + await press('\x03'); + expect(wizardCancel).toHaveBeenCalledExactlyOnceWith('ctrl+c'); +}); + +it('leaves a plain c alone', async () => { + await press('c'); + expect(wizardCancel).not.toHaveBeenCalled(); +}); diff --git a/src/ui/tui/__tests__/start-tui.test.ts b/src/ui/tui/__tests__/start-tui.test.ts new file mode 100644 index 000000000..d5cf8b9f1 --- /dev/null +++ b/src/ui/tui/__tests__/start-tui.test.ts @@ -0,0 +1,34 @@ +import { render } from 'ink'; +import { startTUI } from '../start-tui'; +import { installCancelSignals } from '@utils/wizard-abort'; + +vi.mock('ink', async (original) => ({ + ...(await original()), + render: vi.fn(() => ({ + unmount: vi.fn(), + waitUntilExit: () => new Promise(() => undefined), + })), +})); +vi.mock('../App.js', () => ({ App: () => null })); +vi.mock('../terminal.js', () => ({ + enterDarkTerminal: vi.fn(), + releaseTerminal: vi.fn(), +})); +vi.mock('@utils/debug'); +vi.mock('@utils/analytics', () => ({ + analytics: { setTag: vi.fn(), wizardCapture: vi.fn() }, +})); +vi.mock('@utils/wizard-abort', async (original) => ({ + ...(await original()), + installCancelSignals: vi.fn(), +})); + +it('hands ctrl+c and the cancel signals to wizardCancel, not to ink', () => { + const on = vi.spyOn(process, 'on').mockReturnValue(process); + startTUI('0.0.0'); + expect(render).toHaveBeenCalledWith(expect.anything(), { + exitOnCtrlC: false, + }); + expect(installCancelSignals).toHaveBeenCalledOnce(); + on.mockRestore(); +}); diff --git a/src/ui/tui/primitives/ScreenContainer.tsx b/src/ui/tui/primitives/ScreenContainer.tsx index afc385c9b..9fc3c3fb4 100644 --- a/src/ui/tui/primitives/ScreenContainer.tsx +++ b/src/ui/tui/primitives/ScreenContainer.tsx @@ -22,11 +22,9 @@ import { KeyboardHintsProvider } from '@ui/tui/hooks/useKeyboardHints'; import { DissolveTransition } from './DissolveTransition.js'; import { KeyboardHintsBar } from './KeyboardHintsBar.js'; import { ScreenErrorBoundary } from './ScreenErrorBoundary.js'; -import { - ViewportTooSmall, - isViewportTooSmall, -} from './ViewportTooSmall.js'; +import { ViewportTooSmall, isViewportTooSmall } from './ViewportTooSmall.js'; import type { WizardStore } from '@ui/tui/store'; +import { wizardCancel } from '@utils/wizard-abort'; const MIN_WIDTH = 80; export const MAX_WIDTH = 120; @@ -56,6 +54,8 @@ export const ScreenContainer = ({ store, screens }: ScreenContainerProps) => { // ScreenContainer is the one component alive for the whole process. useInput((input, key) => { if (key.ctrl && input === 't') store.toggleTokenHud(); + // Raw mode delivers ctrl+c as a key, not a SIGINT: cancel the same way. + if (key.ctrl && input === 'c') void wizardCancel('ctrl+c'); }); const terminalWidth = columns; @@ -88,8 +88,7 @@ export const ScreenContainer = ({ store, screens }: ScreenContainerProps) => { // Only enforced on a real terminal: with stdout piped there are no // dimensions to read (useStdoutDimensions substitutes 80×24) and no window // for anyone to resize, so nagging would be both wrong and unactionable. - const tooSmall = - Boolean(stdout.isTTY) && isViewportTooSmall(columns, rows); + const tooSmall = Boolean(stdout.isTTY) && isViewportTooSmall(columns, rows); const inner = ( { - // `cleaned` still false here means Ink tore itself down (ctrl+c) rather - // than a runner-driven exit — flush the terminal analytics event before - // the process dies, or interrupted runs vanish from the funnel entirely. - // shutdown() is a no-op when a runner already reported a real status. - const interrupted = !cleaned; + // Unmounting alone doesn't end the process — background handles (e.g. the + // OAuth callback server) keep the event loop alive, leaving a zombie wizard + // with no UI. Follow the app teardown with a real exit. + void waitUntilExit().then(() => { cleanup(); - if (interrupted) { - try { - await analytics.shutdown('cancelled'); - } catch { - /* never block exit on a flush failure */ - } - } process.exit(process.exitCode ?? 0); });