From 9c3f9f079a47e0dd889cd41c2ad7a7d78e6e6bd9 Mon Sep 17 00:00:00 2001 From: BIackFIame <77388790+BIackFIame@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:19:38 +0000 Subject: [PATCH 1/2] fix(agents): report an agent killed by a signal as failed with exit 128+n node-pty reports a process killed by a signal as exitCode 0 plus the signal. recordExit dropped the signal, so an agent killed with SIGKILL (out of memory, kill -9) was recorded as "done, exit 0": wait_for_agent returned done, get_agent_result said done and the saved session restored as exited. Record such an exit the way a shell does, as 128+signal (SIGKILL -> 137), mark the session failed and put the signal name first in the failure details. Every reader of the exit (wait_for_agent, get_agent_result, the session store, the HOME failure summary) already derives its state from the exit code, so they now agree. Exits CanvasTTY causes itself (closing a card, quitting) are unaffected: those sessions are removed before the kill, and the exit handler ignores them. --- src/main/services/TerminalManager.ts | 22 ++++-- tests/helpers/terminal.mjs | 2 +- tests/subagent-signal-exit.test.mjs | 101 +++++++++++++++++++++++++++ tests/terminal-lifecycle.test.mjs | 2 +- 4 files changed, 121 insertions(+), 6 deletions(-) create mode 100644 tests/subagent-signal-exit.test.mjs diff --git a/src/main/services/TerminalManager.ts b/src/main/services/TerminalManager.ts index 9e05ee78f..82592d9c5 100644 --- a/src/main/services/TerminalManager.ts +++ b/src/main/services/TerminalManager.ts @@ -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"; @@ -2513,7 +2514,7 @@ export class TerminalManager { let exited!: () => void; this.liveProcesses.set(process, new Promise((resolve) => { exited = resolve; })); - process.onExit(({ exitCode }) => { + process.onExit(({ exitCode, signal }) => { this.liveProcesses.delete(process); clearTimeout(this.closedProcessTimers.get(process)); this.closedProcessTimers.delete(process); @@ -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(); @@ -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}.`; +} diff --git a/tests/helpers/terminal.mjs b/tests/helpers/terminal.mjs index 9e612d96c..1fcfcbfb9 100644 --- a/tests/helpers/terminal.mjs +++ b/tests/helpers/terminal.mjs @@ -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; diff --git a/tests/subagent-signal-exit.test.mjs b/tests/subagent-signal-exit.test.mjs new file mode 100644 index 000000000..6bd35dae4 --- /dev/null +++ b/tests/subagent-signal-exit.test.mjs @@ -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"); +}); diff --git a/tests/terminal-lifecycle.test.mjs b/tests/terminal-lifecycle.test.mjs index d0b868511..1a9669ed3 100644 --- a/tests/terminal-lifecycle.test.mjs +++ b/tests/terminal-lifecycle.test.mjs @@ -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\n\s+\? null/); }); function effectDependenciesContaining(source, marker) { From 0b9300def90cb0cd89f5fbf1af1b9fcf30f88f1a Mon Sep 17 00:00:00 2001 From: BIackFIame <77388790+BIackFIame@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:27:34 +0000 Subject: [PATCH 2/2] test: accept CRLF in the failure details source assertion On the Windows CI runner the checkout uses CRLF, so the source assertion added for the renamed line (a literal "\n" between two lines of TerminalManager.ts) did not match. It now accepts "\r?\n". --- tests/terminal-lifecycle.test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/terminal-lifecycle.test.mjs b/tests/terminal-lifecycle.test.mjs index 1a9669ed3..86e19588d 100644 --- a/tests/terminal-lifecycle.test.mjs +++ b/tests/terminal-lifecycle.test.mjs @@ -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, /const details = exitCode === 0\n\s+\? null/); + assert.match(source, /const details = exitCode === 0\r?\n\s+\? null/); }); function effectDependenciesContaining(source, marker) {