Skip to content

Commit cb16d73

Browse files
authored
fix(inference): harden Codex streaming, cancellation, and live QA (#116012)
* fix(inference): harden Codex turns, streams, and live QA * fix(inference): dispatch open CR-delimited response frames * fix(inference): finish live goal and split streaming regressions * fix(codex): wait for interrupted turn completion * fix(codex): narrow terminal collector notification ownership * fix(inference): harden completion authority and lifecycle * fix(inference): use canonical source delivery contract * test(inference): align lifecycle probes with current main * style(inference): format source delivery verification * fix(goals): prevent premature completion across staged work * fix(qa): settle streamed goal turns before continuation * fix(goals): require visible replies after goal completion * test(qa): keep goal flow regressions within lint limits
1 parent f9d2f0d commit cb16d73

117 files changed

Lines changed: 6030 additions & 733 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/tools/goal.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,14 +147,15 @@ target.
147147
`update_goal` should mark a goal `complete` only when the objective is
148148
actually achieved. It should mark a goal `blocked` only after the same
149149
blocking condition recurs for at least three consecutive goal turns, not for
150-
ordinary difficulty or missing polish.
150+
ordinary difficulty or missing polish. Updating goal status does not send a
151+
chat reply; the agent must still provide the user's requested final response.
151152

152153
## Goal context on every turn
153154

154155
Every user/chat turn with an active goal includes this user-role context line:
155156

156157
```text
157-
Active goal: <objective> — advance it or update its status (get_goal/update_goal).
158+
Active goal: <objective> — advance; keep active until fully achieved; block only after the same blocker on 3 consecutive turns; after update_goal, provide the requested visible final.
158159
```
159160

160161
OpenClaw keeps the line compact by truncating long objectives. Paused,

‎extensions/codex/media-understanding-provider.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,20 @@ function createFakeClient(options?: {
106106
if (method === "thread/start") {
107107
return threadStartResult();
108108
}
109+
if (method === "turn/interrupt") {
110+
queueMicrotask(() => {
111+
for (const notify of notifications) {
112+
notify({
113+
method: "turn/completed",
114+
params: {
115+
threadId: "thread-1",
116+
turn: turnStartResult("interrupted").turn,
117+
},
118+
});
119+
}
120+
});
121+
return {};
122+
}
109123
if (method === "turn/start") {
110124
options?.onTurnStart?.();
111125
if (options?.approvalRequestMethod) {
@@ -181,6 +195,7 @@ function createFakeClient(options?: {
181195
requestHandlers.add(handler);
182196
return () => requestHandlers.delete(handler);
183197
},
198+
addCloseHandler: () => () => undefined,
184199
close: vi.fn(),
185200
} as unknown as CodexAppServerClient;
186201

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

Lines changed: 134 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,120 @@
11
// Codex tests cover attempt client cleanup plugin behavior.
22
import { describe, expect, it, vi } from "vitest";
33
import {
4-
interruptCodexTurnBestEffort,
4+
interruptCodexTurnAndWaitBestEffort,
55
retireCodexAppServerClientAfterTimedOutTurn,
66
unsubscribeCodexThreadBestEffort,
77
} from "./attempt-client-cleanup.js";
8+
import { createClientHarness } from "./test-support.js";
89

910
describe("Codex app-server attempt client cleanup", () => {
10-
it("interrupts turns with optional request timeout", () => {
11-
const request = vi.fn(async () => ({}));
12-
13-
interruptCodexTurnBestEffort({ request } as never, {
11+
it("waits for the matching terminal after an interrupt is acknowledged", async () => {
12+
const harness = createClientHarness();
13+
const completion = interruptCodexTurnAndWaitBestEffort(harness.client, {
1414
threadId: "thread-1",
1515
turnId: "turn-1",
16-
timeoutMs: 123,
16+
timeoutMs: 1_000,
17+
});
18+
const settled = vi.fn();
19+
void completion.then(settled);
20+
const request = JSON.parse(harness.writes.at(-1) ?? "{}") as {
21+
id: number;
22+
method: string;
23+
params: Record<string, unknown>;
24+
};
25+
26+
expect(request).toMatchObject({
27+
method: "turn/interrupt",
28+
params: { threadId: "thread-1", turnId: "turn-1" },
29+
});
30+
harness.send({ id: request.id, result: {} });
31+
await Promise.resolve();
32+
expect(settled).not.toHaveBeenCalled();
33+
34+
harness.send({
35+
method: "turn/completed",
36+
params: {
37+
threadId: "thread-1",
38+
turn: { id: "turn-other", status: "interrupted" },
39+
},
40+
});
41+
await Promise.resolve();
42+
expect(settled).not.toHaveBeenCalled();
43+
44+
harness.send({
45+
method: "turn/completed",
46+
params: {
47+
threadId: "thread-1",
48+
turn: { id: "turn-1", status: "interrupted" },
49+
},
1750
});
1851

52+
await expect(completion).resolves.toBe(true);
53+
harness.client.close();
54+
});
55+
56+
it("retains the startup interrupt acknowledgement contract", async () => {
57+
const request = vi.fn(async () => ({}));
58+
59+
await expect(
60+
interruptCodexTurnAndWaitBestEffort({ request } as never, {
61+
threadId: "thread-1",
62+
turnId: "",
63+
timeoutMs: 123,
64+
}),
65+
).resolves.toBe(true);
66+
1967
expect(request).toHaveBeenCalledWith(
2068
"turn/interrupt",
21-
{ threadId: "thread-1", turnId: "turn-1" },
69+
{ threadId: "thread-1", turnId: "" },
2270
{ timeoutMs: 123 },
2371
);
2472
});
2573

74+
it("fails closed when acknowledged interruption never reaches its terminal", async () => {
75+
const harness = createClientHarness();
76+
const completion = interruptCodexTurnAndWaitBestEffort(harness.client, {
77+
threadId: "thread-1",
78+
turnId: "turn-1",
79+
timeoutMs: 10,
80+
});
81+
const request = JSON.parse(harness.writes.at(-1) ?? "{}") as { id: number };
82+
harness.send({ id: request.id, result: {} });
83+
84+
await expect(completion).resolves.toBe(false);
85+
harness.client.close();
86+
});
87+
88+
it.each([
89+
{
90+
name: "the exact already-terminal error",
91+
error: { code: -32_600, message: "no active turn to interrupt" },
92+
completed: true,
93+
},
94+
{
95+
name: "another invalid-request error",
96+
error: { code: -32_600, message: "expected another active turn" },
97+
completed: false,
98+
},
99+
{
100+
name: "the terminal message with another error code",
101+
error: { code: -32_000, message: "no active turn to interrupt" },
102+
completed: false,
103+
},
104+
])("classifies $name without waiting for a dropped terminal", async ({ error, completed }) => {
105+
const harness = createClientHarness();
106+
const completion = interruptCodexTurnAndWaitBestEffort(harness.client, {
107+
threadId: "thread-1",
108+
turnId: "turn-1",
109+
timeoutMs: 1_000,
110+
});
111+
const request = JSON.parse(harness.writes.at(-1) ?? "{}") as { id: number };
112+
harness.send({ id: request.id, error });
113+
114+
await expect(completion).resolves.toBe(completed);
115+
harness.client.close();
116+
});
117+
26118
it("swallows unsubscribe cleanup failures", async () => {
27119
const request = vi.fn(async () => {
28120
throw new Error("already gone");
@@ -43,15 +135,43 @@ describe("Codex app-server attempt client cleanup", () => {
43135
});
44136

45137
it("closes only the isolated client after timed-out turn cleanup", async () => {
46-
const request = vi.fn(async () => ({}));
138+
const notificationHandlers = new Set<(notification: unknown) => void>();
139+
const request = vi.fn(async (method: string) => {
140+
if (method === "turn/interrupt") {
141+
queueMicrotask(() => {
142+
for (const handler of notificationHandlers) {
143+
handler({
144+
method: "turn/completed",
145+
params: {
146+
threadId: "thread-1",
147+
turn: { id: "turn-1", status: "interrupted" },
148+
},
149+
});
150+
}
151+
});
152+
}
153+
return {};
154+
});
47155
const close = vi.fn();
48156

49-
await retireCodexAppServerClientAfterTimedOutTurn({ request, close } as never, {
50-
threadId: "thread-1",
51-
turnId: "turn-1",
52-
reason: "turn_terminal_idle_timeout",
53-
suspectPhysicalClient: true,
54-
});
157+
await retireCodexAppServerClientAfterTimedOutTurn(
158+
{
159+
request,
160+
close,
161+
addNotificationHandler: (handler: (notification: unknown) => void) => {
162+
notificationHandlers.add(handler);
163+
return () => notificationHandlers.delete(handler);
164+
},
165+
addRequestHandler: () => () => undefined,
166+
addCloseHandler: () => () => undefined,
167+
} as never,
168+
{
169+
threadId: "thread-1",
170+
turnId: "turn-1",
171+
reason: "turn_terminal_idle_timeout",
172+
suspectPhysicalClient: true,
173+
},
174+
);
55175

56176
expect(request).toHaveBeenCalledWith(
57177
"turn/interrupt",

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

Lines changed: 38 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,31 @@
22
* Best-effort cleanup helpers for Codex app-server startup attempts and turns.
33
*/
44
import { embeddedAgentLog } from "openclaw/plugin-sdk/agent-harness-runtime";
5-
import type { CodexAppServerClient } from "./client.js";
5+
import { CodexAppServerRpcError, type CodexAppServerClient } from "./client.js";
66
import {
77
clearSharedCodexAppServerClientIfCurrent,
88
clearSharedCodexAppServerClientIfCurrentAndUnclaimed,
99
retireSharedCodexAppServerClientIfCurrent,
1010
} from "./shared-client.js";
11+
import { getCodexAppServerTurnRouter } from "./turn-router.js";
1112

1213
/** Timeout for best-effort app-server turn interruption during cleanup. */
1314
export const CODEX_APP_SERVER_INTERRUPT_TIMEOUT_MS = 5_000;
1415
/** Timeout for best-effort thread unsubscribe during cleanup. */
1516
export const CODEX_APP_SERVER_UNSUBSCRIBE_TIMEOUT_MS = 5_000;
17+
const CODEX_NO_ACTIVE_TURN_ERROR_CODE = -32_600;
18+
const CODEX_NO_ACTIVE_TURN_ERROR_MESSAGE = "no active turn to interrupt";
19+
20+
/** Identifies Codex's exact proof that an interrupt target already finished. */
21+
export function isCodexAlreadyTerminalInterruptError(
22+
error: unknown,
23+
): error is CodexAppServerRpcError {
24+
return (
25+
error instanceof CodexAppServerRpcError &&
26+
error.code === CODEX_NO_ACTIVE_TURN_ERROR_CODE &&
27+
error.message === CODEX_NO_ACTIVE_TURN_ERROR_MESSAGE
28+
);
29+
}
1630

1731
/** Raised when a thread subscription may be live on a client OpenClaw no longer controls. */
1832
export class CodexAppServerUnsafeSubscriptionError extends Error {
@@ -84,18 +98,6 @@ export async function closeCodexStartupClientBestEffort(
8498
await closeClientAndWaitIfAvailable(client);
8599
}
86100

87-
/** Sends a turn interrupt without blocking abort cleanup on app-server errors. */
88-
export function interruptCodexTurnBestEffort(
89-
client: CodexAppServerClient,
90-
params: {
91-
threadId: string;
92-
turnId: string;
93-
timeoutMs?: number;
94-
},
95-
): void {
96-
void interruptCodexTurnAndWaitBestEffort(client, params);
97-
}
98-
99101
/** Sends a bounded turn interrupt and waits for Codex to confirm terminal abort handling. */
100102
export async function interruptCodexTurnAndWaitBestEffort(
101103
client: CodexAppServerClient,
@@ -104,20 +106,33 @@ export async function interruptCodexTurnAndWaitBestEffort(
104106
turnId: string;
105107
timeoutMs?: number;
106108
},
107-
): Promise<void> {
108-
const requestOptions =
109+
): Promise<boolean> {
110+
const timeoutMs =
109111
params.timeoutMs && Number.isFinite(params.timeoutMs) && params.timeoutMs > 0
110-
? { timeoutMs: params.timeoutMs }
111-
: undefined;
112+
? params.timeoutMs
113+
: CODEX_APP_SERVER_INTERRUPT_TIMEOUT_MS;
112114
const requestParams = { threadId: params.threadId, turnId: params.turnId };
115+
let completion: { completion: Promise<boolean>; cancel: () => void } | undefined;
113116
try {
114-
// Non-empty interrupts resolve after Codex emits TurnAborted; the empty
115-
// startup form resolves after Op::Interrupt is submitted because no turn exists yet.
116-
await (requestOptions
117-
? client.request("turn/interrupt", requestParams, requestOptions)
118-
: client.request("turn/interrupt", requestParams));
117+
// Codex acknowledges interruption before publishing turn/completed. Register
118+
// first so an immediate exact-turn terminal cannot race past its owner.
119+
completion = params.turnId
120+
? getCodexAppServerTurnRouter(client).watchNativeTurnCompletion({
121+
threadId: params.threadId,
122+
turnId: params.turnId,
123+
timeoutMs,
124+
})
125+
: undefined;
126+
await client.request("turn/interrupt", requestParams, { timeoutMs });
127+
return completion ? await completion.completion : true;
119128
} catch (error) {
129+
if (isCodexAlreadyTerminalInterruptError(error)) {
130+
return true;
131+
}
120132
embeddedAgentLog.debug("codex app-server turn interrupt failed during abort", { error });
133+
return false;
134+
} finally {
135+
completion?.cancel();
121136
}
122137
}
123138

@@ -173,7 +188,7 @@ export async function retireCodexAppServerClientAfterTimedOutTurn(
173188
// Best-effort interrupt/unsubscribe only make sense while the transport is
174189
// still open; a suspect client was just closed (child gets SIGKILLed).
175190
if (!clientAlreadyClosed) {
176-
interruptCodexTurnBestEffort(client, {
191+
await interruptCodexTurnAndWaitBestEffort(client, {
177192
threadId: params.threadId,
178193
turnId: params.turnId,
179194
timeoutMs: CODEX_APP_SERVER_INTERRUPT_TIMEOUT_MS,

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

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -439,7 +439,6 @@ export async function startCodexAttemptThread(params: {
439439
}
440440
startupReservation = turnRouter.reserveThread({
441441
threadId,
442-
releaseOn: params.signal,
443442
});
444443
return { release: releaseStartupReservation };
445444
};

0 commit comments

Comments
 (0)