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
22 changes: 18 additions & 4 deletions src/main/services/TerminalManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { ORCHESTRATION_ENV } from "./agent-browser/orchestration-protocol.ts";
import { connectedLaunchEnvironment } from "../../agent-runtime/launch-environment.mjs";
import { instrumentShellCodex, resumeShellCodex } from "./shellCodexLaunch.ts";
import { realpathSync, statSync } from "node:fs";
import { constants as osConstants } from "node:os";
import { basename, dirname } from "node:path";
import { isPathInside } from "../../agent-runtime/path-inside.mjs";
import * as pty from "node-pty";
Expand Down Expand Up @@ -2513,7 +2514,7 @@ export class TerminalManager {

let exited!: () => void;
this.liveProcesses.set(process, new Promise<void>((resolve) => { exited = resolve; }));
process.onExit(({ exitCode }) => {
process.onExit(({ exitCode, signal }) => {
this.liveProcesses.delete(process);
clearTimeout(this.closedProcessTimers.get(process));
this.closedProcessTimers.delete(process);
Expand All @@ -2523,22 +2524,29 @@ export class TerminalManager {
if (!current || current !== session || current.process !== process) return;
// node-pty calls this from a native callback that aborts the whole app when JavaScript throws in it.
try {
this.recordExit(id, current, exitCode);
this.recordExit(id, current, exitCode, signal);
} catch (error) {
console.warn(`PTY ${id} exit could not be recorded.`, error);
}
});
}

private recordExit(id: string, current: ManagedSession, exitCode: number): void {
private recordExit(id: string, current: ManagedSession, reportedExitCode: number, signal?: number): void {
this.flushOutput(id, current);
this.releaseIsolation(id);
if (current.extras.gitAuditSince !== undefined) void this.auditGit(id, current);
// node-pty reports a process killed by a signal as exitCode 0 plus the signal. That is a crash, not a clean finish:
// record it the way a shell does, as 128+signal, so the card, wait_for_agent and the saved session all say failed.
const killedBy = typeof signal === "number" && signal > 0 ? signal : 0;
const exitCode = killedBy ? 128 + killedBy : reportedExitCode;
current.metadata.exitCode = exitCode;
current.metadata.status = exitCode === 0 ? "done" : "failed";
current.metadata.failureDetails = exitCode === 0
const details = exitCode === 0
? null
: terminalFailureDetails(this.redactSecrets(current.bufferChunks.slice(current.bufferStart).join("")));
current.metadata.failureDetails = killedBy
? `${signalExitText(killedBy)}${details ? `\n${details}` : ""}`.slice(0, 8_000)
: details;
current.agentBrowser?.cleanup();
current.agentBrowser = null;
current.agentRuntime?.cleanup();
Expand Down Expand Up @@ -2892,3 +2900,9 @@ function appendScrollback(session: ManagedSession, data: string): void {
session.bufferStart = 0;
}
}

/** "The process was killed by signal SIGKILL (9)." from node-pty's signal number. */
function signalExitText(signal: number): string {
const name = Object.entries(osConstants.signals).find(([, value]) => value === signal)?.[0];
return `The process was killed by signal ${name ? `${name} (${signal})` : signal}.`;
}
2 changes: 1 addition & 1 deletion tests/helpers/terminal.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export function fakeSpawner(calls, { pidBase = 20_000, onWrite } = {}) {
return { dispose() {} };
},
emitData(data) { dataListener(data); },
emitExit(exitCode) { exitListener({ exitCode, signal: 0 }); }
emitExit(exitCode, signal = 0) { exitListener({ exitCode, signal }); }
};
calls.push({ command, args, options, process });
return process;
Expand Down
101 changes: 101 additions & 0 deletions tests/subagent-signal-exit.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import assert from "node:assert/strict";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import pty from "node-pty";
import { AgentControlService } from "../src/main/services/AgentControlService.ts";
import { TerminalManager } from "../src/main/services/TerminalManager.ts";
import { persistedTerminalSession } from "../src/main/services/TerminalSessionStore.ts";
import { failureSummary } from "../src/renderer/src/features/home/failureSummary.ts";
import { availableRegistry, fakeSpawner } from "./helpers/terminal.mjs";

// node-pty reports a process killed by a signal as { exitCode: 0, signal }. The signal was dropped, so a subagent
// whose CLI was killed (OOM, kill -9) read as "done, exit 0" in wait_for_agent, get_agent_result and the saved session.

const at = { x: 0, y: 0 };
const posix = { skip: process.platform === "win32" ? "POSIX signals only" : false };

async function until(check, timeoutMs = 5_000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const value = check();
if (value) return value;
await new Promise((resolve) => setTimeout(resolve, 25));
}
throw new Error("timed out");
}

function fakeFixture(t) {
const calls = [];
const terminals = new TerminalManager(() => undefined, availableRegistry(), undefined, undefined, true, fakeSpawner(calls));
t.after(() => terminals.disposeAll());
const control = new AgentControlService(terminals);
const session = terminals.create({ provider: "opencode", profile: "normal", cwd: process.cwd(), position: at });
return { calls, terminals, control, session };
}

test("an agent whose process a signal ended is failed with 128+signal and the signal named, everywhere its exit is read", async (t) => {
const f = fakeFixture(t);
f.calls.at(-1).process.emitExit(0, 15);
const ended = f.terminals.getMetadata(f.session.id);
assert.equal(ended.status, "failed");
assert.equal(ended.exitCode, 143);
assert.match(ended.failureDetails, /^The process was killed by signal SIGTERM \(15\)\./u);
const waited = await f.control.waitFor(f.session.id, { timeoutMs: 1_000 });
assert.equal(waited.reason, "failed");
assert.equal(waited.exitCode, 143);
const result = await f.control.result(f.session.id);
assert.equal(result.state, "failed");
assert.equal(result.exitCode, 143);
const saved = persistedTerminalSession(ended);
assert.equal(saved.lastState, "failed");
assert.equal(saved.exitCode, 143);
const summary = failureSummary(ended, "en");
assert.match(summary.headline, /143/u);
assert.match(summary.diagnostics, /^The process was killed by signal SIGTERM \(15\)\./u);
});

test("an exit without a signal keeps its own code", async (t) => {
for (const code of [0, 2]) {
const f = fakeFixture(t);
f.calls.at(-1).process.emitExit(code, 0);
const ended = f.terminals.getMetadata(f.session.id);
assert.equal(ended.exitCode, code);
assert.equal(ended.status, code === 0 ? "done" : "failed");
assert.doesNotMatch(ended.failureDetails ?? "", /killed by signal/u);
}
});

test("a real agent process killed with SIGKILL is failed (137); one that exits cleanly stays done", posix, async (t) => {
const root = await mkdtemp(join(tmpdir(), "ctty-signal-exit-"));
const spawned = [];
let argv = ["/bin/sleep", "30"];
const terminals = new TerminalManager(() => undefined, availableRegistry(), undefined, undefined, true, (_command, _args, options) => {
const child = pty.spawn(argv[0], argv.slice(1), { name: "xterm-256color", cols: 80, rows: 24, cwd: options.cwd, env: { PATH: "/usr/bin:/bin", HOME: options.cwd } });
spawned.push(child);
return child;
});
t.after(async () => {
terminals.disposeAll();
// Only the processes this test started.
for (const child of spawned) { try { process.kill(child.pid, "SIGKILL"); } catch { /* exited */ } }
await rm(root, { recursive: true, force: true });
});
const control = new AgentControlService(terminals);
const killed = terminals.create({ provider: "opencode", profile: "normal", cwd: root, position: at });
process.kill(spawned.at(-1).pid, "SIGKILL");
const ended = await until(() => { const m = terminals.getMetadata(killed.id); return m.exitCode !== null ? m : null; });
assert.equal(ended.status, "failed");
assert.equal(ended.exitCode, 137);
assert.match(ended.failureDetails, /killed by signal SIGKILL \(9\)/u);
assert.equal((await control.waitFor(killed.id, { timeoutMs: 1_000 })).reason, "failed");

argv = ["/usr/bin/true"];
const clean = terminals.create({ provider: "opencode", profile: "normal", cwd: root, position: at });
const done = await until(() => { const m = terminals.getMetadata(clean.id); return m.exitCode !== null ? m : null; });
assert.equal(done.status, "done");
assert.equal(done.exitCode, 0);
assert.equal(done.failureDetails, null);
assert.equal((await control.result(clean.id)).state, "done");
});
2 changes: 1 addition & 1 deletion tests/terminal-lifecycle.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,7 @@ test("failed PTYs preserve their final sanitized output as failure details", asy

// Masked whole before the last lines are chosen (a cut inside a secret would leave its tail readable).
assert.match(source, /terminalFailureDetails\(this\.redactSecrets\(current\.bufferChunks\.slice\(current\.bufferStart\)\.join\(""\)\)\)/);
assert.match(source, /current\.metadata\.failureDetails = exitCode === 0/);
assert.match(source, /const details = exitCode === 0\r?\n\s+\? null/);
});

function effectDependenciesContaining(source, marker) {
Expand Down
Loading