Skip to content

Commit 353b4b8

Browse files
authored
fix(agents): settle nested code mode bridge calls (#128440)
1 parent 2480a52 commit 353b4b8

7 files changed

Lines changed: 370 additions & 63 deletions

‎src/agents/agent-tools.abort.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ function throwAbortError(): never {
2424
* Tool settlements pass through untouched to preserve tool error semantics,
2525
* including non-Error rejections.
2626
*/
27-
function raceWithAbortSignal<T>(
27+
export function raceWithAbortSignal<T>(
2828
promise: Promise<T>,
2929
signal: AbortSignal,
3030
yieldRunSignal?: AbortSignal,

‎src/agents/code-mode-state.ts‎

Lines changed: 33 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
isFutureDateTimestampMs,
44
resolveExpiresAtMsFromDurationSeconds,
55
} from "@openclaw/normalization-core/number-coercion";
6+
import { raceWithAbortSignal } from "./agent-tools.abort.js";
67
import { runBridgeRequest } from "./code-mode-bridge.js";
78
import type { CodeModeCatalogProjection } from "./code-mode-catalog.js";
89
import { CODE_MODE_EXEC_TOOL_NAME, CODE_MODE_WAIT_TOOL_NAME } from "./code-mode-control-tools.js";
@@ -56,6 +57,7 @@ type CodeModeRunState = {
5657

5758
const MAX_ACTIVE_CODE_MODE_RUNS = 64;
5859
const MAX_AGENT_WAIT_SNAPSHOT_TTL_WINDOWS = 4;
60+
const BRIDGE_CLOSED_MESSAGE = "Code Mode tool canceled, expired, or owner lost; start a new run.";
5961

6062
export const activeRuns = new Map<string, CodeModeRunState>();
6163
export const resumingRunIds = new Set<string>();
@@ -158,16 +160,8 @@ export function cancelPendingBridgeStatesById(
158160
return;
159161
}
160162
const canceled = new Set(canceledRequestIds);
161-
const retained = pending.filter((entry) => {
162-
if (!canceled.has(entry.id)) {
163-
return true;
164-
}
165-
if (!entry.settled) {
166-
entry.cancel?.();
167-
}
168-
return false;
169-
});
170-
pending.splice(0, pending.length, ...retained);
163+
cancelPendingBridgeStates(pending.filter((entry) => canceled.has(entry.id)));
164+
pending.splice(0, pending.length, ...pending.filter((entry) => !canceled.has(entry.id)));
171165
}
172166

173167
/** Deliver bridge responses in actual settlement order, not request order. */
@@ -351,9 +345,13 @@ export function createPendingBridgeStates(params: {
351345
// Bridge calls start immediately while the VM snapshot is stored. Their
352346
// settled values are later replayed into QuickJS by the wait tool.
353347
const abortController = new AbortController();
354-
const signal = params.signal
355-
? AbortSignal.any([params.signal, abortController.signal])
356-
: abortController.signal;
348+
const signal = AbortSignal.any(
349+
[params.signal, params.ctx.abortSignal, abortController.signal].filter(
350+
(candidate): candidate is AbortSignal => candidate !== undefined,
351+
),
352+
);
353+
const target = params.catalogProjection.byCallableName.get(String(request.args[0]));
354+
const yieldRunSignal = target?.name === "sessions_yield" ? params.ctx.abortSignal : undefined;
357355
const tracksDispatch = request.method !== "sleep";
358356
if (tracksDispatch) {
359357
params.bridgeDispatch.started = true;
@@ -362,21 +360,29 @@ export function createPendingBridgeStates(params: {
362360
params.bridgeDispatch.repairProvenance = "invalid";
363361
}
364362
}
363+
const bridgeCall = runBridgeRequest({
364+
runtime: params.runtime,
365+
catalogProjection: params.catalogProjection,
366+
namespaceRuntime: params.namespaceRuntime,
367+
parentToolCallId: params.parentToolCallId,
368+
codeModeRunId: params.codeModeRunId,
369+
maxOutputBytes: params.config.maxOutputBytes,
370+
remainingMs: Math.max(1, params.deadlineMs - Date.now()),
371+
ctx: params.ctx,
372+
request,
373+
signal,
374+
onUpdate: params.onUpdate,
375+
});
376+
const completion = raceWithAbortSignal(bridgeCall, signal, yieldRunSignal).catch(
377+
(): SettledBridgeRequest => ({
378+
id: request.id,
379+
ok: false,
380+
error: signal.reason instanceof Error ? signal.reason.message : BRIDGE_CLOSED_MESSAGE,
381+
}),
382+
);
365383
const state: PendingBridgeState = {
366384
...request,
367-
promise: runBridgeRequest({
368-
runtime: params.runtime,
369-
catalogProjection: params.catalogProjection,
370-
namespaceRuntime: params.namespaceRuntime,
371-
parentToolCallId: params.parentToolCallId,
372-
codeModeRunId: params.codeModeRunId,
373-
maxOutputBytes: params.config.maxOutputBytes,
374-
remainingMs: Math.max(1, params.deadlineMs - Date.now()),
375-
ctx: params.ctx,
376-
request,
377-
signal,
378-
onUpdate: params.onUpdate,
379-
}).then((settled) => {
385+
promise: completion.then((settled) => {
380386
const trustedNoStart = tracksDispatch && consumeTrustedToolNoStartError(settled);
381387
if (tracksDispatch && params.bridgeDispatch.repairProvenance !== "invalid") {
382388
params.bridgeDispatch.repairProvenance =
@@ -401,7 +407,7 @@ export function createPendingBridgeStates(params: {
401407
}
402408
return settled;
403409
}),
404-
cancel: () => abortController.abort(),
410+
cancel: () => abortController.abort(new Error(BRIDGE_CLOSED_MESSAGE)),
405411
};
406412
return state;
407413
});
Lines changed: 282 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,282 @@
1+
/** Real QuickJS bridge coverage for subscribed embedded tool lifecycles. */
2+
import { expectDefined } from "@openclaw/normalization-core";
3+
import { afterEach, describe, expect, it, vi } from "vitest";
4+
import { createDeferred } from "../../test/helpers/promise.js";
5+
import { createDiagnosticEmbeddedRunOwner } from "../logging/diagnostic-run-activity.js";
6+
import { disposeAllCodeModeRuns } from "./code-mode-state.js";
7+
import { applyCodeModeCatalog, createCodeModeTools } from "./code-mode.js";
8+
import {
9+
pluginToolWithExecute,
10+
resetCodeModeTestState,
11+
resultDetails,
12+
testing,
13+
} from "./code-mode.test-support.js";
14+
import { prepareEmbeddedAttemptStream } from "./embedded-agent-runner/run/attempt-stream-prepare.js";
15+
import { clearActiveEmbeddedRun } from "./embedded-agent-runner/runs.js";
16+
import { createStubSessionHarness } from "./embedded-agent-subscribe.e2e-harness.js";
17+
import { countActiveToolExecutions } from "./embedded-agent-subscribe.handlers.tools.js";
18+
import { createToolSearchCatalogRef } from "./tool-search.js";
19+
import { jsonResult } from "./tools/common.js";
20+
21+
function createSubscribedCodeModeHarness(params: {
22+
name: string;
23+
onBlockReplyFlush?: () => Promise<void>;
24+
timeoutMs?: number;
25+
}) {
26+
const runId = `run-code-mode-${params.name}`;
27+
const sessionId = `session-code-mode-${params.name}`;
28+
const sessionKey = `agent:main:${params.name}`;
29+
const config = {
30+
tools: { codeMode: { enabled: true, timeoutMs: params.timeoutMs ?? 1_500 } },
31+
} as never;
32+
const catalogRef = createToolSearchCatalogRef();
33+
const runAbortController = new AbortController();
34+
const { session } = createStubSessionHarness();
35+
const activeSession = Object.assign(session, {
36+
agent: { hasQueuedMessages: () => false },
37+
isStreaming: false,
38+
messages: [],
39+
pendingMessageCount: 0,
40+
});
41+
const stream = prepareEmbeddedAttemptStream({
42+
attempt: { config, runId, sessionId, sessionKey } as never,
43+
activeSession: activeSession as never,
44+
hookRunner: undefined as never,
45+
hookAgentId: "main",
46+
diagnosticTrace: {} as never,
47+
diagnosticOwner: createDiagnosticEmbeddedRunOwner({ sessionId, sessionKey, runId }),
48+
clientToolCallSlots: [],
49+
toolSearchTargetTranscriptProjections: [],
50+
isReplaySafeTool: () => false,
51+
runAbortController,
52+
abortRun: () => runAbortController.abort(),
53+
markExternalAbort: () => undefined,
54+
getRunState: () => ({
55+
aborted: runAbortController.signal.aborted,
56+
promptError: undefined,
57+
timedOut: false,
58+
yieldDetected: false,
59+
}),
60+
hasDeliveredSourceReply: () => false,
61+
markSourceReplyDelivered: () => undefined,
62+
onBlockReply: undefined,
63+
onBlockReplyFlush: params.onBlockReplyFlush,
64+
sandboxSessionKey: sessionKey,
65+
builtinToolNames: new Set(),
66+
replaySafeToolNames: new Set(),
67+
});
68+
const context = {
69+
config,
70+
runtimeConfig: config,
71+
sessionId,
72+
sessionKey,
73+
runId,
74+
catalogRef,
75+
abortSignal: runAbortController.signal,
76+
executeTool: stream.toolSearchCatalogExecutor,
77+
};
78+
return {
79+
...context,
80+
tools: createCodeModeTools(context),
81+
runAbortController,
82+
subscription: stream.subscription,
83+
dispose: () => {
84+
stream.subscription.unsubscribe();
85+
clearActiveEmbeddedRun(sessionId, stream.queueHandle, sessionKey);
86+
},
87+
};
88+
}
89+
90+
describe("Code Mode subscribed bridge lifecycle", () => {
91+
afterEach(() => resetCodeModeTestState());
92+
93+
it("starts a subscribed nested tool without re-entering its outer presentation flush", async () => {
94+
const blockReplyFlush = createDeferred();
95+
const onBlockReplyFlush = vi.fn(() => blockReplyFlush.promise);
96+
const harness = createSubscribedCodeModeHarness({ name: "circular-flush", onBlockReplyFlush });
97+
const target = pluginToolWithExecute("release_flush", "Release the pending reply", async () => {
98+
blockReplyFlush.resolve();
99+
return jsonResult({ released: true });
100+
});
101+
applyCodeModeCatalog({ ...harness, tools: [...harness.tools, target] });
102+
103+
try {
104+
const result = resultDetails(
105+
await expectDefined(harness.tools[0], "Code Mode exec test invariant").execute(
106+
"code-call-circular-flush",
107+
{ code: "return await release_flush({});" },
108+
),
109+
);
110+
111+
expect(result.status, JSON.stringify(result)).toBe("completed");
112+
expect(result.value).toEqual({ released: true });
113+
expect(target.execute).toHaveBeenCalledOnce();
114+
expect(onBlockReplyFlush).not.toHaveBeenCalled();
115+
expect(harness.subscription.getItemLifecycle()).toMatchObject({
116+
startedCount: 1,
117+
completedCount: 1,
118+
activeCount: 0,
119+
});
120+
expect(countActiveToolExecutions(harness.runId)).toBe(0);
121+
expect(testing.activeRuns.size).toBe(0);
122+
} finally {
123+
blockReplyFlush.resolve();
124+
harness.dispose();
125+
}
126+
});
127+
128+
it("settles subscribed nested dispatch exactly once across repeated exec and wait turns", async () => {
129+
const blockReplyFlush = createDeferred();
130+
const onBlockReplyFlush = vi.fn(() => blockReplyFlush.promise);
131+
const harness = createSubscribedCodeModeHarness({
132+
name: "repeated-lifecycle",
133+
onBlockReplyFlush,
134+
});
135+
const target = pluginToolWithExecute("finish_stage", "Finish one suspended stage", async () => {
136+
blockReplyFlush.resolve();
137+
return jsonResult({ finished: true });
138+
});
139+
applyCodeModeCatalog({ ...harness, tools: [...harness.tools, target] });
140+
141+
try {
142+
for (let stage = 0; stage < 2; stage += 1) {
143+
const suspended = resultDetails(
144+
await expectDefined(harness.tools[0], "Code Mode exec test invariant").execute(
145+
`code-call-stage-${stage}`,
146+
{ code: 'await yield_control("pause"); return await finish_stage({});' },
147+
),
148+
);
149+
expect(suspended).toMatchObject({ status: "waiting", reason: "yield" });
150+
151+
const completed = resultDetails(
152+
await expectDefined(harness.tools[1], "Code Mode wait test invariant").execute(
153+
`code-wait-stage-${stage}`,
154+
{ runId: suspended.runId },
155+
),
156+
);
157+
expect(completed).toMatchObject({ status: "completed", value: { finished: true } });
158+
expect(countActiveToolExecutions(harness.runId)).toBe(0);
159+
}
160+
161+
expect(target.execute).toHaveBeenCalledTimes(2);
162+
expect(onBlockReplyFlush).not.toHaveBeenCalled();
163+
expect(harness.subscription.getItemLifecycle()).toMatchObject({
164+
startedCount: 2,
165+
completedCount: 2,
166+
activeCount: 0,
167+
});
168+
expect(testing.activeRuns.size).toBe(0);
169+
} finally {
170+
blockReplyFlush.resolve();
171+
harness.dispose();
172+
}
173+
});
174+
175+
it("preserves the initiating sessions_yield result across its run-owner handoff", async () => {
176+
const harness = createSubscribedCodeModeHarness({ name: "yield-handoff" });
177+
const handoffReason = { code: "sessions_yield", turnHandoff: true } as const;
178+
const target = pluginToolWithExecute(
179+
"sessions_yield",
180+
"Hand off the current turn",
181+
async () => {
182+
harness.runAbortController.abort(handoffReason);
183+
return jsonResult({ status: "yielded" });
184+
},
185+
);
186+
applyCodeModeCatalog({ ...harness, tools: [...harness.tools, target] });
187+
188+
try {
189+
const result = resultDetails(
190+
await expectDefined(harness.tools[0], "Code Mode exec test invariant").execute(
191+
"code-call-yield-handoff",
192+
{ code: "return await sessions_yield({});" },
193+
),
194+
);
195+
196+
expect(result).toMatchObject({ status: "completed", value: { status: "yielded" } });
197+
expect(target.execute).toHaveBeenCalledOnce();
198+
expect(countActiveToolExecutions(harness.runId)).toBe(0);
199+
expect(testing.activeRuns.size).toBe(0);
200+
} finally {
201+
harness.dispose();
202+
}
203+
});
204+
205+
it.each([
206+
{ kind: "explicit cancellation", close: "cancel" },
207+
{ kind: "run-owner loss", close: "abort" },
208+
{ kind: "snapshot expiry", close: "expire" },
209+
{ kind: "gateway shutdown", close: "shutdown" },
210+
] as const)(
211+
"settles an abort-ignoring subscribed tool exactly once after $kind",
212+
async ({ close }) => {
213+
const downstream = createDeferred();
214+
const harness = createSubscribedCodeModeHarness({
215+
name: `closure-${close}`,
216+
timeoutMs: 2_000,
217+
});
218+
const target = pluginToolWithExecute("stalled_target", "Ignore cancellation", async () => {
219+
await downstream.promise;
220+
return jsonResult({ late: true });
221+
});
222+
applyCodeModeCatalog({ ...harness, tools: [...harness.tools, target] });
223+
224+
try {
225+
const suspended = resultDetails(
226+
await expectDefined(harness.tools[0], "Code Mode exec test invariant").execute(
227+
`code-call-${close}`,
228+
{
229+
code: `const target = stalled_target({});
230+
await yield_control("pause");
231+
try { return await target; } catch (error) { return error.message; }`,
232+
},
233+
),
234+
);
235+
expect(suspended.status).toBe("waiting");
236+
expect(target.execute).toHaveBeenCalledOnce();
237+
expect(countActiveToolExecutions(harness.runId)).toBe(1);
238+
239+
const parked = testing.activeRuns.get(suspended.runId as string);
240+
const pending = parked?.pending.find((entry) => entry.method === "callValue");
241+
expect(pending).toBeDefined();
242+
if (!parked || !pending) {
243+
throw new Error("expected one parked subscribed tool call");
244+
}
245+
const settlements = vi.fn();
246+
void pending.promise.then(settlements);
247+
const waiting = expectDefined(harness.tools[1], "Code Mode wait test invariant").execute(
248+
`code-wait-${close}`,
249+
{ runId: suspended.runId },
250+
);
251+
252+
if (close === "cancel") {
253+
pending.cancel?.();
254+
} else if (close === "abort") {
255+
harness.runAbortController.abort(new Error("run owner closed"));
256+
} else if (close === "expire") {
257+
parked.expiresAt = Date.now() - 1;
258+
testing.removeExpiredRuns();
259+
} else {
260+
disposeAllCodeModeRuns();
261+
}
262+
263+
const settlement = await pending.promise;
264+
expect(settlement).toMatchObject({ id: pending.id, ok: false });
265+
expect(settlement.ok ? "" : settlement.error).toMatch(/cancel|abort|expir|owner|shut/i);
266+
expect(resultDetails(await waiting).status).not.toBe("waiting");
267+
await vi.waitFor(() => expect(countActiveToolExecutions(harness.runId)).toBe(0));
268+
expect(settlements).toHaveBeenCalledOnce();
269+
expect(harness.subscription.getItemLifecycle().activeCount).toBe(0);
270+
expect(testing.activeRuns.size).toBe(0);
271+
272+
downstream.resolve();
273+
await Promise.resolve();
274+
expect(target.execute).toHaveBeenCalledOnce();
275+
expect(settlements).toHaveBeenCalledOnce();
276+
} finally {
277+
downstream.resolve();
278+
harness.dispose();
279+
}
280+
},
281+
);
282+
});

0 commit comments

Comments
 (0)