Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): make Ctrl+C exit the dev TUI quickly and safely (#1142)

Chad Hietala5cf8ae0a2144
diff --git a/.changeset/tidy-badgers-stop.md b/.changeset/tidy-badgers-stop.md
new file mode 100644
index 000000000..6bb52faa0
--- /dev/null
+++ b/.changeset/tidy-badgers-stop.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Make `eve dev` return the terminal after one Ctrl+C or termination signal. The local server gets a bounded cleanup window before process-group termination, and interrupted sandbox cleanup resumes on the next start. A forced exit (second Ctrl+C or the shutdown backstop) now restores the terminal — raw mode, cursor, bracketed paste — before the process ends.
diff --git a/packages/eve/src/cli/dev/local-server-child.ts b/packages/eve/src/cli/dev/local-server-child.ts
new file mode 100644
index 000000000..193f9c81b
--- /dev/null
+++ b/packages/eve/src/cli/dev/local-server-child.ts
@@ -0,0 +1,70 @@
+import { createDevelopmentServer } from "#internal/nitro/host.js";
+import type { DevelopmentServerOptions } from "#internal/nitro/host/types.js";
+import { getDevelopmentSandboxRunId } from "#execution/sandbox/development-run.js";
+import { reconcileCleanupIntents, recordCleanupIntent } from "#cli/dev/local-server-cleanup.js";
+
+const options = JSON.parse(process.argv[2] ?? "{}") as Pick<
+ DevelopmentServerOptions,
+ "existing" | "host" | "port"
+>;
+const server = createDevelopmentServer(process.cwd(), {
+ ...options,
+ onBootProgress: (event) => send({ type: "progress", event }),
+});
+let stopping = false;
+let removeCleanupIntent: (() => Promise<void>) | undefined;
+void reconcileCleanupIntents(process.cwd()).catch(() => undefined);
+
+const send = (message: unknown) => {
+ try {
+ if (process.connected) process.send?.(message, () => {});
+ } catch {}
+};
+
+const stop = () => {
+ if (stopping) return;
+ stopping = true;
+ console.log = console.warn = console.error = () => {};
+ process.stdout.on("error", () => {});
+ process.stderr.on("error", () => {});
+ const cleanup = server.close();
+ if (process.connected) process.disconnect?.();
+ void cleanup.then(
+ async () => {
+ await intentReady.catch(() => undefined);
+ await removeCleanupIntent?.().catch(() => undefined);
+ process.exit(0);
+ },
+ () => process.exit(1),
+ );
+};
+
+process.on("message", (message: { type?: string }) => {
+ if (message.type === "shutdown") stop();
+});
+// IPC disconnect is the parent-death signal: it fires however the parent
+// exits (including SIGKILL), which no portable OS mechanism covers.
+process.once("disconnect", stop);
+process.once("SIGINT", stop);
+process.once("SIGTERM", stop);
+
+const intentReady = server.start().then(
+ async (handle) => {
+ const runId = getDevelopmentSandboxRunId();
+ if (handle.kind === "started" && runId !== undefined) {
+ removeCleanupIntent = await recordCleanupIntent(process.cwd(), {
+ ownerPid: process.pid,
+ runId,
+ });
+ }
+ send({ type: "started", handle });
+ if (handle.kind === "existing" && process.connected) process.disconnect?.();
+ },
+ (error: unknown) => {
+ const value = error instanceof Error ? error : new Error(String(error));
+ send({ type: "failed", message: value.message, stack: value.stack });
+ process.exitCode = 1;
+ if (process.connected) process.disconnect?.();
+ },
+);
+void intentReady;
diff --git a/packages/eve/src/cli/dev/local-server-cleanup.test.ts b/packages/eve/src/cli/dev/local-server-cleanup.test.ts
new file mode 100644
index 000000000..f22d5880f
--- /dev/null
+++ b/packages/eve/src/cli/dev/local-server-cleanup.test.ts
@@ -0,0 +1,64 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { reconcileCleanupIntents, recordCleanupIntent } from "#cli/dev/local-server-cleanup.js";
+
+const mocks = vi.hoisted(() => ({
+ mkdir: vi.fn(async () => undefined),
+ readFile: vi.fn(async () => '{"ownerPid":123,"runId":"stale-run"}\n'),
+ readdir: vi.fn(async () => ["dev-cleanup-intent.stale-run.json"]),
+ rm: vi.fn(async () => undefined),
+ stop: vi.fn(async () => undefined),
+ writeFile: vi.fn(async () => undefined),
+}));
+
+vi.mock("node:fs/promises", () => ({
+ mkdir: mocks.mkdir,
+ readFile: mocks.readFile,
+ readdir: mocks.readdir,
+ rm: mocks.rm,
+ writeFile: mocks.writeFile,
+}));
+vi.mock("#execution/sandbox/bindings/local.js", () => ({
+ stopDevelopmentSandboxResources: mocks.stop,
+}));
+
+describe("local server cleanup intents", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("records and removes the current run intent", async () => {
+ const remove = await recordCleanupIntent("/tmp/app", { ownerPid: 123, runId: "run-1" });
+ expect(mocks.writeFile).toHaveBeenCalledWith(
+ "/tmp/app/.eve/dev-cleanup-intent.run-1.json",
+ '{"ownerPid":123,"runId":"run-1"}\n',
+ "utf8",
+ );
+ await remove();
+ expect(mocks.rm).toHaveBeenCalled();
+ });
+
+ it("reconciles stale run intents", async () => {
+ const kill = vi.spyOn(process, "kill").mockImplementation(() => {
+ throw Object.assign(new Error("missing"), { code: "ESRCH" });
+ });
+ try {
+ await reconcileCleanupIntents("/tmp/app");
+ expect(mocks.stop).toHaveBeenCalledWith({ appRoot: "/tmp/app", devRunId: "stale-run" });
+ expect(mocks.rm).toHaveBeenCalled();
+ } finally {
+ kill.mockRestore();
+ }
+ });
+
+ it("leaves intents owned by live instances untouched", async () => {
+ const kill = vi.spyOn(process, "kill").mockReturnValue(true);
+ try {
+ await reconcileCleanupIntents("/tmp/app");
+ expect(mocks.stop).not.toHaveBeenCalled();
+ expect(mocks.rm).not.toHaveBeenCalled();
+ } finally {
+ kill.mockRestore();
+ }
+ });
+});
diff --git a/packages/eve/src/cli/dev/local-server-cleanup.ts b/packages/eve/src/cli/dev/local-server-cleanup.ts
new file mode 100644
index 000000000..5abb4f203
--- /dev/null
+++ b/packages/eve/src/cli/dev/local-server-cleanup.ts
@@ -0,0 +1,62 @@
+import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { stopDevelopmentSandboxResources } from "#execution/sandbox/bindings/local.js";
+
+const PREFIX = "dev-cleanup-intent.";
+const SUFFIX = ".json";
+
+export async function recordCleanupIntent(
+ appRoot: string,
+ input: { readonly ownerPid: number; readonly runId: string },
+): Promise<() => Promise<void>> {
+ const directory = join(appRoot, ".eve");
+ const path = join(directory, `${PREFIX}${input.runId}${SUFFIX}`);
+ await mkdir(directory, { recursive: true });
+ await writeFile(path, `${JSON.stringify(input)}\n`, "utf8");
+ return async () => await rm(path, { force: true });
+}
+
+export async function reconcileCleanupIntents(appRoot: string): Promise<void> {
+ const directory = join(appRoot, ".eve");
+ let names: string[];
+ try {
+ names = await readdir(directory);
+ } catch (error) {
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return;
+ throw error;
+ }
+ await Promise.all(
+ names
+ .filter((name) => name.startsWith(PREFIX) && name.endsWith(SUFFIX))
+ .map(async (name) => {
+ try {
+ const path = join(directory, name);
+ const value = JSON.parse(await readFile(path, "utf8")) as {
+ ownerPid?: unknown;
+ runId?: unknown;
+ };
+ if (
+ typeof value.runId !== "string" ||
+ typeof value.ownerPid !== "number" ||
+ !Number.isInteger(value.ownerPid) ||
+ value.ownerPid <= 0 ||
+ isProcessAlive(value.ownerPid)
+ ) {
+ return;
+ }
+ await stopDevelopmentSandboxResources({ appRoot, devRunId: value.runId });
+ await rm(path, { force: true });
+ } catch {}
+ }),
+ );
+}
+
+function isProcessAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return error instanceof Error && "code" in error && error.code === "EPERM";
+ }
+}
diff --git a/packages/eve/src/cli/dev/local-server-process.test.ts b/packages/eve/src/cli/dev/local-server-process.test.ts
new file mode 100644
index 000000000..4fdc77d37
--- /dev/null
+++ b/packages/eve/src/cli/dev/local-server-process.test.ts
@@ -0,0 +1,81 @@
+import { EventEmitter } from "node:events";
+import { PassThrough } from "node:stream";
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ createDevelopmentServer,
+ DEV_SERVER_CLOSE_BUDGET_MS,
+} from "#cli/dev/local-server-process.js";
+import { FORCED_EXIT_BACKSTOP_MS } from "#cli/shutdown.js";
+
+const mocks = vi.hoisted(() => ({ fork: vi.fn(), loadEnv: vi.fn() }));
+vi.mock("node:child_process", () => ({ fork: mocks.fork }));
+vi.mock("#cli/dev/environment.js", () => ({ loadDevelopmentEnvironmentFiles: mocks.loadEnv }));
+
+class FakeChild extends EventEmitter {
+ connected = true;
+ readonly stdout = new PassThrough();
+ readonly stderr = new PassThrough();
+ readonly send = vi.fn();
+ readonly kill = vi.fn();
+ readonly disconnect = vi.fn(() => {
+ this.connected = false;
+ });
+ readonly unref = vi.fn();
+}
+
+describe("createDevelopmentServer", () => {
+ let child: FakeChild;
+
+ beforeEach(() => {
+ child = new FakeChild();
+ mocks.fork.mockReturnValue(child);
+ });
+
+ it("finishes the close escalation inside the CLI forced-exit backstop", () => {
+ expect(DEV_SERVER_CLOSE_BUDGET_MS).toBeLessThan(FORCED_EXIT_BACKSTOP_MS);
+ });
+
+ it("starts and hands cleanup to the child", async () => {
+ const server = createDevelopmentServer("/tmp/app", { port: 2000 });
+ const started = server.start();
+ child.emit("message", {
+ type: "started",
+ handle: { kind: "started", appRoot: "/tmp/app", url: "http://127.0.0.1:2000" },
+ });
+ await started;
+
+ const closing = server.close();
+ expect(child.send).toHaveBeenCalledWith({ type: "shutdown" });
+ child.emit("exit", 0, null);
+
+ await closing;
+ expect(child.unref).toHaveBeenCalledOnce();
+ });
+
+ it("escalates when graceful cleanup misses the deadline", async () => {
+ vi.useFakeTimers();
+ try {
+ const server = createDevelopmentServer("/tmp/app");
+ const started = server.start();
+ child.emit("message", {
+ type: "started",
+ handle: { kind: "started", appRoot: "/tmp/app", url: "http://127.0.0.1:2000" },
+ });
+ await started;
+
+ const closing = server.close();
+ await vi.advanceTimersByTimeAsync(550);
+ expect(child.kill).toHaveBeenCalledWith("SIGTERM");
+ await vi.advanceTimersByTimeAsync(150);
+ expect(child.kill).toHaveBeenCalledWith("SIGKILL");
+ child.emit("exit", null, "SIGKILL");
+
+ await closing;
+ expect(child.unref).toHaveBeenCalledOnce();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/packages/eve/src/cli/dev/local-server-process.ts b/packages/eve/src/cli/dev/local-server-process.ts
new file mode 100644
index 000000000..47511e872
--- /dev/null
+++ b/packages/eve/src/cli/dev/local-server-process.ts
@@ -0,0 +1,196 @@
+/**
+ * The `eve dev` server child: forked `detached` (its own process group) and
+ * bound to the CLI's lifetime through the IPC channel, never through the OS.
+ *
+ * Why the child is not bound to the parent at the OS level (shared process
+ * group, inherited terminal signals):
+ *
+ * - The TUI puts stdin in raw mode, which disables ISIG: Ctrl+C never becomes
+ * a terminal-generated SIGINT, so same-group signal delivery does nothing in
+ * the mode where Ctrl+C matters most.
+ * - In headless mode, same-group delivery would signal parent and child
+ * simultaneously, racing the parent's graceful IPC shutdown against the
+ * child's own signal handler.
+ * - macOS has no parent-death signal. IPC `disconnect` is the portable
+ * equivalent: the child self-stops whenever this process exits, for any
+ * reason including SIGKILL (see local-server-child.ts).
+ *
+ * `detached` makes the child a process-group leader, so close() can escalate
+ * to a group-wide SIGTERM/SIGKILL that reaps the entire server tree. Sandbox
+ * resources leaked by a crash are reconciled by the cleanup-intent janitor on
+ * the next run (see local-server-cleanup.ts).
+ */
+
+import { fork, type ChildProcess } from "node:child_process";
+import { fileURLToPath } from "node:url";
+
+import { loadDevelopmentEnvironmentFiles } from "#cli/dev/environment.js";
+import { EVE_DEV_ENV_FLAG } from "#internal/application/optional-package-install.js";
+import type {
+ DevelopmentServer,
+ DevelopmentServerHandle,
+ DevelopmentServerOptions,
+} from "#internal/nitro/host/types.js";
+
+type ChildMessage =
+ | {
+ type: "progress";
+ event: Parameters<NonNullable<DevelopmentServerOptions["onBootProgress"]>>[0];
+ }
+ | { type: "started"; handle: DevelopmentServerHandle }
+ | { type: "failed"; message: string; stack?: string };
+
+const childPath = fileURLToPath(new URL("./local-server-child.js", import.meta.url));
+
+// close() escalation stages. Their sum is DEV_SERVER_CLOSE_BUDGET_MS.
+const IPC_SHUTDOWN_GRACE_MS = 550;
+const SIGTERM_GRACE_MS = 150;
+const SIGKILL_REAP_MS = 100;
+
+/**
+ * Worst-case close() duration. Must stay below the forced-exit backstop the
+ * dev command arms on its lifecycle (FORCED_EXIT_BACKSTOP_MS in
+ * `#cli/shutdown.js`), so a graceful close always beats the backstop and
+ * `eve dev` exits 0 after Ctrl+C. Enforced by local-server-process.test.ts.
+ */
+export const DEV_SERVER_CLOSE_BUDGET_MS =
+ IPC_SHUTDOWN_GRACE_MS + SIGTERM_GRACE_MS + SIGKILL_REAP_MS;
+
+export interface DevelopmentServerProcess extends DevelopmentServer {
+ wait(): Promise<void>;
+}
+
+/** Runs the CLI-owned local server outside the foreground TUI process. */
+export function createDevelopmentServer(
+ appRoot: string,
+ options: DevelopmentServerOptions = {},
+): DevelopmentServerProcess {
+ let child: ChildProcess | undefined;
+ let handoff: Promise<void> | undefined;
+ let expectedExit = false;
+ const exited = Promise.withResolvers<void>();
+ const terminated = Promise.withResolvers<void>();
+ void exited.promise.catch(() => undefined);
+
+ const release = () => {
+ const active = child;
+ if (active === undefined) return;
+ child = undefined;
+ active.stdout?.destroy();
+ active.stderr?.destroy();
+ if (active.connected) active.disconnect();
+ active.unref();
+ };
+
+ const start = (): Promise<DevelopmentServerHandle> => {
+ if (child !== undefined) throw new Error("DevelopmentServer.start() was already called.");
+ const shellEnvironment = { ...process.env };
+ loadDevelopmentEnvironmentFiles(appRoot);
+ process.env[EVE_DEV_ENV_FLAG] ??= "1";
+ const spawned = fork(
+ childPath,
+ [
+ JSON.stringify({
+ existing: options.existing,
+ host: options.host,
+ port: options.port,
+ }),
+ ],
+ {
+ cwd: appRoot,
+ detached: true,
+ env: { ...shellEnvironment, [EVE_DEV_ENV_FLAG]: "1" },
+ stdio: ["ignore", "pipe", "pipe", "ipc"],
+ },
+ );
+ child = spawned;
+ spawned.stdout?.on("data", (chunk: Buffer) => process.stdout.write(chunk));
+ spawned.stderr?.on("data", (chunk: Buffer) => process.stderr.write(chunk));
+
+ return new Promise<DevelopmentServerHandle>((resolve, reject) => {
+ let settled = false;
+ spawned.once("error", reject);
+ spawned.once("exit", (code, signal) => {
+ terminated.resolve();
+ release();
+ if (!settled) {
+ reject(
+ new Error(
+ `Development server exited during startup (${String(code)}, ${String(signal)}).`,
+ ),
+ );
+ } else if (expectedExit) {
+ exited.resolve();
+ } else {
+ exited.reject(
+ new Error(
+ `Development server exited unexpectedly (${String(code)}, ${String(signal)}).`,
+ ),
+ );
+ }
+ });
+ spawned.on("message", (message: ChildMessage) => {
+ if (message.type === "progress") options.onBootProgress?.(message.event);
+ if (message.type === "started" && !settled) {
+ settled = true;
+ resolve(message.handle);
+ if (message.handle.kind === "existing") {
+ expectedExit = true;
+ release();
+ }
+ }
+ if (message.type === "failed" && !settled) {
+ settled = true;
+ const error = new Error(message.message);
+ if (message.stack !== undefined) error.stack = message.stack;
+ reject(error);
+ }
+ });
+ });
+ };
+
+ return {
+ start,
+ close() {
+ if (handoff !== undefined) return handoff;
+ const active = child;
+ if (active === undefined) return Promise.resolve();
+ expectedExit = true;
+ handoff = (async () => {
+ if (active.connected) active.send({ type: "shutdown" });
+ if (await settlesWithin(terminated.promise, IPC_SHUTDOWN_GRACE_MS)) return;
+ signalProcessGroup(active, "SIGTERM");
+ if (await settlesWithin(terminated.promise, SIGTERM_GRACE_MS)) return;
+ signalProcessGroup(active, "SIGKILL");
+ await settlesWithin(terminated.promise, SIGKILL_REAP_MS);
+ release();
+ })();
+ return handoff;
+ },
+ wait: () => exited.promise,
+ };
+}
+
+async function settlesWithin(operation: Promise<void>, ms: number): Promise<boolean> {
+ let timer: NodeJS.Timeout | undefined;
+ try {
+ return await Promise.race([
+ operation.then(() => true),
+ new Promise<false>((resolve) => {
+ timer = setTimeout(() => resolve(false), ms);
+ }),
+ ]);
+ } finally {
+ if (timer !== undefined) clearTimeout(timer);
+ }
+}
+
+function signalProcessGroup(child: ChildProcess, signal: NodeJS.Signals): void {
+ if (process.platform !== "win32" && child.pid !== undefined) {
+ try {
+ process.kill(-child.pid, signal);
+ return;
+ } catch {}
+ }
+ child.kill(signal);
+}
diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.ts
index 7971c7d9b..2a82253fc 100644
--- a/packages/eve/src/cli/dev/tui/runner.test.ts
+++ b/packages/eve/src/cli/dev/tui/runner.test.ts
@@ -3040,3 +3040,36 @@ describe("EveTUIRunner cancelled-turn subagent settling", () => {
expect(view.complete).toHaveBeenCalledWith({ callId: "call-1" });
});
});
+
+describe("EveTUIRunner command shutdown", () => {
+ it("unwinds a blocked prompt", async () => {
+ const client = stubClient();
+ vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);
+ const prompt = createDeferred<string | undefined>();
+ const controller = new AbortController();
+ const renderer: AgentTUIRenderer = {
+ readPrompt: vi.fn(() => prompt.promise),
+ renderAgentHeader: vi.fn(),
+ renderStream: vi.fn(async () => {}),
+ requestInterrupt: vi.fn(() => prompt.reject(interruptedError())),
+ };
+ const runner = new EveTUIRunner({
+ session: stubSession(),
+ client,
+ renderer,
+ lifecycle: {
+ signal: controller.signal,
+ stopped: new Promise<NodeJS.Signals | undefined>(() => {}),
+ requestStop: () => controller.abort(),
+ dispose: () => {},
+ },
+ });
+
+ const run = runner.run();
+ await settleAsyncWork();
+ controller.abort();
+
+ await expect(run).resolves.toBeUndefined();
+ expect(renderer.requestInterrupt).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.ts
index fe3bcf84c..851402668 100644
--- a/packages/eve/src/cli/dev/tui/runner.ts
+++ b/packages/eve/src/cli/dev/tui/runner.ts
@@ -98,6 +98,7 @@ import {
import type { detectProjectIdentity } from "#setup/project-resolution.js";
import { getVercelAuthStatus, type VercelAuthStatus } from "#setup/vercel-project.js";
import type { DevDiagnostics } from "../diagnostics.js";
+import type { CommandLifecycle } from "../../shutdown.js";
export { parsePromptCommand, type PromptCommand } from "./prompt-commands.js";
@@ -347,6 +348,8 @@ export type AgentTUIRenderer = {
* lifecycle ends.
*/
shutdown?(): void;
+ requestInterrupt?(): void;
+ exitRequested?(): boolean;
};
export interface PromptCommandHandlerContext {
@@ -436,6 +439,7 @@ export type EveTUIRunnerOptions = TuiDisplayOptions & {
onBootProgress?: DevBootProgressReporter;
/** Parent-owned diagnostics recorder; omitted for remote and test renderers. */
diagnostics?: DevDiagnostics;
+ lifecycle?: CommandLifecycle;
};
/** The attention-line issue for a Vercel auth state, or undefined when nothing's wrong. */
@@ -542,10 +546,12 @@ export class EveTUIRunner {
*/
#sessionFailed = false;
#unsubscribeDevelopmentSandboxLogs?: () => void;
+ readonly #lifecycle?: CommandLifecycle;
constructor(options: EveTUIRunnerOptions) {
this.#session = options.session;
if (options.client !== undefined) this.#client = options.client;
+ if (options.lifecycle !== undefined) this.#lifecycle = options.lifecycle;
this.#renderer = createRenderer(options);
const pumpOptions: SubagentPumpOptions = { formatActionResultError };
if (this.#client !== undefined) pumpOptions.client = this.#client;
@@ -666,9 +672,13 @@ export class EveTUIRunner {
}
async run() {
+ const onStop = () => this.#renderer.requestInterrupt?.();
+ if (this.#lifecycle?.signal.aborted === true) onStop();
+ else this.#lifecycle?.signal.addEventListener("abort", onStop, { once: true });
try {
await this.#run();
} finally {
+ this.#lifecycle?.signal.removeEventListener("abort", onStop);
this.#disposed = true;
this.#authProbeAbort.abort();
this.#subagentPump.abortAll();
@@ -723,6 +733,9 @@ export class EveTUIRunner {
}
while (true) {
+ if (this.#lifecycle?.signal.aborted === true || this.#renderer.exitRequested?.() === true) {
+ return;
+ }
if (!streamWithoutPrompt) {
if (prompt == null) {
if (!this.#renderer.readPrompt) {
@@ -1600,6 +1613,7 @@ function createRenderer(options: EveTUIRunnerOptions): AgentTUIRenderer {
input: options.userInput,
output: options.screen,
diagnostics: options.diagnostics,
+ onExitRequest: options.lifecycle?.requestStop,
});
}
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
index 3ee0071da..357b183eb 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
@@ -192,6 +192,25 @@ describe("TerminalRenderer (inline scrollback)", () => {
expect(latest.screen.snapshot()).not.toContain("ses_first");
});
+ it("restores the terminal when a forced process exit preempts teardown", async () => {
+ const before = process.listeners("exit");
+ const { screen, input, renderer } = makeRenderer();
+ const prompt = renderer.readPrompt();
+ const added = process.listeners("exit").filter((listener) => !before.includes(listener));
+ expect(added).toHaveLength(1);
+
+ // Simulate the lifecycle backstop's process.exit() firing mid-session.
+ (added[0] as () => void)();
+ expect(input.rawModes.at(-1)).toBe(false);
+ expect(screen.rawOutput()).toContain("\x1b[?2004l"); // bracketed paste off
+ expect(screen.rawOutput()).toContain("\x1b[?25h"); // cursor visible
+
+ // A normal teardown removes the last-resort hook.
+ input.ctrlC();
+ await expect(prompt).rejects.toThrow("Interrupted");
+ expect(process.listeners("exit")).toEqual(before);
+ });
+
it("renders the brand line with the agent name and a tip", () => {
const { screen, renderer } = makeRenderer();
renderer.renderAgentHeader({
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
index d8d5c1804..f26eab179 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
@@ -277,6 +277,7 @@ export type TerminalRendererOptions = {
diagnostics?: DevDiagnostics;
/** Slash commands available in this local or remote session. */
availablePromptCommands?: readonly PromptCommandSpec[];
+ onExitRequest?: () => void;
};
export type AgentHeaderOptions = {
@@ -456,6 +457,8 @@ export class TerminalRenderer implements AgentTUIRenderer {
#everInteractive = false;
#partingLinePrinted = false;
#interrupted = false;
+ #exitRequested = false;
+ readonly #onExitRequest?: () => void;
#caretVisible = true;
#spinnerIndex = 0;
#activityPulseStartedAtMs = Date.now();
@@ -580,6 +583,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#contextSize = options?.contextSize;
this.#captureForeignOutput = options?.captureForeignOutput ?? this.#output === process.stdout;
this.#diagnostics = options?.diagnostics;
+ this.#onExitRequest = options?.onExitRequest;
this.#logs = options?.logs ?? "none";
this.#availablePromptCommands = options?.availablePromptCommands ?? PROMPT_COMMANDS;
}
@@ -766,6 +770,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
case "ctrl-d":
// EOF on an empty line quits; otherwise it forward-deletes.
if (editor.text.length === 0) {
+ this.#requestExit();
interrupt();
} else {
apply(deleteForward(editor));
@@ -778,9 +783,8 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#paint();
break;
case "ctrl-c":
- // A first Ctrl+C clears a non-empty prompt; on an already-empty
- // prompt it quits.
if (editor.text.length === 0) {
+ this.#requestExit();
interrupt();
} else {
apply(EMPTY_LINE);
@@ -2394,7 +2398,12 @@ export class TerminalRenderer implements AgentTUIRenderer {
};
// See #armFlowIdleTrap: stale deferred keys die with the old consumer.
this.#clearKeyFlush();
- this.#consumeKey = (key) => consume(key, settle, reject);
+ this.#consumeKey = (key) => {
+ if (key.type === "ctrl-c") {
+ this.#requestExit();
+ }
+ consume(key, settle, reject);
+ };
this.#attachInput();
return { promise, settle };
}
@@ -2426,6 +2435,9 @@ export class TerminalRenderer implements AgentTUIRenderer {
if (this.#flowInterrupt === undefined) return;
const consumer = (key: TerminalKey): void => {
if (key.type === "ctrl-c" || key.type === "escape") {
+ if (key.type === "ctrl-c") {
+ this.#requestExit();
+ }
const fire = this.#flowInterrupt;
this.#flowInterrupt = undefined;
this.#disarmFlowIdleTrap();
@@ -2560,6 +2572,22 @@ export class TerminalRenderer implements AgentTUIRenderer {
}
}
+ requestInterrupt(): void {
+ this.#interrupted = true;
+ if (this.#setupFlow !== undefined) this.#consumeKey?.({ type: "ctrl-c" });
+ this.#resolveStreamInterrupt?.();
+ this.#stop();
+ }
+
+ exitRequested(): boolean {
+ return this.#exitRequested;
+ }
+
+ #requestExit(): void {
+ this.#exitRequested = true;
+ this.#onExitRequest?.();
+ }
+
// ---------------------------------------------------------------------------
// Lifecycle
// ---------------------------------------------------------------------------
@@ -2589,8 +2617,25 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#onResize = () => this.#paint();
this.#output.on("resize", this.#onResize);
+ process.on("exit", this.#onProcessExit);
}
+ /**
+ * Last-resort synchronous terminal restore for a forced `process.exit()`
+ * (the lifecycle's forced-exit backstop or a second Ctrl+C/SIGTERM) that
+ * preempts {@link #stop}. A shell left in raw mode with a hidden cursor and
+ * bracketed paste enabled is unusable; this runs on the process "exit"
+ * event, where only synchronous writes survive. Normal teardown removes it.
+ */
+ readonly #onProcessExit = () => {
+ if (!this.#isInteractive) return;
+ if (this.#input.isTTY) {
+ this.#live.emitBracketedPaste(false);
+ this.#input.setRawMode?.(false);
+ }
+ this.#live.showCursor();
+ };
+
#stop() {
// A reader still awaiting keys can never settle once input detaches;
// rejecting a promise that already settled is a no-op.
@@ -2636,6 +2681,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
this.#output.off("resize", this.#onResize);
this.#onResize = undefined;
}
+ process.off("exit", this.#onProcessExit);
this.#isInteractive = false;
}
diff --git a/packages/eve/src/cli/dev/tui/tui.ts b/packages/eve/src/cli/dev/tui/tui.ts
index d6fff057e..cef31755a 100644
--- a/packages/eve/src/cli/dev/tui/tui.ts
+++ b/packages/eve/src/cli/dev/tui/tui.ts
@@ -1,5 +1,6 @@
import { Client } from "#client/index.js";
import type { DevBootProgressReporter } from "#internal/dev-boot-progress.js";
+import type { CommandLifecycle } from "#cli/shutdown.js";
import {
resolveLocalDevelopmentClientOptions,
resolveRemoteDevelopmentClientOptions,
@@ -36,6 +37,7 @@ export interface RunDevelopmentTuiInput extends TuiDisplayOptions {
readonly initialInput?: string;
/** Reports local CLI boot phases. Omitted for remote and programmatic TUI runs. */
readonly onBootProgress?: DevBootProgressReporter;
+ readonly lifecycle?: CommandLifecycle;
}
function prepareRemoteTarget(target: RemoteDevelopmentTarget) {
@@ -80,7 +82,7 @@ function prepareDevelopmentTarget(target: DevelopmentTuiTarget): PreparedDevelop
* the inline error region rather than crashing the command.
*/
export async function runDevelopmentTui(input: RunDevelopmentTuiInput): Promise<void> {
- const { target, headers, initialInput, onBootProgress, ...display } = input;
+ const { target, headers, initialInput, onBootProgress, lifecycle, ...display } = input;
const prepared = prepareDevelopmentTarget(target);
const { serverUrl } = target;
const headerOptions = headers === undefined ? {} : { headers };
@@ -119,6 +121,7 @@ export async function runDevelopmentTui(input: RunDevelopmentTuiInput): Promise<
}
if (initialInput !== undefined) options.initialInput = initialInput;
if (onBootProgress !== undefined) options.onBootProgress = onBootProgress;
+ if (lifecycle !== undefined) options.lifecycle = lifecycle;
const diagnostics =
prepared.kind === "local"
diff --git a/packages/eve/src/cli/dev/wait-for-ui.ts b/packages/eve/src/cli/dev/wait-for-ui.ts
new file mode 100644
index 000000000..a43234f53
--- /dev/null
+++ b/packages/eve/src/cli/dev/wait-for-ui.ts
@@ -0,0 +1,36 @@
+import type { CommandLifecycle } from "#cli/shutdown.js";
+import type { DevelopmentServer, DevelopmentServerHandle } from "#internal/nitro/host/types.js";
+
+type WaitableServer = DevelopmentServer & { wait?: () => Promise<void> };
+
+export async function waitForServerOrStop(
+ server: WaitableServer,
+ lifecycle: CommandLifecycle,
+): Promise<void> {
+ await Promise.race([lifecycle.stopped, server.wait?.() ?? new Promise<void>(() => {})]);
+}
+
+export async function waitForUiOrServer(input: {
+ readonly handle: DevelopmentServerHandle;
+ readonly lifecycle: CommandLifecycle;
+ readonly runUi: () => Promise<void>;
+ readonly server: WaitableServer;
+}): Promise<void> {
+ const ui = input.runUi();
+ if (input.handle.kind === "existing" || input.server.wait === undefined) {
+ await ui;
+ return;
+ }
+ const result = await Promise.race([
+ ui.then(() => ({ type: "ui" as const })),
+ input.server.wait().then(
+ () => ({ type: "server" as const, error: undefined }),
+ (error: unknown) => ({ type: "server" as const, error }),
+ ),
+ ]);
+ if (result.type === "server") {
+ input.lifecycle.requestStop();
+ await ui;
+ if (result.error !== undefined) throw result.error;
+ }
+}
diff --git a/packages/eve/src/cli/run.test.ts b/packages/eve/src/cli/run.test.ts
index 5ee643ca9..c18febeed 100644
--- a/packages/eve/src/cli/run.test.ts
+++ b/packages/eve/src/cli/run.test.ts
@@ -421,6 +421,39 @@ describe("eve dev local server ownership", () => {
await runInteractiveDev(["dev"], { startHost });
expect(close).toHaveBeenCalledOnce();
});
+
+ it("awaits the close already started by a TUI stop request", async () => {
+ let resolveClose: () => void = () => {};
+ const closing = new Promise<void>((resolve) => {
+ resolveClose = resolve;
+ });
+ const close = vi.fn(() => closing);
+ const startHost = vi.fn(() => ({
+ start: async () => ({
+ kind: "started" as const,
+ appRoot: "/canonical/app",
+ url: "http://127.0.0.1:4321/",
+ }),
+ close,
+ }));
+ const runDevelopmentTui = vi.fn(async (input: RunDevelopmentTuiInput) => {
+ input.lifecycle?.requestStop();
+ });
+
+ let settled = false;
+ const run = withInteractiveTerminal(() =>
+ runCli(["dev"], { error: () => {}, log: () => {} }, { runDevelopmentTui, startHost }),
+ ).then(() => {
+ settled = true;
+ });
+ await vi.waitFor(() => expect(close).toHaveBeenCalledOnce());
+ await Promise.resolve();
+ expect(settled).toBe(false);
+
+ resolveClose();
+ await run;
+ expect(close).toHaveBeenCalledOnce();
+ });
});
describe("eve build output ownership", () => {
diff --git a/packages/eve/src/cli/run.ts b/packages/eve/src/cli/run.ts
index 9f31469fd..eaf71773a 100644
--- a/packages/eve/src/cli/run.ts
+++ b/packages/eve/src/cli/run.ts
@@ -7,6 +7,13 @@ import { isCodingAgentLaunch } from "#cli/agent-detection.js";
import { eveCliBanner } from "#cli/banner.js";
import { registerProjectCommands } from "#cli/commands/register-project-commands.js";
import { resolveDevUiMode, resolveTuiDisplayOptions } from "#cli/dev/ui-options.js";
+import {
+ FORCED_EXIT_BACKSTOP_MS,
+ installShutdownSignal,
+ type CommandLifecycle,
+ waitForShutdownSignal,
+} from "#cli/shutdown.js";
+import { waitForServerOrStop, waitForUiOrServer } from "#cli/dev/wait-for-ui.js";
import {
parseDevelopmentHeaderOption,
resolveDevelopmentUrlTarget,
@@ -140,7 +147,7 @@ async function loadRunEvalCommand(): Promise<CliRuntimeDependencies["runEvalComm
}
async function loadStartHost(): Promise<CliRuntimeDependencies["startHost"]> {
- return (await import("#internal/nitro/host.js")).createDevelopmentServer;
+ return (await import("#cli/dev/local-server-process.js")).createDevelopmentServer;
}
const loadIsActiveDevelopmentServerForApp = async () =>
@@ -158,39 +165,6 @@ function shouldPrintCliBootBanner(actionCommand: Command): boolean {
);
}
-async function waitForShutdownSignal(input: { close(): Promise<void> }): Promise<void> {
- await new Promise<void>((resolve, reject) => {
- let settled = false;
-
- const cleanup = () => {
- process.off("SIGINT", handleSignal);
- process.off("SIGTERM", handleSignal);
- };
-
- const handleSignal = () => {
- if (settled) {
- return;
- }
-
- settled = true;
- cleanup();
- void input.close().then(resolve, reject);
- };
-
- process.once("SIGINT", handleSignal);
- process.once("SIGTERM", handleSignal);
- });
-}
-
-async function waitForProductionServer(input: ProductionServerHandle): Promise<void> {
- await Promise.race([
- input.wait(),
- waitForShutdownSignal({
- close: () => input.close(),
- }),
- ]);
-}
-
function parsePortOption(value: string): number {
if (!/^-?\d+$/.test(value)) {
throw new InvalidArgumentError(`Expected a numeric port, received "${value}".`);
@@ -388,7 +362,7 @@ function createCliProgram(logger: CliLogger, runtime: CliRuntimeOverrides): Comm
}),
);
- await waitForProductionServer(server);
+ await waitForShutdownSignal({ close: () => server.close(), wait: () => server.wait() });
});
program
@@ -465,6 +439,7 @@ function createCliProgram(logger: CliLogger, runtime: CliRuntimeOverrides): Comm
readonly serverUrl: string;
},
report?: DevBootProgressReporter,
+ lifecycle?: CommandLifecycle,
): Promise<void> => {
const runDevelopmentTui = await devBootPhase(
"loading interactive UI",
@@ -486,6 +461,7 @@ function createCliProgram(logger: CliLogger, runtime: CliRuntimeOverrides): Comm
target,
initialInput: options.input,
onBootProgress: report,
+ lifecycle,
...display,
} satisfies RunDevelopmentTuiInput;
if (remoteTarget?.headers !== undefined) {
@@ -514,27 +490,34 @@ function createCliProgram(logger: CliLogger, runtime: CliRuntimeOverrides): Comm
}
logger.log("");
- await runInteractiveUi({ serverUrl: remoteServerUrl });
+ const lifecycle = installShutdownSignal({ exitAfterMs: FORCED_EXIT_BACKSTOP_MS });
+ try {
+ await runInteractiveUi({ serverUrl: remoteServerUrl }, undefined, lifecycle);
+ } finally {
+ lifecycle.dispose();
+ }
return;
}
- // Print spacing before the live row; a later write would strand the row.
if (mode === "tui") logger.log("");
const buildProgress = mode === "tui" ? startCliLiveRow(logger) : undefined;
const onBootProgress = createDevBootProgressReporter(buildProgress);
buildProgress?.update("Building your agent");
- let closed = false;
let server: DevelopmentServer | undefined;
- const closeServer = async () => {
- if (closed || server === undefined) {
- return;
- }
-
- closed = true;
- // No-op when this instance attached to a server another process owns.
- await server.close();
+ let closePromise: Promise<void> | undefined;
+ const closeServer = () => {
+ if (server === undefined) return Promise.resolve();
+ closePromise ??= server.close();
+ void closePromise.catch(() => undefined);
+ return closePromise;
};
+ const lifecycle = installShutdownSignal({
+ exitAfterMs: FORCED_EXIT_BACKSTOP_MS,
+ onStop: () => {
+ void closeServer();
+ },
+ });
try {
const startHost = runtime.startHost ?? (await loadStartHost());
@@ -544,11 +527,13 @@ function createCliProgram(logger: CliLogger, runtime: CliRuntimeOverrides): Comm
onBootProgress,
port: options.port,
});
- const handle = await server.start();
+ const outcome = await Promise.race([
+ server.start().then((handle) => ({ handle })),
+ lifecycle.stopped.then(() => ({ handle: undefined })),
+ ]);
+ const handle = outcome.handle;
+ if (handle === undefined) return;
- // The terminal UI's header already shows the server URL, and startup
- // no longer clears the screen, so the line would linger as noise.
- // Headless consumers (scripts, scenario tests) still parse it.
if (mode !== "tui") {
logger.log(
renderCliTaggedLine(theme, {
@@ -560,9 +545,6 @@ function createCliProgram(logger: CliLogger, runtime: CliRuntimeOverrides): Comm
}
if (mode === "headless") {
- // An explicit `--no-ui` is intentional and silent; a non-TTY
- // terminal that did not ask for headless gets a hint so the
- // missing UI is not mistaken for a hang.
if (options.ui !== false && !interactive) {
logger.log(
renderCliTaggedLine(theme, {
@@ -573,15 +555,25 @@ function createCliProgram(logger: CliLogger, runtime: CliRuntimeOverrides): Comm
);
}
- return await waitForShutdownSignal({
- close: closeServer,
- });
+ await waitForServerOrStop(server, lifecycle);
+ return;
}
- await runInteractiveUi({ appRoot: handle.appRoot, serverUrl: handle.url }, onBootProgress);
+ await waitForUiOrServer({
+ handle,
+ lifecycle,
+ server,
+ runUi: async () =>
+ await runInteractiveUi(
+ { appRoot: handle.appRoot, serverUrl: handle.url },
+ onBootProgress,
+ lifecycle,
+ ),
+ });
} finally {
buildProgress?.stop();
await closeServer();
+ lifecycle.dispose();
}
});
diff --git a/packages/eve/src/cli/shutdown.test.ts b/packages/eve/src/cli/shutdown.test.ts
new file mode 100644
index 000000000..a0f131386
--- /dev/null
+++ b/packages/eve/src/cli/shutdown.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+
+import { installShutdownSignal, waitForShutdownSignal } from "#cli/shutdown.js";
+
+describe("installShutdownSignal", () => {
+ it("removes its process listeners when disposed", () => {
+ const sigint = process.listenerCount("SIGINT");
+ const sigterm = process.listenerCount("SIGTERM");
+ const lifecycle = installShutdownSignal();
+
+ expect(process.listenerCount("SIGINT")).toBe(sigint + 1);
+ expect(process.listenerCount("SIGTERM")).toBe(sigterm + 1);
+ lifecycle.requestStop();
+ lifecycle.requestStop();
+ lifecycle.dispose();
+
+ expect(process.listenerCount("SIGINT")).toBe(sigint);
+ expect(process.listenerCount("SIGTERM")).toBe(sigterm);
+ });
+
+ it("removes listeners when an owned server stops itself", async () => {
+ const sigint = process.listenerCount("SIGINT");
+ const sigterm = process.listenerCount("SIGTERM");
+
+ await waitForShutdownSignal({ close: async () => {}, wait: async () => {} });
+
+ expect(process.listenerCount("SIGINT")).toBe(sigint);
+ expect(process.listenerCount("SIGTERM")).toBe(sigterm);
+ });
+});
diff --git a/packages/eve/src/cli/shutdown.ts b/packages/eve/src/cli/shutdown.ts
new file mode 100644
index 000000000..fa4807373
--- /dev/null
+++ b/packages/eve/src/cli/shutdown.ts
@@ -0,0 +1,77 @@
+/**
+ * How long a stop request may run before the process force-exits, passed as
+ * `exitAfterMs` by commands that own child resources. Cleanup owners must
+ * finish inside this budget — see DEV_SERVER_CLOSE_BUDGET_MS in
+ * `#cli/dev/local-server-process.js`.
+ */
+export const FORCED_EXIT_BACKSTOP_MS = 900;
+
+export interface CommandLifecycle {
+ readonly signal: AbortSignal;
+ readonly stopped: Promise<NodeJS.Signals | undefined>;
+ requestStop(): void;
+ dispose(): void;
+}
+
+/** Owns SIGINT/SIGTERM listeners for one running CLI command. */
+export function installShutdownSignal(
+ input: {
+ readonly exitAfterMs?: number;
+ readonly onStop?: () => void;
+ } = {},
+): CommandLifecycle {
+ const controller = new AbortController();
+ const stopped = Promise.withResolvers<NodeJS.Signals | undefined>();
+ let stopRequested = false;
+ let signalCount = 0;
+ let backstop: NodeJS.Timeout | undefined;
+ const stop = (signal?: NodeJS.Signals) => {
+ if (stopRequested) return;
+ stopRequested = true;
+ input.onStop?.();
+ controller.abort(signal);
+ stopped.resolve(signal);
+ if (input.exitAfterMs !== undefined) {
+ backstop = setTimeout(
+ () => process.exit(signal === undefined ? 0 : signal === "SIGINT" ? 130 : 143),
+ input.exitAfterMs,
+ );
+ }
+ };
+ const handleSignal = (signal: NodeJS.Signals) => {
+ signalCount += 1;
+ if (signalCount > 1) process.exit(signal === "SIGINT" ? 130 : 143);
+ stop(signal);
+ };
+ const onSigint = () => handleSignal("SIGINT");
+ const onSigterm = () => handleSignal("SIGTERM");
+ process.on("SIGINT", onSigint);
+ process.on("SIGTERM", onSigterm);
+ return {
+ signal: controller.signal,
+ stopped: stopped.promise,
+ requestStop: () => stop(),
+ dispose() {
+ if (backstop !== undefined) clearTimeout(backstop);
+ process.off("SIGINT", onSigint);
+ process.off("SIGTERM", onSigterm);
+ },
+ };
+}
+
+/** Waits for a signal, or until the owned server stops on its own. */
+export async function waitForShutdownSignal(input: {
+ readonly close: () => Promise<void>;
+ readonly wait?: () => Promise<void>;
+}): Promise<void> {
+ const lifecycle = installShutdownSignal();
+ try {
+ const outcome = await Promise.race([
+ lifecycle.stopped.then(() => "signal" as const),
+ input.wait?.().then(() => "stopped" as const) ?? new Promise<never>(() => {}),
+ ]);
+ if (outcome === "signal") await input.close();
+ } finally {
+ lifecycle.dispose();
+ }
+}
diff --git a/packages/eve/test/scenarios/dev-server-harness.ts b/packages/eve/test/scenarios/dev-server-harness.ts
index 66f1b6ae3..235f07e74 100644
--- a/packages/eve/test/scenarios/dev-server-harness.ts
+++ b/packages/eve/test/scenarios/dev-server-harness.ts
@@ -19,6 +19,15 @@ export interface RunningEveDev {
readonly stderr: () => string;
readonly stdout: () => string;
readonly url: string;
+ signalAndAwaitExit(
+ signal: NodeJS.Signals,
+ deadlineMs?: number,
+ ): Promise<{
+ readonly code: number | null;
+ readonly durationMs: number;
+ readonly forcedKill: boolean;
+ readonly signal: NodeJS.Signals | null;
+ }>;
stop(): Promise<void>;
}
@@ -28,6 +37,43 @@ export interface StartEveDevOptions {
readonly runtime?: "bun" | "node";
}
+export async function signalEveDevDuringStartup(
+ appRoot: string,
+ signal: NodeJS.Signals,
+): Promise<{ readonly durationMs: number; readonly forcedKill: boolean }> {
+ const child = spawnEveDev(appRoot, {});
+ let output = "";
+ child.stdout.setEncoding("utf8");
+ child.stderr.setEncoding("utf8");
+ child.stdout.on("data", (chunk: string) => {
+ output += chunk;
+ });
+ child.stderr.on("data", (chunk: string) => {
+ output += chunk;
+ });
+ const deadline = Date.now() + 30_000;
+ while (!output.includes("eve")) {
+ if (Date.now() >= deadline)
+ throw new Error(`Timed out waiting for eve dev startup.\n${output}`);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ const startedAt = Date.now();
+ let forcedKill = false;
+ await new Promise<void>((resolve) => {
+ const timer = setTimeout(() => {
+ forcedKill = true;
+ child.kill("SIGKILL");
+ }, 1_000);
+ child.once("exit", () => {
+ clearTimeout(timer);
+ resolve();
+ });
+ child.kill(signal);
+ });
+ return { durationMs: Date.now() - startedAt, forcedKill };
+}
+
/**
* Spawns `eve dev --no-ui` for the app and resolves once the server URL is
* printed and the state record exists. `NODE_ENV=test` activates the
@@ -78,6 +124,24 @@ export async function startEveDev(
},
stderr: () => stderr,
stdout: () => stdout,
+ async signalAndAwaitExit(signal, deadlineMs = 1_000) {
+ if (child.exitCode !== null || child.signalCode !== null) {
+ return { code: child.exitCode, durationMs: 0, forcedKill: false, signal: child.signalCode };
+ }
+ const startedAt = Date.now();
+ return await new Promise((resolve) => {
+ let forcedKill = false;
+ const timer = setTimeout(() => {
+ forcedKill = true;
+ child.kill("SIGKILL");
+ }, deadlineMs);
+ child.once("exit", (code, exitSignal) => {
+ clearTimeout(timer);
+ resolve({ code, durationMs: Date.now() - startedAt, forcedKill, signal: exitSignal });
+ });
+ child.kill(signal);
+ });
+ },
async stop() {
await stopEveDevChild(child);
},
diff --git a/packages/eve/test/scenarios/dev-server-shutdown.scenario.test.ts b/packages/eve/test/scenarios/dev-server-shutdown.scenario.test.ts
new file mode 100644
index 000000000..af2663c17
--- /dev/null
+++ b/packages/eve/test/scenarios/dev-server-shutdown.scenario.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from "vitest";
+
+import { WEATHER_AGENT_DESCRIPTOR } from "../../src/internal/testing/scenario-apps/weather-agent.js";
+import { useScenarioApp } from "../../src/internal/testing/scenario-app.js";
+import { signalEveDevDuringStartup, startEveDev } from "./dev-server-harness.js";
+
+const scenarioApp = useScenarioApp();
+
+describe("eve dev shutdown", () => {
+ for (const signal of ["SIGINT", "SIGTERM"] as const) {
+ it(`returns within one second after ${signal}`, async () => {
+ const app = await scenarioApp(WEATHER_AGENT_DESCRIPTOR);
+ const server = await startEveDev(app.appRoot);
+
+ const exit = await server.signalAndAwaitExit(signal);
+
+ expect(exit.forcedKill).toBe(false);
+ expect(exit.durationMs).toBeLessThan(1_000);
+ expect(exit.code).toBe(0);
+ expect(exit.signal).toBe(null);
+ await expect(fetch(server.url)).rejects.toThrow();
+ }, 120_000);
+ }
+
+ it("returns within one second when signalled during startup", async () => {
+ const app = await scenarioApp(WEATHER_AGENT_DESCRIPTOR);
+ const exit = await signalEveDevDuringStartup(app.appRoot, "SIGTERM");
+
+ expect(exit.forcedKill).toBe(false);
+ expect(exit.durationMs).toBeLessThan(1_000);
+ }, 120_000);
+});