Skip to content

Commit cde3458

Browse files
mingyooagisteipete
andauthored
fix: gateway kill leaves Codex tool processes running (#107721)
* fix(codex): stop native terminals on run cancellation Codex turn interruption deliberately leaves native background terminals running. Wait for the matching turn to stop, terminate that thread's terminals through the app-server API, and join cleanup before releasing the attempt. Surface cleanup failures without retiring shared peer threads. Keep existing host process scopes and background gateway jobs unchanged. Verified with 412 focused tests and an authenticated live Codex run with a concurrent peer thread on the same app-server. Co-authored-by: Ming Yoo <[email protected]> * fix(codex): freeze cancellation before attempt teardown Close cancellation admission synchronously when cleanup takes ownership, including when finalization throws before freezing its terminal outcome. This keeps late aborts from replacing the joined cleanup promise during resource release or masking the original finalization error. Move the existing terminal freeze instead of adding another lifecycle flag. Verified the regression fails before the change; all 413 Codex tests pass. --------- Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: Ming Yoo <[email protected]>
1 parent 0b0a64e commit cde3458

11 files changed

Lines changed: 271 additions & 51 deletions

‎docs/plugins/codex-harness.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,14 @@ to the Gateway host and follows OpenClaw exec policy. `gateway_process` uses the
5858
existing per-session OpenClaw process scope for background follow-up. Prefer
5959
Codex native shell for ordinary local work.
6060

61+
Stopping an active Codex run interrupts its turn, then stops the native background
62+
terminals listed on that Codex thread before releasing the run. Other Codex
63+
threads and deliberately backgrounded `gateway_process` jobs are unaffected.
64+
If native terminal cleanup fails, the run reports an error instead of silently
65+
claiming cleanup succeeded. Inspect that thread's running terminals before
66+
starting more work. This uses Codex's terminal ownership; it does not guarantee
67+
cleanup of commands that deliberately detach from that ownership.
68+
6169
With the default `tools.exec.host: "auto"` and no active OpenClaw sandbox,
6270
Codex also receives `node_exec` for commands on paired nodes. Native shell
6371
remains on the Codex app-server host and workspace

‎extensions/codex/src/app-server/attempt-client-cleanup.test.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,62 @@ import {
66
retireUnsafeCodexTurnClientBestEffort,
77
retireCodexAppServerClientAfterTimedOutTurn,
88
unsubscribeCodexThreadBestEffort,
9+
terminateCodexBackgroundTerminals,
910
} from "./attempt-client-cleanup.js";
1011
import { createClientHarness } from "./test-support.js";
1112

1213
describe("Codex app-server attempt client cleanup", () => {
14+
it.each([true, false])(
15+
"drains the full terminal inventory and accepts a concurrent exit (%s)",
16+
async (terminated) => {
17+
const request = vi
18+
.fn()
19+
.mockResolvedValueOnce({
20+
data: [{ processId: "10" }, { processId: "20" }],
21+
nextCursor: null,
22+
})
23+
.mockResolvedValueOnce({ terminated })
24+
.mockResolvedValueOnce({ terminated: true })
25+
.mockResolvedValueOnce({ data: [], nextCursor: null });
26+
await expect(
27+
terminateCodexBackgroundTerminals({ request } as never, "thread-1"),
28+
).resolves.toBeUndefined();
29+
expect(request.mock.calls.map(([method, params]) => [method, params])).toEqual([
30+
["thread/backgroundTerminals/list", { threadId: "thread-1" }],
31+
["thread/backgroundTerminals/terminate", { threadId: "thread-1", processId: "10" }],
32+
["thread/backgroundTerminals/terminate", { threadId: "thread-1", processId: "20" }],
33+
["thread/backgroundTerminals/list", { threadId: "thread-1", limit: 1 }],
34+
]);
35+
},
36+
);
37+
38+
it("reports a terminal that remains running after termination", async () => {
39+
const request = vi
40+
.fn()
41+
.mockResolvedValueOnce({ data: [{ processId: "10" }], nextCursor: null })
42+
.mockResolvedValueOnce({ terminated: false })
43+
.mockResolvedValueOnce({ data: [{ processId: "10" }], nextCursor: null });
44+
await expect(
45+
terminateCodexBackgroundTerminals({ request } as never, "thread-1"),
46+
).rejects.toThrow("Codex background-terminal cleanup failed");
47+
});
48+
49+
it("bounds the entire terminal inventory request without closing the shared client", async () => {
50+
vi.useFakeTimers();
51+
const harness = createClientHarness();
52+
const close = vi.spyOn(harness.client, "close");
53+
try {
54+
const cleanup = terminateCodexBackgroundTerminals(harness.client, "thread-1");
55+
const rejected = expect(cleanup).rejects.toThrow("Codex background-terminal cleanup failed");
56+
await vi.advanceTimersByTimeAsync(5_000);
57+
await rejected;
58+
expect(close).not.toHaveBeenCalled();
59+
} finally {
60+
harness.client.close();
61+
vi.useRealTimers();
62+
}
63+
});
64+
1365
it("keeps strict startup retirement failures visible to lifecycle owners", async () => {
1466
const closeAndWait = vi.fn(async () => {
1567
throw new Error("strict client retirement failed");

‎extensions/codex/src/app-server/attempt-client-cleanup.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,46 @@ export async function interruptCodexTurnAndWaitBestEffort(
138138
}
139139
}
140140

141+
/** Stops native terminals on the cancelled thread without retiring peer threads. */
142+
export async function terminateCodexBackgroundTerminals(
143+
client: CodexAppServerClient,
144+
threadId: string,
145+
): Promise<void> {
146+
const options = {
147+
timeoutMs: CODEX_APP_SERVER_INTERRUPT_TIMEOUT_MS,
148+
signal: AbortSignal.timeout(CODEX_APP_SERVER_INTERRUPT_TIMEOUT_MS),
149+
};
150+
try {
151+
// Codex returns the complete inventory when limit is omitted. Its process
152+
// IDs are thread-owned handles, not host PIDs or process-group authority.
153+
const { data } = await client.request("thread/backgroundTerminals/list", { threadId }, options);
154+
for (const { processId } of data) {
155+
// False also means it exited between listing and termination. The final
156+
// inventory distinguishes that benign race from a failed termination.
157+
await client.request(
158+
"thread/backgroundTerminals/terminate",
159+
{ threadId, processId },
160+
options,
161+
);
162+
}
163+
if (data.length > 0) {
164+
const remaining = await client.request(
165+
"thread/backgroundTerminals/list",
166+
{ threadId, limit: 1 },
167+
options,
168+
);
169+
if (remaining.data.length > 0) {
170+
throw new Error("native background terminals remain running");
171+
}
172+
}
173+
} catch (cause) {
174+
throw new Error(
175+
"Codex background-terminal cleanup failed; inspect the thread's running terminals before starting more work.",
176+
{ cause },
177+
);
178+
}
179+
}
180+
141181
/** Unsubscribes from a thread while swallowing cleanup-only failures. */
142182
export async function unsubscribeCodexThreadBestEffort(
143183
client: CodexAppServerClient,

‎extensions/codex/src/app-server/protocol.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -653,6 +653,8 @@ export declare namespace v2 {
653653
}
654654

655655
type CodexAppServerRequestParamsOverride = {
656+
"thread/backgroundTerminals/list": { threadId: string; limit?: number };
657+
"thread/backgroundTerminals/terminate": { threadId: string; processId: string };
656658
"app/installed": CodexAppsInstalledParams;
657659
"app/list": CodexAppsListParams;
658660
"app/read": CodexAppsReadParams;
@@ -685,6 +687,8 @@ type CodexAppServerRequestParamsOverride = {
685687
};
686688

687689
type CodexAppServerRequestResultMap = {
690+
"thread/backgroundTerminals/list": { data: { processId: string }[] };
691+
"thread/backgroundTerminals/terminate": { terminated: boolean };
688692
initialize: CodexInitializeResponse;
689693
"account/rateLimits/read": JsonValue;
690694
"account/read": CodexGetAccountResponse;

‎extensions/codex/src/app-server/run-attempt-active-turn.ts‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@ import {
55
formatErrorMessage,
66
setActiveEmbeddedRun,
77
} from "openclaw/plugin-sdk/agent-harness-runtime";
8-
import { retireCodexAppServerClientAfterTimedOutTurn } from "./attempt-client-cleanup.js";
8+
import {
9+
retireCodexAppServerClientAfterTimedOutTurn,
10+
terminateCodexBackgroundTerminals,
11+
} from "./attempt-client-cleanup.js";
912
import { isTerminalTurnStatus } from "./attempt-notifications.js";
1013
import {
1114
CodexSteeringAcceptedUnconfirmedError,
@@ -390,7 +393,29 @@ export async function activateCodexAttemptTurn(
390393
})().finally(completeTurn);
391394
return;
392395
}
393-
void interruptTurn(activeTurnId).finally(completeTurn);
396+
const interrupted = interruptTurn(activeTurnId);
397+
if (terminalState.explicitCancellationObserved) {
398+
// turn/completed ends the turn, not its native background terminals.
399+
// Keep this attempt's route and lease until thread-scoped cleanup settles.
400+
state.abortCleanup = interrupted.then(async (confirmed) => {
401+
if (!confirmed) {
402+
throw new Error(
403+
"Codex cancellation could not confirm the turn stopped; background terminals may still be running.",
404+
);
405+
}
406+
await terminateCodexBackgroundTerminals(
407+
resourceState.client,
408+
resourceState.thread.threadId,
409+
);
410+
});
411+
}
412+
const cancellation = terminalState.explicitCancellationObserved
413+
? state.abortCleanup
414+
: interrupted;
415+
void cancellation.then(completeTurn, (error: unknown) => {
416+
embeddedAgentLog.warn("codex app-server cancellation cleanup failed", { error });
417+
completeTurn();
418+
});
394419
};
395420
runAbortController.signal.addEventListener("abort", abortListener, { once: true });
396421
if (runAbortController.signal.aborted) {

‎extensions/codex/src/app-server/run-attempt-cleanup.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,12 @@ export async function cleanupCodexAttempt(
4545
// Exact-thread cron authority exists only while this creator turn owns the
4646
// live client/thread. Retained model callbacks must fail after cleanup begins.
4747
prompt.context.attemptTools.scheduledAppAuthoritySourceRef.current = undefined;
48+
// Finalization can throw before freezing. Close cancellation admission before
49+
// any teardown await so it cannot replace the cleanup promise being joined.
50+
freezeRunTerminalOutcome();
51+
// Join late cancellation before releasing the subscription, but do not let a
52+
// failed terminal RPC skip resource cleanup. Surface that failure below.
53+
await state.abortCleanup.catch(() => undefined);
4854
try {
4955
steeringQueueRef.current?.cancel();
5056
if (params.isFinalFallbackAttempt !== false) {
@@ -195,12 +201,12 @@ export async function cleanupCodexAttempt(
195201
runAbortController.signal.removeEventListener("abort", abortListener);
196202
});
197203
await runCleanupStep("codex-steering-cancel", () => steeringQueueRef.current?.cancel());
198-
await runCleanupStep("codex-terminal-freeze", freezeRunTerminalOutcome);
199204
await runCleanupStep("codex-reply-backend-detach", () =>
200205
params.replyOperation?.detachBackend(handle),
201206
);
202207
await runCleanupStep("codex-active-run-clear", () => {
203208
clearActiveEmbeddedRun(params.sessionId, handle, params.sessionKey, params.sessionFile);
204209
});
205210
}
211+
await state.abortCleanup;
206212
}

‎extensions/codex/src/app-server/run-attempt-finalize.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ export async function finalizeCodexAttempt(
9393
notifyUserMessagePersisted,
9494
} = activeTurn;
9595
await completion;
96+
await state.abortCleanup;
9697
// Include projection work already queued when timeout completion wins.
9798
await drainNotificationQueue();
9899
const hasQuiescentCompletedAssistant =

‎extensions/codex/src/app-server/run-attempt-test-harness.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -625,6 +625,9 @@ export function createStartedThreadHarness(
625625
if (method === "turn/start") {
626626
return turnStartResult();
627627
}
628+
if (method === "thread/backgroundTerminals/list") {
629+
return { data: [], nextCursor: null };
630+
}
628631
return {};
629632
}, options);
630633
}

0 commit comments

Comments
 (0)