Skip to content

Commit 500fd2c

Browse files
authored
refactor(codex): separate exec session transport (#126859)
1 parent a73166b commit 500fd2c

12 files changed

Lines changed: 393 additions & 338 deletions

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

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
} from "./config.js";
2222
import { createCodexTestHostCapabilities } from "./host-capability.test-support.js";
2323
import { defaultCodexPluginMetadataCache } from "./plugin-metadata-cache.js";
24+
import { sandboxExecServerRegistry } from "./sandbox-exec-server-registry.js";
2425
import { createSandboxContext } from "./sandbox-exec-server.test-helpers.js";
2526
import {
2627
resetCodexTestBindingStore,
@@ -723,7 +724,7 @@ describe("startCodexAttemptThread", () => {
723724
);
724725
});
725726

726-
it("requires app-server environment support for remote-exec placement", async () => {
727+
it("propagates environment registration failures for remote-exec placement", async () => {
727728
const sandbox = {
728729
...createSandboxContext({}),
729730
placementExecutionMode: "remote-exec" as const,
@@ -735,12 +736,11 @@ describe("startCodexAttemptThread", () => {
735736
const environmentAdd = await waitForRequest(harness, "environment/add");
736737
harness.send({
737738
id: environmentAdd.id,
738-
error: { code: -32601, message: "unknown variant environment/add" },
739+
error: { code: -32603, message: "environment registration failed" },
739740
});
740741

741-
await expect(run).rejects.toThrow(
742-
"Codex app-server did not register an OpenClaw sandbox exec-server environment.",
743-
);
742+
await expect(run).rejects.toThrow("environment registration failed");
743+
expect(sandboxExecServerRegistry.servers.has(sandbox.runtimeId)).toBe(false);
744744
expect(
745745
readHarnessMessages(harness.writes).some((entry) => entry.method === "thread/start"),
746746
).toBe(false);
Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,21 @@
11
// Codex tests cover sandbox exec server.json rpc plugin behavior.
22
import { describe, expect, it, vi } from "vitest";
3-
import type { WebSocket } from "ws";
43
import { sendResult } from "./sandbox-exec-server/json-rpc.js";
54

6-
function createSocket() {
7-
return {
8-
send: vi.fn(),
9-
} as unknown as WebSocket & { send: ReturnType<typeof vi.fn> };
10-
}
11-
12-
function sentJson(socket: ReturnType<typeof createSocket>) {
13-
return JSON.parse(String(socket.send.mock.calls[0]?.[0])) as unknown;
14-
}
15-
165
describe("sandbox exec-server JSON-RPC helpers", () => {
176
it("preserves explicit null results", () => {
18-
const socket = createSocket();
7+
const send = vi.fn();
198

20-
sendResult(socket, 1, null);
9+
sendResult(send, 1, null);
2110

22-
expect(sentJson(socket)).toEqual({ jsonrpc: "2.0", id: 1, result: null });
11+
expect(send).toHaveBeenCalledWith({ jsonrpc: "2.0", id: 1, result: null });
2312
});
2413

2514
it("keeps undefined results as empty objects for methods without bodies", () => {
26-
const socket = createSocket();
15+
const send = vi.fn();
2716

28-
sendResult(socket, 2, undefined);
17+
sendResult(send, 2, undefined);
2918

30-
expect(sentJson(socket)).toEqual({ jsonrpc: "2.0", id: 2, result: {} });
19+
expect(send).toHaveBeenCalledWith({ jsonrpc: "2.0", id: 2, result: {} });
3120
});
3221
});

‎extensions/codex/src/app-server/sandbox-exec-server.lifecycle.test.ts‎

Lines changed: 110 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import { EventEmitter } from "node:events";
44
import { PassThrough } from "node:stream";
55
import type { SandboxContext } from "openclaw/plugin-sdk/sandbox";
66
import { afterEach, describe, expect, it, vi } from "vitest";
7-
import type { WebSocket } from "ws";
87

98
const spawnMock = vi.hoisted(() => vi.fn());
109
const killProcessTreeMock = vi.hoisted(() => vi.fn());
@@ -26,9 +25,17 @@ vi.mock("openclaw/plugin-sdk/process-runtime", async (importOriginal) => {
2625
import { createSandboxContext } from "./sandbox-exec-server.test-helpers.js";
2726
import { httpRequest } from "./sandbox-exec-server/http.js";
2827
import { startProcess, terminateProcess } from "./sandbox-exec-server/processes.js";
29-
import type { ManagedProcess, OpenClawExecServer } from "./sandbox-exec-server/types.js";
30-
31-
type FakeSocket = WebSocket & { send: ReturnType<typeof vi.fn> };
28+
import { CodexSandboxExecSession } from "./sandbox-exec-server/session.js";
29+
import type {
30+
CodexSandboxExecSessionNotifications,
31+
ManagedProcess,
32+
OpenClawExecServer,
33+
} from "./sandbox-exec-server/types.js";
34+
35+
type FakeNotifications = CodexSandboxExecSessionNotifications & {
36+
send: ReturnType<typeof vi.fn<CodexSandboxExecSessionNotifications["send"]>>;
37+
close: () => void;
38+
};
3239

3340
function createFakeChild(): ChildProcessWithoutNullStreams {
3441
return Object.assign(new EventEmitter(), {
@@ -40,15 +47,24 @@ function createFakeChild(): ChildProcessWithoutNullStreams {
4047
}) as unknown as ChildProcessWithoutNullStreams;
4148
}
4249

43-
function createFakeSocket(): FakeSocket {
44-
return Object.assign(new EventEmitter(), {
45-
readyState: 1,
46-
send: vi.fn(),
47-
}) as unknown as FakeSocket;
50+
function createFakeNotifications(): FakeNotifications {
51+
const controller = new AbortController();
52+
return {
53+
send: vi.fn<CodexSandboxExecSessionNotifications["send"]>(),
54+
isOpen: () => !controller.signal.aborted,
55+
signal: controller.signal,
56+
close: () => controller.abort(),
57+
};
4858
}
4959

5060
function createExecServer(sandbox: SandboxContext): OpenClawExecServer {
51-
return { sandbox, children: new Set(), cleanupTasks: new Set() } as OpenClawExecServer;
61+
return {
62+
sandbox,
63+
backend: sandbox.backend,
64+
fsBridge: sandbox.fsBridge,
65+
children: new Set(),
66+
cleanupTasks: new Set(),
67+
} as OpenClawExecServer;
5268
}
5369

5470
function processStartParams(processId: string) {
@@ -79,6 +95,76 @@ afterEach(() => {
7995
});
8096

8197
describe("Codex sandbox exec-server lifecycle", () => {
98+
it("owns JSON-RPC delivery, ordered process notifications, and idempotent session cleanup", async () => {
99+
const child = createFakeChild();
100+
spawnMock.mockReturnValue(child);
101+
const finalizeExec = vi.fn(async () => undefined);
102+
const sandbox = createSandboxContext({
103+
buildExecSpec: async () => ({
104+
argv: ["sandbox-child"],
105+
env: {},
106+
finalizeToken: "session-token",
107+
stdinMode: "pipe-closed",
108+
}),
109+
finalizeExec,
110+
});
111+
const send = vi.fn();
112+
const session = new CodexSandboxExecSession(createExecServer(sandbox), {
113+
send,
114+
isOpen: () => true,
115+
});
116+
117+
await session.handleRequest({ id: 1, method: "initialize" });
118+
await session.handleRequest({ id: 2, method: "environment/status" });
119+
await session.handleRequest({ id: 3, method: "unsupported/method" });
120+
await session.handleRequest({
121+
id: 4,
122+
method: "process/start",
123+
params: processStartParams("direct-session"),
124+
});
125+
(child.stdout as PassThrough).write(Buffer.from("session-output"));
126+
child.emit("close", 0, null);
127+
await vi.waitFor(() => expect(finalizeExec).toHaveBeenCalledOnce());
128+
129+
expect(send.mock.calls.map(([message]) => message)).toEqual([
130+
{ jsonrpc: "2.0", id: 1, result: { sessionId: expect.any(String) } },
131+
{ jsonrpc: "2.0", id: 2, result: { status: "ready" } },
132+
{
133+
jsonrpc: "2.0",
134+
id: 3,
135+
error: {
136+
code: -32601,
137+
message: "Unsupported OpenClaw sandbox exec-server method: unsupported/method",
138+
},
139+
},
140+
{ jsonrpc: "2.0", id: 4, result: { processId: "direct-session" } },
141+
{
142+
jsonrpc: "2.0",
143+
method: "process/output",
144+
params: {
145+
processId: "direct-session",
146+
seq: 1,
147+
stream: "stdout",
148+
chunk: Buffer.from("session-output").toString("base64"),
149+
},
150+
},
151+
{
152+
jsonrpc: "2.0",
153+
method: "process/exited",
154+
params: { processId: "direct-session", seq: 2, exitCode: 0 },
155+
},
156+
{
157+
jsonrpc: "2.0",
158+
method: "process/closed",
159+
params: { processId: "direct-session", seq: 3 },
160+
},
161+
]);
162+
const cleanup = session.close();
163+
expect(session.close()).toBe(cleanup);
164+
await cleanup;
165+
expect(finalizeExec).toHaveBeenCalledOnce();
166+
});
167+
82168
it("reaps and finalizes a TERM-resistant child before acknowledging termination", async () => {
83169
vi.useFakeTimers();
84170
const child = createFakeChild();
@@ -103,7 +189,7 @@ describe("Codex sandbox exec-server lifecycle", () => {
103189
await startProcess(
104190
createExecServer(sandbox),
105191
processes,
106-
createFakeSocket(),
192+
createFakeNotifications().send,
107193
processStartParams("process-resistant"),
108194
);
109195
killProcessTreeMock.mockImplementation(() => {
@@ -158,7 +244,7 @@ describe("Codex sandbox exec-server lifecycle", () => {
158244
}),
159245
),
160246
processes,
161-
createFakeSocket(),
247+
createFakeNotifications().send,
162248
processStartParams("process-cooperative"),
163249
);
164250

@@ -197,7 +283,7 @@ describe("Codex sandbox exec-server lifecycle", () => {
197283
}),
198284
),
199285
processes,
200-
createFakeSocket(),
286+
createFakeNotifications().send,
201287
processStartParams("process-race"),
202288
);
203289

@@ -233,7 +319,7 @@ describe("Codex sandbox exec-server lifecycle", () => {
233319
}),
234320
),
235321
processes,
236-
createFakeSocket(),
322+
createFakeNotifications().send,
237323
processStartParams("process-survivor"),
238324
);
239325

@@ -255,7 +341,7 @@ describe("Codex sandbox exec-server lifecycle", () => {
255341
setTimeout(() => child.emit("close", null, "SIGKILL"), 1_000);
256342
});
257343
const finalizeExec = vi.fn(async () => undefined);
258-
const socket = createFakeSocket();
344+
const notifications = createFakeNotifications();
259345
const request = httpRequest(
260346
createExecServer(
261347
createSandboxContext({
@@ -268,7 +354,7 @@ describe("Codex sandbox exec-server lifecycle", () => {
268354
finalizeExec,
269355
}),
270356
),
271-
socket,
357+
notifications,
272358
streamingHttpParams("http-resistant"),
273359
);
274360
await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledOnce());
@@ -277,7 +363,7 @@ describe("Codex sandbox exec-server lifecycle", () => {
277363
);
278364
await expect(request).resolves.toEqual({ status: 200, headers: [], bodyBase64: "" });
279365

280-
socket.emit("close");
366+
notifications.close();
281367
await vi.runOnlyPendingTimersAsync();
282368

283369
expect(killProcessTreeMock).toHaveBeenCalledOnce();
@@ -303,13 +389,13 @@ describe("Codex sandbox exec-server lifecycle", () => {
303389
}),
304390
finalizeExec,
305391
});
306-
const socket = createFakeSocket();
392+
const notifications = createFakeNotifications();
307393
const processes = new Map<string, ManagedProcess>();
308394

309395
await startProcess(
310396
createExecServer(sandbox),
311397
processes,
312-
socket,
398+
notifications.send,
313399
processStartParams("process-error"),
314400
);
315401
child.emit("error", new Error("child transport failed"));
@@ -321,7 +407,7 @@ describe("Codex sandbox exec-server lifecycle", () => {
321407
failure: "child transport failed",
322408
});
323409
expect(finalizeExec).not.toHaveBeenCalled();
324-
expect(socket.send).not.toHaveBeenCalled();
410+
expect(notifications.send).not.toHaveBeenCalled();
325411

326412
child.emit("close", 23, null);
327413
await vi.waitFor(() => expect(finalizeExec).toHaveBeenCalledOnce());
@@ -337,7 +423,7 @@ describe("Codex sandbox exec-server lifecycle", () => {
337423
timedOut: false,
338424
token: "process-token",
339425
});
340-
expect(socket.send.mock.calls.map(([payload]) => JSON.parse(String(payload)).method)).toEqual([
426+
expect(notifications.send.mock.calls.map(([method]) => method)).toEqual([
341427
"process/exited",
342428
"process/closed",
343429
]);
@@ -367,7 +453,7 @@ describe("Codex sandbox exec-server lifecycle", () => {
367453
startProcess(
368454
createExecServer(sandbox),
369455
new Map(),
370-
createFakeSocket(),
456+
createFakeNotifications().send,
371457
processStartParams("process-start-failure"),
372458
),
373459
).rejects.toThrow(spawnError ?? "did not provide a command");
@@ -395,7 +481,7 @@ describe("Codex sandbox exec-server lifecycle", () => {
395481
});
396482
const request = httpRequest(
397483
createExecServer(sandbox),
398-
createFakeSocket(),
484+
createFakeNotifications(),
399485
streamingHttpParams("http-error"),
400486
);
401487
let settled = false;
@@ -455,7 +541,7 @@ describe("Codex sandbox exec-server lifecycle", () => {
455541
await expect(
456542
httpRequest(
457543
createExecServer(sandbox),
458-
createFakeSocket(),
544+
createFakeNotifications(),
459545
streamingHttpParams("http-start-failure"),
460546
),
461547
).rejects.toThrow(spawnError ?? "did not provide a command");

‎extensions/codex/src/app-server/sandbox-exec-server.test.ts‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,12 +66,24 @@ async function readStartedPid(
6666
}
6767

6868
describe("OpenClaw Codex sandbox exec-server", () => {
69-
it("reports unavailable app-server remote environment support without exposing an environment", async () => {
69+
it("rejects an incomplete sandbox environment before publishing an exec-server", async () => {
70+
const sandbox = createSandboxContext({});
71+
sandbox.fsBridge = undefined;
72+
const client = createClient();
73+
74+
await expect(
75+
ensureCodexSandboxExecServerEnvironment({ client: client as never, sandbox }),
76+
).rejects.toThrow("Sandbox filesystem bridge is unavailable.");
77+
expect(client.request).not.toHaveBeenCalled();
78+
expect(sandboxExecServerRegistry.servers.has(sandbox.runtimeId)).toBe(false);
79+
});
80+
81+
it("propagates environment registration failures and releases the server lease", async () => {
7082
const sandbox = createSandboxContext({});
7183
const client = {
7284
getServerVersion: vi.fn(() => CODEX_APP_SERVER_VERSION),
7385
request: vi.fn(async () => {
74-
throw new Error("unknown variant environment/add");
86+
throw new Error("environment registration failed");
7587
}),
7688
};
7789

@@ -80,7 +92,8 @@ describe("OpenClaw Codex sandbox exec-server", () => {
8092
client: client as never,
8193
sandbox,
8294
}),
83-
).resolves.toBeUndefined();
95+
).rejects.toThrow("environment registration failed");
96+
expect(sandboxExecServerRegistry.servers.has(sandbox.runtimeId)).toBe(false);
8497
});
8598

8699
it.each([

0 commit comments

Comments
 (0)