Skip to content

Commit 73b98c4

Browse files
Yigtwxxsteipete
andauthored
fix(agents): node plugin tool calls report a generic client timeout (#118720)
* fix(agents): node plugin tool calls report a generic client timeout Plain node-hosted plugin tool calls send no invocation budget, so the Gateway arms no deadline over pairing, wake, and policy work and the node registry falls back to its own 30s pending timer that only starts at dispatch. The agent-side wait defaults to the same 30s but starts earlier, so the caller always abandons the request first and the Gateway answer that carries nodeCommandDispatched retry-safety provenance can never arrive. Send the same 30s budget explicitly and give the caller the +5s grace the node MCP path already uses, so the Gateway answer wins the race. * test(gateway): prove the node invoke deadline answer reaches the agent Adds an end-to-end proof that runs a real Gateway, pairs a real node that accepts the forwarded command and never answers, and drives the shipped agent tool through the real gateway client. It asserts the agent receives the Gateway's structured timeout with nodeCommandDispatched provenance rather than a client-side gateway timeout. * fix(gateway): keep node invoke dispatch inside the caller budget The invocation budget only started once dispatch was reached, so pairing revalidation before it spent nothing. With the Gateway deadline now armed for plain node plugin tools, that let a send land after the deadline had already answered the caller with nodeCommandDispatched:false, advertising a command the node had in fact received as retry-safe. Anchor the budget at entry and re-derive what is left after pairing revalidation, refusing to dispatch once it is exhausted. * test(gateway): restore the Gateway URL after the invoke deadline proof The shared Gateway fixture does not snapshot OPENCLAW_GATEWAY_URL, so the proof left later tests in the same worker pointing at its stopped ephemeral server. Capture and restore the key, including its previously-unset case. * fix(gateway): read the node invoke budget after request serialization Pairing revalidation is not the only step that can spend the caller budget before the pending timer is armed: tool parameters are unbounded, so serializing them and resolving the pending system.run event can outlive the remaining budget on their own. Reading the budget once all of that work is behind the call site keeps the node timeout and the pending timer starting from what is actually left, so an exhausted budget refuses the dispatch instead of arming a timer that answers after the caller already reported a timeout. * test(gateway): pin node invoke dispatch provenance against a budget-consuming send The review asked for the final event envelope to be serialized before the deadline admission check, on the grounds that a slow serialization could let the Gateway report nodeCommandDispatched: false for a command the node did receive. Envelope build, send and onDispatchReady are one synchronous block, so nothing can settle the pending request between them. Pin that invariant with a send that spends the whole remaining budget. * test(gateway): type the node socket send mock with its call signature The budget-consuming send regression wraps the recorded socket send, and ReturnType<typeof vi.fn> resolves to a mock without a call signature, so tsgo rejected the wrapper with TS2348 while vitest ran it fine. * test(gateway): follow the node pairing helpers into device-pairing-node main folded src/infra/node-pairing.ts into src/infra/device-pairing-node.ts, so the deadline proof stopped resolving its pairing import after the merge. * fix(gateway): scope the invoke deadline to caller-supplied budgets Callers that omit timeoutMs, such as fs.listDir and the exec-approval paths, have always used the registry's 30-second fallback as a post-dispatch pending timer. Anchoring that fallback before pairing revalidation turned it into a dispatch admission check, so a slow revalidation could answer TIMEOUT without ever dispatching. Only a positive caller-supplied budget anchors the deadline now, which keeps the plain plugin-tool path covered while those callers keep their established semantics. * fix(test): import approveDevicePairing from its new module main split the device pairing lifecycle modules in #124734 and moved approveDevicePairing to src/infra/device-pairing-approval.ts. Nothing on either side touched this import line, so the merge stays conflict free and only the typecheck reports the missing export. * refactor(gateway): move node invoke deadline budget to a sibling module node-registry-private.ts sits at 693 counted lines on main against a 700-line max-lines ratchet, and the inline budget bookkeeping pushed it to 703, which is what turned check-lint-core-2 red. The budget arithmetic moves to node-registry.invoke-budget.js unchanged; the call site keeps the same two reads. * refactor(gateway): move system.run invoke helpers to their sibling module The max-lines ratchet caps src/gateway/node-registry-private.ts at 700 effective lines and main now sits at 699, so the dispatch budget guard this branch adds takes the file to 705 and check-lint-core fails. resolvePendingSystemRunEvent and normalizeSystemRunInvokeParams are module-private and both already delegate to normalizeSystemRunTimeoutMs in node-registry.system-run.ts, so that module is where they belong. Pure move: no behavior change and no new export surface. * fix(gateway): keep the moved system.run helpers within the ratchet baselines The previous commit moved resolvePendingSystemRunEvent and normalizeSystemRunInvokeParams into node-registry.system-run.ts. It changed no behavior, but it did move three per-file measurements. normalizeSystemRunTimeoutMs was exported because node-registry-private.ts consumed it; the two callers that moved were its only external consumers, so after the move the export had none and Knip reported it as an unused production export. It is module-private now. The moved code also carried two `as Record<string, unknown>` assertions that were grandfathered under the old file. The new file's baseline is 0, so both now carry the // SAFETY: invariant the ratchet asks for, and the source file's baseline entry is shrunk from 3 to 1 as the ratchet's own message requested. * test(gateway): fix typed node invoke serialization fixture Close over the typed execution payload instead of reading contextual this inside toJSON, whose surrounding invoke params contract is unknown. Keep the serialization delay and independent execution-budget assertions. The 141 registry tests and focused canonical-inherited test type graph pass. Co-authored-by: Yigtwxx <[email protected]> * docs(changelog): avoid node deadline entry merge conflict Move only this PR's credited release-note entry beside the existing Gateway client watchdog entry, away from the concurrently edited section boundary. The entry and tested runtime behavior are unchanged. Co-authored-by: Yigtwxx <[email protected]> --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent e00d46b commit 73b98c4

9 files changed

Lines changed: 466 additions & 69 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@ Docs: https://docs.openclaw.ai
233233
- **Outbound channel bootstrap:** suppress repeated failed plugin activation for the same channel, config, and registry generation while retrying after config or registry reloads. (#100377) Thanks @xialonglee.
234234
- **OpenAI Realtime client-secret deadlines:** bound voice and transcription secret acquisition to 30 seconds through the guarded fetch boundary while preserving authentication and bounded response parsing. (#102860) Thanks @Alix-007.
235235
- **Gateway client watchdog:** keep transport-stall detection active for unbounded and mixed pending requests so dead sockets reject pending requests, reconnect, and never replay rejected requests. (#103407) Thanks @NianJiuZst.
236+
- **Node-hosted tools:** return structured deadline failures for plugin tools and prevent browser or other node commands from dispatching after their budget expires during pairing or parameter preparation. (#118720) Thanks @Yigtwxx.
236237
- **iOS Share Extension drafts:** preserve legitimate shared text beginning with scaffold-like prefixes, remove only exact legacy scaffold lines, avoid treating scheme-like prose as a URL, and deduplicate host-mirrored content. (#103453) Thanks @lin-hongkuan.
237238
- **Telegram reasoning previews:** reposition split reasoning previews through deferred deletion so prior preview messages do not remain stale while preserving client scroll position. (#97828) Thanks @ly-wang19.
238239
- **Feishu native-card threading:** normalize whitespace reply targets once and reuse the shared reply mode for card and media parts so native-card topic replies stay in their thread. (#102804) Thanks @sunlit-deng.

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2895,7 +2895,7 @@ src/gateway/node-browser-proxy-policy.ts 1
28952895
src/gateway/node-command-policy.ts 2
28962896
src/gateway/node-invoke-system-run-approval.ts 1
28972897
src/gateway/node-pairing-ssh-verify.ts 1
2898-
src/gateway/node-registry-private.ts 3
2898+
src/gateway/node-registry-private.ts 1
28992899
src/gateway/node-registry.ts 27
29002900
src/gateway/openai-agent-run-usage.ts 1
29012901
src/gateway/openai-http.ts 29

‎src/agents/node-plugin-tools.test.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -155,11 +155,12 @@ describe("createNodePluginTools", () => {
155155
});
156156
expect(callGatewayTool).toHaveBeenCalledWith(
157157
"node.invoke",
158-
{},
158+
{ timeoutMs: 35_000 },
159159
{
160160
nodeId: "node-1",
161161
command: "remote.echo",
162162
params: { text: "ping" },
163+
timeoutMs: 30_000,
163164
idempotencyKey: "call-1",
164165
sessionKey: "agent:main:canvas",
165166
},
@@ -216,11 +217,12 @@ describe("createNodePluginTools", () => {
216217

217218
expect(callGatewayTool).toHaveBeenCalledWith(
218219
"node.invoke",
219-
{},
220+
{ timeoutMs: 35_000 },
220221
{
221222
nodeId: "node-1",
222223
command: "remote.echo",
223224
params: { text: "ping" },
225+
timeoutMs: 30_000,
224226
idempotencyKey: "call-cancellable",
225227
},
226228
{ scopes: ["operator.write"], signal: controller.signal },
@@ -256,12 +258,13 @@ describe("createNodePluginTools", () => {
256258
);
257259
expect(callGatewayTool).toHaveBeenCalledWith(
258260
"node.invoke",
259-
{},
261+
{ timeoutMs: 35_000 },
260262
{
261263
nodeId: "node-1",
262264
command: "remote.echo",
263265
params: { text: "ping" },
264266
idempotencyKey: "call-aborted",
267+
timeoutMs: 30_000,
265268
},
266269
{ scopes: ["operator.write"], signal: controller.signal },
267270
);
@@ -646,12 +649,13 @@ describe("createNodePluginTools", () => {
646649
expect(tools.map((tool) => tool.name)).toEqual(["node_a_remote_echo", "node_b_remote_echo"]);
647650
expect(callGatewayTool).toHaveBeenCalledWith(
648651
"node.invoke",
649-
{},
652+
{ timeoutMs: 35_000 },
650653
{
651654
nodeId: "node-b",
652655
command: "remote.echo",
653656
params: { text: "ping" },
654657
idempotencyKey: "call-2",
658+
timeoutMs: 30_000,
655659
},
656660
{ scopes: ["operator.write"] },
657661
);

‎src/agents/node-plugin-tools.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import {
55
NODE_MCP_TOOL_CALL_GATEWAY_TIMEOUT_MS,
66
NODE_MCP_TOOL_CALL_TIMEOUT_MS,
77
NODE_MCP_TOOLS_CALL_COMMAND,
8+
NODE_PLUGIN_TOOL_CALL_GATEWAY_TIMEOUT_MS,
9+
NODE_PLUGIN_TOOL_CALL_TIMEOUT_MS,
810
} from "../infra/node-commands.js";
911
import { setPluginToolMeta } from "../plugins/tools.js";
1012
import { sanitizeServerName } from "./agent-bundle-mcp-names.js";
@@ -227,7 +229,11 @@ export function createNodePluginTools(params: {
227229
execute: async (toolCallId, toolParams, signal) => {
228230
const raw = await callGatewayTool(
229231
"node.invoke",
230-
mcpTool ? { timeoutMs: NODE_MCP_TOOL_CALL_GATEWAY_TIMEOUT_MS } : {},
232+
{
233+
timeoutMs: mcpTool
234+
? NODE_MCP_TOOL_CALL_GATEWAY_TIMEOUT_MS
235+
: NODE_PLUGIN_TOOL_CALL_GATEWAY_TIMEOUT_MS,
236+
},
231237
{
232238
nodeId: entry.nodeId,
233239
command: entry.command,
@@ -238,7 +244,7 @@ export function createNodePluginTools(params: {
238244
arguments: toolParams,
239245
}
240246
: toolParams,
241-
...(mcpTool ? { timeoutMs: NODE_MCP_TOOL_CALL_TIMEOUT_MS } : {}),
247+
timeoutMs: mcpTool ? NODE_MCP_TOOL_CALL_TIMEOUT_MS : NODE_PLUGIN_TOOL_CALL_TIMEOUT_MS,
242248
idempotencyKey: toolCallId,
243249
...(params.agentSessionKey ? { sessionKey: params.agentSessionKey } : {}),
244250
},
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
/**
2+
* Runtime proof for the plain node plugin tool invocation budget.
3+
* Drives a real Gateway and a real paired node that accepts a command and never
4+
* answers, then asserts the agent receives the Gateway's structured timeout with
5+
* its dispatch provenance instead of a client-side gateway timeout.
6+
*/
7+
import { describe, expect, it } from "vitest";
8+
import type { WebSocket } from "ws";
9+
import { createNodePluginTools } from "../agents/node-plugin-tools.js";
10+
import { approveDevicePairing } from "../infra/device-pairing-approval.js";
11+
import { approveNodePairing, requestNodePairing } from "../infra/device-pairing-node.js";
12+
import { listDevicePairing } from "../infra/device-pairing.js";
13+
import { getActiveRuntimePluginRegistry } from "../plugins/active-runtime-registry.js";
14+
import { captureEnv, setTestEnvValue } from "../test-utils/env.js";
15+
import { GATEWAY_CLIENT_MODES, GATEWAY_CLIENT_NAMES } from "../utils/message-channel.js";
16+
import { replaceConnectedNodePluginTools } from "./node-plugin-tool-snapshot.js";
17+
import { connectGatewayClient } from "./test-helpers.e2e.js";
18+
import { installGatewayTestHooks, rpcReq } from "./test-helpers.js";
19+
import { installConnectedControlUiServerSuite } from "./test-with-server.js";
20+
21+
installGatewayTestHooks({ scope: "suite" });
22+
23+
const NODE_DISPLAY_NAME = "Slow Studio Node";
24+
const NODE_COMMAND = "remote.echo";
25+
// One Gateway deadline (30s) plus the caller grace, plus room for pairing setup.
26+
const PROOF_TIMEOUT_MS = 240_000;
27+
28+
let ws: WebSocket;
29+
let port = 0;
30+
31+
installConnectedControlUiServerSuite((started) => {
32+
ws = started.ws;
33+
port = started.port;
34+
});
35+
36+
/** Registers the node-invoke policy a node-hosted plugin would contribute. */
37+
function installNodeCommandPolicy(): void {
38+
const registry = getActiveRuntimePluginRegistry();
39+
if (!registry) {
40+
throw new Error("active plugin registry is required for node invoke policy tests");
41+
}
42+
if (registry.nodeInvokePolicies.some((entry) => entry.policy.commands.includes(NODE_COMMAND))) {
43+
return;
44+
}
45+
registry.nodeInvokePolicies.push({
46+
pluginId: "remote-demo",
47+
pluginName: "Remote Demo",
48+
source: "test",
49+
rootDir: "extensions/remote-demo",
50+
pluginConfig: {},
51+
policy: {
52+
commands: [NODE_COMMAND],
53+
defaultPlatforms: ["ios", "android", "macos", "windows", "unknown"],
54+
foregroundRestrictedOnIos: false,
55+
handle: (ctx) => ctx.invokeNode(),
56+
},
57+
});
58+
}
59+
60+
describe("plain node plugin tool invocation deadline", () => {
61+
it(
62+
"returns the Gateway timeout with dispatch provenance when the node never answers",
63+
async () => {
64+
installNodeCommandPolicy();
65+
const dispatchedToNode: { timeoutMs?: number }[] = [];
66+
67+
const connectNode = async () =>
68+
await connectGatewayClient({
69+
url: `ws://127.0.0.1:${port}`,
70+
token: process.env.OPENCLAW_GATEWAY_TOKEN,
71+
role: "node",
72+
clientName: GATEWAY_CLIENT_NAMES.NODE_HOST,
73+
clientVersion: "1.0.0",
74+
clientDisplayName: NODE_DISPLAY_NAME,
75+
platform: "macos",
76+
mode: GATEWAY_CLIENT_MODES.NODE,
77+
scopes: [],
78+
commands: [NODE_COMMAND],
79+
// The node accepts the forwarded command and never sends a result.
80+
onEvent: (event) => {
81+
if (event.event === "node.invoke.request") {
82+
dispatchedToNode.push(event.payload as { timeoutMs?: number });
83+
}
84+
},
85+
timeoutMessage: "timeout waiting for node to connect",
86+
});
87+
88+
const connectWithDevicePairing = async () => {
89+
try {
90+
return await connectNode();
91+
} catch (error) {
92+
const message = error instanceof Error ? error.message : String(error);
93+
if (!message.includes("pairing required")) {
94+
throw error;
95+
}
96+
const pairings = await listDevicePairing();
97+
for (const pending of pairings.pending) {
98+
await approveDevicePairing(pending.requestId, {
99+
callerScopes: pending.scopes ?? ["operator.admin"],
100+
});
101+
}
102+
return await connectNode();
103+
}
104+
};
105+
106+
const findNodeId = async () => {
107+
const listed = await rpcReq<{
108+
nodes?: { nodeId: string; displayName?: string; connected?: boolean }[];
109+
}>(ws, "node.list", {});
110+
return (listed.payload?.nodes ?? []).find(
111+
(entry) => entry.connected && entry.displayName === NODE_DISPLAY_NAME,
112+
)?.nodeId;
113+
};
114+
115+
const provisional = await connectWithDevicePairing();
116+
const provisionalNodeId = await findNodeId();
117+
if (!provisionalNodeId) {
118+
throw new Error("expected a connected node id before pairing");
119+
}
120+
await provisional.stopAndWait();
121+
const pairing = await requestNodePairing({
122+
nodeId: provisionalNodeId,
123+
displayName: NODE_DISPLAY_NAME,
124+
platform: "macos",
125+
commands: [NODE_COMMAND],
126+
});
127+
await approveNodePairing(pairing.request.requestId, {
128+
callerScopes: ["operator.admin", "operator.write"],
129+
});
130+
const node = await connectNode();
131+
// The shared Gateway fixture snapshots no such key, so leaving it set would
132+
// point later tests in this worker at this stopped ephemeral server.
133+
const gatewayUrlEnv = captureEnv(["OPENCLAW_GATEWAY_URL"]);
134+
135+
try {
136+
const nodeId = (await findNodeId()) ?? provisionalNodeId;
137+
replaceConnectedNodePluginTools({
138+
nodeId,
139+
displayName: NODE_DISPLAY_NAME,
140+
tools: [
141+
{
142+
descriptor: {
143+
pluginId: "remote-demo",
144+
name: "remote_echo",
145+
description: "Echo through a remote node",
146+
parameters: { type: "object", properties: { text: { type: "string" } } },
147+
command: NODE_COMMAND,
148+
},
149+
registered: false,
150+
},
151+
],
152+
});
153+
setTestEnvValue("OPENCLAW_GATEWAY_URL", `ws://127.0.0.1:${port}`);
154+
155+
const tool = createNodePluginTools({})[0];
156+
if (!tool) {
157+
throw new Error("expected a materialized node plugin tool");
158+
}
159+
160+
const failure = await tool
161+
.execute("deadline-proof-call", { text: "ping" })
162+
.then(() => undefined)
163+
.catch((error: unknown) => error);
164+
165+
// The command really reached the node, so the answer must not claim retry safety.
166+
expect(dispatchedToNode).toHaveLength(1);
167+
expect(dispatchedToNode[0]?.timeoutMs).toBeGreaterThan(0);
168+
169+
const message = failure instanceof Error ? failure.message : String(failure);
170+
// Without the payload budget the Gateway arms no deadline and this reads
171+
// "gateway timeout after 30000ms" instead, with no provenance to inspect.
172+
expect(message).toContain("node invoke timed out");
173+
expect(failure).toMatchObject({ details: { nodeCommandDispatched: true } });
174+
} finally {
175+
gatewayUrlEnv.restore();
176+
await node.stopAndWait();
177+
}
178+
},
179+
PROOF_TIMEOUT_MS,
180+
);
181+
});

0 commit comments

Comments
 (0)