Skip to content

Commit b661be4

Browse files
committed
fix(codex): reap orphaned app-servers before reconnect
1 parent 32bd160 commit b661be4

19 files changed

Lines changed: 747 additions & 178 deletions

‎docs/plugins/codex-harness-runtime.md‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,34 @@ marked `catalogMode: "direct-only"` use `openclaw_direct`, which Codex keeps
6969
directly model-visible as `DirectModelOnly` instead of exposing it to nested
7070
Code Mode execution.
7171

72+
## Recovery after a hard Gateway stop
73+
74+
On POSIX systems, OpenClaw checks for registered orphaned Codex app-server
75+
processes before spawning each fresh stdio child. This runs when the connection
76+
is needed, not necessarily at Gateway boot. OpenClaw records the parent and
77+
child process identities in the current state directory's SQLite plugin store
78+
before sending Codex `initialize`, so a child cannot start a native turn before
79+
its registration is durable.
80+
81+
Cleanup only targets a registered child whose original OpenClaw parent is no
82+
longer running. It checks process IDs, start times, and process groups before
83+
terminating the orphan and its discoverable descendants. Another live OpenClaw
84+
instance, processes registered under another state directory, and externally
85+
managed WebSocket or Unix-socket app-servers are left alone. These portable
86+
process checks do not provide an atomic operating-system ownership guarantee
87+
or discover descendants that independently reparented before inspection.
88+
89+
If process inspection or bounded cleanup cannot confirm that the registered
90+
orphan is gone, the new stdio connection fails instead of spawning another
91+
child. Follow the reported action: check that `ps` works, or verify and stop
92+
the reported orphan process, then retry. If the cleanup budget expires, retry
93+
to finish the remaining registrations.
94+
95+
This recovery requires a spawn-time registration. It does not discover
96+
unregistered children left by an older OpenClaw version or scan command names
97+
to infer ownership. Windows does not yet have equivalent orphan registration
98+
and recovery.
99+
72100
## Thread bindings and model changes
73101

74102
When an OpenClaw session is attached to an existing Codex thread, the next

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

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ function startThreadWithHarness(
161161
const paths = overrides?.paths ?? createAttemptPaths();
162162
const startSpy = overrides?.skipStartSpy
163163
? undefined
164-
: vi.spyOn(CodexAppServerClient, "start").mockReturnValue(harness.client);
164+
: vi.spyOn(CodexAppServerClient, "start").mockResolvedValue(harness.client);
165165
const effectivePluginConfig = overrides?.pluginConfig ?? pluginConfig;
166166

167167
const run = startCodexAttemptThread({
@@ -383,8 +383,8 @@ describe("startCodexAttemptThread", () => {
383383
};
384384
const startSpy = vi
385385
.spyOn(CodexAppServerClient, "start")
386-
.mockReturnValueOnce(first.client)
387-
.mockReturnValueOnce(second.client);
386+
.mockResolvedValueOnce(first.client)
387+
.mockResolvedValueOnce(second.client);
388388
const paths = createAttemptPaths();
389389
let persistedComputerUse = false;
390390
const { run } = startThreadWithHarness(10_000, new AbortController().signal, {
@@ -455,8 +455,8 @@ describe("startCodexAttemptThread", () => {
455455
const second = createClientHarness();
456456
const startSpy = vi
457457
.spyOn(CodexAppServerClient, "start")
458-
.mockReturnValueOnce(first.client)
459-
.mockReturnValueOnce(second.client);
458+
.mockResolvedValueOnce(first.client)
459+
.mockResolvedValueOnce(second.client);
460460
desktopGeneration.current = { epoch: 1, fingerprint: "desktop-x" };
461461
if (changeStage === "Computer Use readiness") {
462462
computerUseReadinessFailure.next = Object.assign(new Error("desktop selection changed"), {
@@ -511,7 +511,7 @@ describe("startCodexAttemptThread", () => {
511511

512512
it("retires the startup generation when context restart sees a new executable owner", async () => {
513513
const harness = createClientHarness();
514-
vi.spyOn(CodexAppServerClient, "start").mockReturnValue(harness.client);
514+
vi.spyOn(CodexAppServerClient, "start").mockResolvedValue(harness.client);
515515
const paths = createAttemptPaths();
516516
const { run } = startThreadWithHarness(5_000, new AbortController().signal, {
517517
harness,
@@ -547,8 +547,8 @@ describe("startCodexAttemptThread", () => {
547547
const replacement = createClientHarness();
548548
const startSpy = vi
549549
.spyOn(CodexAppServerClient, "start")
550-
.mockReturnValueOnce(retained.client)
551-
.mockReturnValueOnce(replacement.client);
550+
.mockResolvedValueOnce(retained.client)
551+
.mockResolvedValueOnce(replacement.client);
552552
const appServer = resolveCodexAppServerRuntimeOptions({ pluginConfig });
553553
const paths = createAttemptPaths();
554554

@@ -610,7 +610,7 @@ describe("startCodexAttemptThread", () => {
610610

611611
it("closes indeterminate thread startup even when another lease shares the app-server", async () => {
612612
const retained = createClientHarness();
613-
vi.spyOn(CodexAppServerClient, "start").mockReturnValue(retained.client);
613+
vi.spyOn(CodexAppServerClient, "start").mockResolvedValue(retained.client);
614614
const appServer = resolveCodexAppServerRuntimeOptions({ pluginConfig });
615615
const paths = createAttemptPaths();
616616

@@ -798,7 +798,7 @@ describe("startCodexAttemptThread", () => {
798798
const clients = [createClientHarness(), createClientHarness(), createClientHarness()];
799799
const start = vi.spyOn(CodexAppServerClient, "start");
800800
for (const harness of clients) {
801-
start.mockReturnValueOnce(harness.client);
801+
start.mockResolvedValueOnce(harness.client);
802802
}
803803
const environmentIds = new Set<string>();
804804

@@ -831,7 +831,7 @@ describe("startCodexAttemptThread", () => {
831831
const runtime = createPairedAttemptRuntime();
832832
const firstPaths = createAttemptPaths();
833833
const secondPaths = createAttemptPaths();
834-
const start = vi.spyOn(CodexAppServerClient, "start").mockImplementation((options) => {
834+
const start = vi.spyOn(CodexAppServerClient, "start").mockImplementation(async (options) => {
835835
const codexHome = options?.env?.CODEX_HOME;
836836
if (codexHome?.startsWith(`${firstPaths.agentDir}${path.sep}`)) {
837837
return first.client;

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,10 @@ export class CodexAppServerClient {
273273
}
274274

275275
/** Starts a new app-server client using resolved runtime start options. */
276-
static start(options?: Partial<CodexAppServerStartOptions>): CodexAppServerClient {
276+
static async start(
277+
options?: Partial<CodexAppServerStartOptions>,
278+
assertCurrent?: () => void,
279+
): Promise<CodexAppServerClient> {
277280
const defaults = resolveCodexAppServerRuntimeOptions().start;
278281
const startOptions = {
279282
...defaults,
@@ -286,7 +289,9 @@ export class CodexAppServerClient {
286289
if (startOptions.transport === "websocket" || startOptions.transport === "unix") {
287290
return new CodexAppServerClient(createWebSocketTransport(startOptions));
288291
}
289-
return new CodexAppServerClient(createStdioTransport(startOptions));
292+
return new CodexAppServerClient(
293+
await createStdioTransport(startOptions, process.env, assertCurrent),
294+
);
290295
}
291296

292297
/** Builds a client around a fake transport for tests. */

‎extensions/codex/src/app-server/models.test.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ describe("listCodexAppServerModels", () => {
166166
},
167167
])("rejects $label through the app-server JSON-RPC boundary", async ({ response }) => {
168168
const harness = createClientHarness();
169-
const startSpy = vi.spyOn(CodexAppServerClient, "start").mockReturnValue(harness.client);
169+
const startSpy = vi.spyOn(CodexAppServerClient, "start").mockResolvedValue(harness.client);
170170

171171
const listPromise = listCodexAppServerModels({ timeoutMs: 1000 });
172172
await vi.waitFor(() => expect(harness.writes.length).toBeGreaterThanOrEqual(1));
@@ -187,7 +187,7 @@ describe("listCodexAppServerModels", () => {
187187

188188
it("lists app-server models through the typed helper", async () => {
189189
const harness = createClientHarness();
190-
const startSpy = vi.spyOn(CodexAppServerClient, "start").mockReturnValue(harness.client);
190+
const startSpy = vi.spyOn(CodexAppServerClient, "start").mockResolvedValue(harness.client);
191191

192192
const listPromise = listCodexAppServerModels({ limit: 12, timeoutMs: 1000 });
193193
await vi.waitFor(() => expect(harness.writes.length).toBeGreaterThanOrEqual(1));
@@ -257,7 +257,7 @@ describe("listCodexAppServerModels", () => {
257257

258258
it("lists all app-server model pages through one client", async () => {
259259
const harness = createClientHarness();
260-
const startSpy = vi.spyOn(CodexAppServerClient, "start").mockReturnValue(harness.client);
260+
const startSpy = vi.spyOn(CodexAppServerClient, "start").mockResolvedValue(harness.client);
261261

262262
const listPromise = listAllCodexAppServerModels({ limit: 1, timeoutMs: 1000 });
263263
await vi.waitFor(() => expect(harness.writes.length).toBeGreaterThanOrEqual(1));
@@ -337,7 +337,7 @@ describe("listCodexAppServerModels", () => {
337337

338338
it("marks all-model listing truncated after the page cap", async () => {
339339
const harness = createClientHarness();
340-
const startSpy = vi.spyOn(CodexAppServerClient, "start").mockReturnValue(harness.client);
340+
const startSpy = vi.spyOn(CodexAppServerClient, "start").mockResolvedValue(harness.client);
341341

342342
const listPromise = listAllCodexAppServerModels({ limit: 1, timeoutMs: 1000, maxPages: 1 });
343343
await vi.waitFor(() => expect(harness.writes.length).toBeGreaterThanOrEqual(1));

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

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ describe("Codex app-server main thread cleanup", () => {
188188
b: path.join(tempDir, "session-b.jsonl"),
189189
};
190190
const harness = createClientHarness();
191-
vi.spyOn(CodexAppServerClient, "start").mockReturnValue(harness.client);
191+
vi.spyOn(CodexAppServerClient, "start").mockResolvedValue(harness.client);
192192

193193
for (const [index, label] of (["a", "b", "a", "b"] as const).entries()) {
194194
const sessionKey = `agent:main:session-${label}`;
@@ -284,7 +284,7 @@ describe("Codex app-server main thread cleanup", () => {
284284

285285
it("preserves a quiet long-running native tool while a distinct shared-client turn completes", async () => {
286286
const physical = createClientHarness();
287-
const startClient = vi.spyOn(CodexAppServerClient, "start").mockReturnValue(physical.client);
287+
const startClient = vi.spyOn(CodexAppServerClient, "start").mockResolvedValue(physical.client);
288288
const firstParams = createParams(
289289
path.join(tempDir, "concurrent-first.jsonl"),
290290
path.join(tempDir, "concurrent-first-workspace"),
@@ -441,7 +441,7 @@ describe("Codex app-server main thread cleanup", () => {
441441
const workspaceDir = path.join(tempDir, "incognito-workspace");
442442
const sessionKey = "agent:main:dashboard:incognito-live-thread";
443443
const harness = createClientHarness();
444-
vi.spyOn(CodexAppServerClient, "start").mockReturnValueOnce(harness.client);
444+
vi.spyOn(CodexAppServerClient, "start").mockResolvedValueOnce(harness.client);
445445
const run = runCodexAppServerAttempt(createParams(sessionFile, workspaceDir, sessionKey), {
446446
bindingStore: testCodexAppServerBindingStore,
447447
});
@@ -547,7 +547,7 @@ describe("Codex app-server main thread cleanup", () => {
547547
const workspaceDir = path.join(tempDir, "cancelled-start-workspace");
548548
const harness = createClientHarness();
549549
const abort = new AbortController();
550-
vi.spyOn(CodexAppServerClient, "start").mockReturnValueOnce(harness.client);
550+
vi.spyOn(CodexAppServerClient, "start").mockResolvedValueOnce(harness.client);
551551

552552
const params = createParams(sessionFile, workspaceDir);
553553
params.abortSignal = abort.signal;
@@ -655,7 +655,7 @@ describe("Codex app-server main thread cleanup", () => {
655655
const harness = createClientHarness();
656656
const abort = new AbortController();
657657
const close = vi.spyOn(harness.client, "close");
658-
vi.spyOn(CodexAppServerClient, "start").mockReturnValueOnce(harness.client);
658+
vi.spyOn(CodexAppServerClient, "start").mockResolvedValueOnce(harness.client);
659659

660660
const params = createParams(sessionFile, workspaceDir, sessionKey);
661661
params.abortSignal = abort.signal;
@@ -759,7 +759,7 @@ describe("Codex app-server main thread cleanup", () => {
759759

760760
it("rejects late cancellation after failed finalization enters cleanup", async () => {
761761
const harness = createClientHarness();
762-
vi.spyOn(CodexAppServerClient, "start").mockReturnValueOnce(harness.client);
762+
vi.spyOn(CodexAppServerClient, "start").mockResolvedValueOnce(harness.client);
763763
const abort = new AbortController();
764764
const params = createParams(
765765
path.join(tempDir, "failed-finalization.jsonl"),
@@ -803,8 +803,8 @@ describe("Codex app-server main thread cleanup", () => {
803803
const replacement = createClientHarness();
804804
const startClient = vi
805805
.spyOn(CodexAppServerClient, "start")
806-
.mockReturnValueOnce(contaminated.client)
807-
.mockReturnValueOnce(replacement.client);
806+
.mockResolvedValueOnce(contaminated.client)
807+
.mockResolvedValueOnce(replacement.client);
808808

809809
const failedRun = runCodexAppServerAttempt(
810810
createParams(sessionFile, workspaceDir, sessionKey),

0 commit comments

Comments
 (0)