Skip to content
Draft
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
4 changes: 2 additions & 2 deletions docs/error-catalog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
95 changes: 95 additions & 0 deletions src/__tests__/wizard-abort.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -257,6 +261,97 @@ describe('runCleanups', () => {
});
});

describe('wizardCancel', () => {
let exit: MockInstance<typeof process.exit>;

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<void>(() => 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<void>(() => 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();
Expand Down
72 changes: 70 additions & 2 deletions src/lib/programs/__tests__/run-agent-legacy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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';

Expand Down Expand Up @@ -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<typeof process.exit>;

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<void>)();
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();
});
});
15 changes: 14 additions & 1 deletion src/lib/runners/run-non-interactive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -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({
Expand Down
58 changes: 8 additions & 50 deletions src/lib/runners/run-wizard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -77,8 +77,6 @@ export function runWizard(
): void {
let tui: ReturnType<typeof StartTUIFn> | null = null;
let taskStream: TaskStreamPushClass | null = null;
let onSignal: (() => void) | null = null;
let exitInProgress = false;

void (async () => {
try {
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand Down
Loading
Loading