Skip to content

Commit 8ec4a05

Browse files
authored
fix(codex): keep stressed inference turns isolated and observable (#115893)
1 parent 095f30a commit 8ec4a05

9 files changed

Lines changed: 161 additions & 18 deletions

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,38 @@ describe("CodexAppServerClient", () => {
4949
expect(outbound.method).toBe("model/list");
5050
});
5151

52+
it("isolates synchronous notification handler failures", async () => {
53+
const warn = vi.spyOn(embeddedAgentLog, "warn").mockImplementation(() => undefined);
54+
const harness = createClientHarness();
55+
clients.push(harness.client);
56+
const error = new Error("notification observer failed");
57+
const receiveNotification = vi.fn();
58+
59+
harness.client.addNotificationHandler(() => {
60+
throw error;
61+
});
62+
harness.client.addNotificationHandler(receiveNotification);
63+
64+
const notification = {
65+
method: "item/agentMessage/delta",
66+
params: {
67+
threadId: "thread-1",
68+
turnId: "turn-1",
69+
itemId: "message-1",
70+
delta: "hello",
71+
},
72+
};
73+
74+
expect(() => harness.send(notification)).not.toThrow();
75+
expect(receiveNotification).toHaveBeenCalledWith(notification);
76+
expect(warn).toHaveBeenCalledWith("codex app-server notification handler failed", { error });
77+
78+
const request = harness.client.request("model/list", {});
79+
const outbound = JSON.parse(harness.writes[0] ?? "{}") as { id?: number };
80+
harness.send({ id: outbound.id, result: { models: [] } });
81+
await expect(request).resolves.toEqual({ models: [] });
82+
});
83+
5284
it("rejects unbounded guarded thread requests before acquiring the fence", async () => {
5385
const harness = createClientHarness();
5486
clients.push(harness.client);

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

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -929,9 +929,13 @@ export class CodexAppServerClient {
929929

930930
private handleNotification(notification: CodexServerNotification): void {
931931
for (const handler of this.notificationHandlers) {
932-
Promise.resolve(handler(notification)).catch((error: unknown) => {
932+
try {
933+
Promise.resolve(handler(notification)).catch((error: unknown) => {
934+
embeddedAgentLog.warn("codex app-server notification handler failed", { error });
935+
});
936+
} catch (error) {
933937
embeddedAgentLog.warn("codex app-server notification handler failed", { error });
934-
});
938+
}
935939
}
936940
}
937941

‎extensions/codex/src/app-server/context-engine-projection.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,18 @@ describe("projectContextEngineAssemblyForCodex", () => {
392392
);
393393
});
394394

395+
it.each([
396+
{ contextTokenBudget: 4_000, maxRenderedContextChars: 8_000 },
397+
{ contextTokenBudget: 8_000, maxRenderedContextChars: 16_000 },
398+
])(
399+
"keeps a $contextTokenBudget-token model within its reserved prompt budget",
400+
({ contextTokenBudget, maxRenderedContextChars }) => {
401+
expect(resolveCodexContextEngineProjectionMaxChars({ contextTokenBudget })).toBe(
402+
maxRenderedContextChars,
403+
);
404+
},
405+
);
406+
395407
it("applies configured reserve tokens to the scaled projection cap", () => {
396408
expect(
397409
resolveCodexContextEngineProjectionMaxChars({

‎extensions/codex/src/app-server/context-engine-projection.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -443,13 +443,10 @@ function hasMessageContent(message: AgentMessage): message is AgentMessage & { c
443443
}
444444

445445
function normalizeRenderedContextMaxChars(value: unknown): number {
446-
if (typeof value !== "number" || !Number.isFinite(value)) {
446+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
447447
return DEFAULT_RENDERED_CONTEXT_CHARS;
448448
}
449-
return Math.min(
450-
MAX_RENDERED_CONTEXT_CHARS,
451-
Math.max(DEFAULT_RENDERED_CONTEXT_CHARS, Math.floor(value)),
452-
);
449+
return Math.min(MAX_RENDERED_CONTEXT_CHARS, Math.max(1, Math.floor(value)));
453450
}
454451

455452
function resolveTextPartMaxChars(maxRenderedContextChars: number): number {

‎extensions/codex/src/app-server/event-projector-assistant.ts‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -315,13 +315,17 @@ export class CodexAssistantProjection {
315315
return;
316316
}
317317
const turnItems = turn.items ?? [];
318-
const authoritativeIndex = turnItems.findLastIndex(
319-
(item) =>
320-
item.type === "agentMessage" &&
321-
readItemString(item, "phase") === "final_answer" &&
322-
typeof item.text === "string" &&
323-
item.text.trim().length > 0,
324-
);
318+
const authoritativeIndex = turnItems.findLastIndex((item) => {
319+
if (
320+
item.type !== "agentMessage" ||
321+
typeof item.text !== "string" ||
322+
item.text.trim().length === 0
323+
) {
324+
return false;
325+
}
326+
const phase = readItemString(item, "phase");
327+
return phase === "final_answer" || phase === undefined;
328+
});
325329
const authoritative = authoritativeIndex >= 0 ? turnItems[authoritativeIndex] : undefined;
326330
const invalidatedByLaterTool = turnItems
327331
.slice(authoritativeIndex + 1)

‎extensions/codex/src/app-server/event-projector.assistant.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,40 @@ describe("CodexAppServerEventProjector assistant projection", () => {
263263
expect(candidateStatuses).toEqual(["candidate", "superseded"]);
264264
});
265265

266+
it("selects an unphased final answer supplied only by the completed-turn snapshot", async () => {
267+
const onAgentEvent = vi.fn();
268+
const projector = await createProjector({
269+
...(await createParams()),
270+
onAgentEvent,
271+
});
272+
273+
await projector.handleNotification(
274+
turnCompleted([{ type: "agentMessage", id: "answer-unphased", text: "done" }]),
275+
);
276+
277+
const result = projector.buildResult(buildEmptyToolTelemetry());
278+
expect(result.assistantTexts).toEqual(["done"]);
279+
expect(result.messagesSnapshot.at(-1)).toEqual(
280+
expect.objectContaining({
281+
role: "assistant",
282+
content: [{ type: "text", text: "done" }],
283+
}),
284+
);
285+
expect(
286+
onAgentEvent.mock.calls
287+
.map((call) => call[0])
288+
.filter((event) => event.stream === "item" && event.data.kind === "answer_candidate")
289+
.map((event) => event.data),
290+
).toEqual([
291+
expect.objectContaining({
292+
itemId: "answer-unphased",
293+
status: "selected",
294+
progressText: "done",
295+
hideFromChannelProgress: true,
296+
}),
297+
]);
298+
});
299+
266300
it("streams final-answer assistant deltas into partial replies", async () => {
267301
const onAgentEvent = vi.fn();
268302
const onPartialReply = vi.fn();

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,10 +127,14 @@ export async function cleanupCodexAttempt(
127127
if (!state.timedOut && !retainLiveThread) {
128128
// Clear first: if a newer owner won the binding, its live subscription must remain intact.
129129
if (bindingReleased) {
130-
await unsubscribeCodexThreadBestEffort(resourceState.client, {
130+
const released = await unsubscribeCodexThreadBestEffort(resourceState.client, {
131131
threadId: resourceState.thread.threadId,
132132
timeoutMs: CODEX_APP_SERVER_UNSUBSCRIBE_TIMEOUT_MS,
133133
});
134+
if (!released) {
135+
// Never reuse a client whose previous thread may still publish notifications.
136+
await closeCodexStartupClientBestEffort(resourceState.client);
137+
}
134138
}
135139
}
136140
userInputBridgeRef.current?.cancelPending();

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

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,4 +336,60 @@ describe("Codex app-server main thread cleanup", () => {
336336
);
337337
await expect(readCodexAppServerBinding(sessionFile)).resolves.toBeUndefined();
338338
});
339+
340+
it("retires a Codex client when a failed turn cannot unsubscribe its thread", async () => {
341+
const sessionFile = path.join(tempDir, "session.jsonl");
342+
const workspaceDir = path.join(tempDir, "workspace");
343+
const sessionKey = "agent:main:dashboard:incognito-failed-unsubscribe";
344+
const requests: string[] = [];
345+
const request = vi.fn(async (method: string) => {
346+
requests.push(method);
347+
if (method === "thread/start") {
348+
return threadStartResult();
349+
}
350+
if (method === "turn/start") {
351+
throw new Error("turn start exploded");
352+
}
353+
if (method === "thread/unsubscribe") {
354+
throw new Error("thread unsubscribe failed");
355+
}
356+
return {};
357+
});
358+
const createClient = vi.fn(async () => {
359+
return {
360+
...mockClientRuntimeMethods(),
361+
request,
362+
close: vi.fn(),
363+
addNotificationHandler: () => () => undefined,
364+
addRequestHandler: () => () => undefined,
365+
addCloseHandler: () => () => undefined,
366+
} as never;
367+
});
368+
const clientFactory: CodexAppServerClientFactory = multiplexedClientFactory(createClient);
369+
370+
await expect(
371+
runCodexAppServerAttempt(createParams(sessionFile, workspaceDir, sessionKey), {
372+
bindingStore: testCodexAppServerBindingStore,
373+
clientFactory,
374+
}),
375+
).rejects.toThrow("turn start exploded");
376+
377+
await expect(
378+
runCodexAppServerAttempt(createParams(sessionFile, workspaceDir, sessionKey), {
379+
bindingStore: testCodexAppServerBindingStore,
380+
clientFactory,
381+
}),
382+
).rejects.toThrow("turn start exploded");
383+
384+
expect(requests).toEqual([
385+
"thread/start",
386+
"turn/start",
387+
"thread/unsubscribe",
388+
"thread/start",
389+
"turn/start",
390+
"thread/unsubscribe",
391+
]);
392+
expect(createClient).toHaveBeenCalledTimes(2);
393+
await expect(readCodexAppServerBinding(sessionFile)).resolves.toBeUndefined();
394+
});
339395
});

‎src/cli/update-cli/shared.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ export function parseTimeoutMsOrExit(timeout?: string): number | undefined | nul
7777
const OPENCLAW_REPO_URL = "https://github.com/openclaw/openclaw.git";
7878
// Keep the full commit graph for dev ref switching while deferring historical blobs.
7979
// A shallow clone would make older or non-default dev targets unreachable.
80-
const OPENCLAW_CLONE_FILTER = "--filter=blob:none";
80+
const GIT_CLONE_BLOB_FILTER = "--filter=blob:none";
8181
const MAX_LOG_CHARS = 8000;
8282

8383
export const DEFAULT_PACKAGE_NAME = "openclaw";
@@ -254,7 +254,7 @@ export async function ensureGitCheckout(params: {
254254
await fs.mkdir(path.dirname(params.dir), { recursive: true });
255255
return await runUpdateStep({
256256
name: "git clone",
257-
argv: ["git", "clone", OPENCLAW_CLONE_FILTER, OPENCLAW_REPO_URL, params.dir],
257+
argv: ["git", "clone", GIT_CLONE_BLOB_FILTER, OPENCLAW_REPO_URL, params.dir],
258258
env: gitEnv,
259259
timeoutMs: params.timeoutMs,
260260
progress: params.progress,
@@ -271,7 +271,7 @@ export async function ensureGitCheckout(params: {
271271

272272
return await runUpdateStep({
273273
name: "git clone",
274-
argv: ["git", "clone", OPENCLAW_CLONE_FILTER, OPENCLAW_REPO_URL, params.dir],
274+
argv: ["git", "clone", GIT_CLONE_BLOB_FILTER, OPENCLAW_REPO_URL, params.dir],
275275
cwd: params.dir,
276276
env: gitEnv,
277277
timeoutMs: params.timeoutMs,

0 commit comments

Comments
 (0)