Skip to content

Commit 730b6ef

Browse files
authored
fix: dashboard tools target the wrong Gateway after admission (#130112)
Dashboard tools now stay bound to the Gateway that admitted the agent run. Reads, mutations, and broadcasts fail closed if that Gateway is replaced or retired instead of transferring authority to another instance.
1 parent f010c00 commit 730b6ef

9 files changed

Lines changed: 433 additions & 52 deletions

‎src/agents/harness/host-capability.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,16 @@ import path from "node:path";
44
import { Type } from "typebox";
55
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
66
import { createDeferred } from "../../../test/helpers/promise.js";
7+
import type { GatewayRequestContext } from "../../gateway/server-methods/types.js";
78
import {
89
resetAgentRunRegistryForTest,
910
rotateAgentRunRegistryLifecycleGeneration,
1011
validateAgentRunDelegatedAuthority,
1112
} from "../../infra/agent-run-registry.js";
13+
import {
14+
bindGatewayContextResolver,
15+
withPluginRuntimeGatewayRequestScope,
16+
} from "../../plugins/runtime/gateway-request-scope.js";
1217
import {
1318
closeAdmittedRunDelegatedAuthority,
1419
createOperationalRunInstanceRef,
@@ -29,6 +34,7 @@ import {
2934
import type { AnyAgentTool } from "../tools/common.js";
3035
import { getGatewayToolCallerIdentity } from "../tools/gateway-caller-context.js";
3136
import { callGatewayTool } from "../tools/gateway.js";
37+
import { getInProcessGatewayToolContext } from "../tools/in-process-gateway.js";
3238
import {
3339
createAgentHarnessHostCapabilities,
3440
retainBeforeToolCallForNativeHookRelay,
@@ -242,6 +248,44 @@ describe("agent harness host capability", () => {
242248
expect(() => host.capabilities.preparedEnvironment?.()).toThrow("no longer active");
243249
});
244250

251+
it("rejects retained preparation after the admitted Gateway is replaced", async () => {
252+
const { attempt } = await admittedAttempt("run-prepared-gateway");
253+
const admitted = {} as GatewayRequestContext;
254+
const replacement = {} as GatewayRequestContext;
255+
let current = admitted;
256+
bindGatewayContextResolver(attempt.admittedRunContext, () => current);
257+
const preparedExecute = vi.fn(async () => ({ content: [], details: {} }));
258+
const tool = attachInternalToolExecutionPreparer(testTool().tool, async () => {
259+
expect(getInProcessGatewayToolContext()).toBe(admitted);
260+
return {
261+
kind: "ready",
262+
args: {},
263+
execute: preparedExecute,
264+
dispose: vi.fn(),
265+
};
266+
});
267+
const host = createAgentHarnessHostCapabilities({ attempt, pluginId: "codex" });
268+
const [bound] = host.capabilities.bindToolSurface([tool]);
269+
const preparer = bound ? getInternalToolExecutionPreparer(bound) : undefined;
270+
if (!preparer) {
271+
throw new Error("expected bound preparer");
272+
}
273+
274+
await withPluginRuntimeGatewayRequestScope(
275+
{ context: replacement, isWebchatConnect: () => false },
276+
async () => {
277+
const prepared = await preparer({ toolCallId: "prepare", args: {} });
278+
expect(prepared.kind).toBe("ready");
279+
current = replacement;
280+
if (prepared.kind === "ready") {
281+
await expect(prepared.execute()).rejects.toThrow("no longer active");
282+
}
283+
},
284+
);
285+
286+
expect(preparedExecute).not.toHaveBeenCalled();
287+
});
288+
245289
it("delegates trajectory events and rejects a flush that outlives the capability", async () => {
246290
const flushStarted = createDeferred();
247291
const flushResult = createDeferred();

‎src/agents/harness/host-capability.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -168,16 +168,18 @@ export function createAgentHarnessHostCapabilities(params: {
168168
// Lexical closure must also fence work already past its entry guard. The
169169
// result guards below cover exact authority loss that does not use close().
170170
const capabilityAbortController = new AbortController();
171-
const assertActive = () => {
171+
const callerIdentity = createBoundCallerIdentity(attempt, assertActive);
172+
function assertActive() {
172173
if (
173174
!active ||
174175
attempt.admittedRunContext.operationalRunInstance !== operationalRunInstance ||
175-
getAdmittedRunDelegatedAuthority(attempt.admittedRunContext) !== delegatedAuthority
176+
getAdmittedRunDelegatedAuthority(attempt.admittedRunContext) !== delegatedAuthority ||
177+
(callerIdentity?.gatewayContextResolver !== undefined &&
178+
callerIdentity.gatewayContextResolver() === undefined)
176179
) {
177180
throw new Error("agent harness host capability is no longer active");
178181
}
179-
};
180-
const callerIdentity = createBoundCallerIdentity(attempt, assertActive);
182+
}
181183
const requester = {
182184
...((attempt.messageChannel ?? attempt.messageProvider)
183185
? { channel: attempt.messageChannel ?? attempt.messageProvider ?? undefined }
@@ -276,7 +278,9 @@ export function createAgentHarnessHostCapabilities(params: {
276278
const assertRecoveryActive = () => {
277279
if (
278280
attempt.abortSignal?.aborted ||
279-
attempt.admittedRunContext.operationalRunInstance !== operationalRunInstance
281+
attempt.admittedRunContext.operationalRunInstance !== operationalRunInstance ||
282+
(callerIdentity?.gatewayContextResolver !== undefined &&
283+
callerIdentity.gatewayContextResolver() === undefined)
280284
) {
281285
throw new Error("agent harness retained host policy is no longer active");
282286
}

‎src/agents/tools/dashboard-tool.test.ts‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,18 @@
11
import { Value } from "typebox/value";
22
import { describe, expect, it, vi } from "vitest";
33
import type { BoardCommand, BoardSnapshot } from "../../../packages/gateway-protocol/src/index.js";
4+
import {
5+
createGatewayMethodDescriptorsFromHandlers,
6+
createGatewayMethodRegistry,
7+
} from "../../gateway/methods/registry.js";
8+
import type {
9+
GatewayRequestContext,
10+
GatewayRequestHandlerOptions,
11+
GatewayRequestHandlers,
12+
} from "../../gateway/server-methods/types.js";
413
import { withPluginRuntimeGatewayRequestScope } from "../../plugins/runtime/gateway-request-scope.js";
514
import { createDashboardTool } from "./dashboard-tool.js";
15+
import { withGatewayToolCallerIdentity } from "./gateway-caller-context.js";
616
import type { InProcessGatewayCaller } from "./in-process-gateway.js";
717

818
const snapshot: BoardSnapshot = {
@@ -33,6 +43,32 @@ function recorder(boardSnapshot: BoardSnapshot = snapshot) {
3343
};
3444
}
3545

46+
function createGatewayAffinityHarness(revision: number) {
47+
const requests: GatewayRequestHandlerOptions["req"][] = [];
48+
const broadcastToConnIds = vi.fn();
49+
const handlers: GatewayRequestHandlers = {
50+
"board.get": ({ req, respond }) => {
51+
requests.push(req);
52+
respond(true, { ...snapshot, revision });
53+
},
54+
};
55+
const methodRegistry = createGatewayMethodRegistry(
56+
createGatewayMethodDescriptorsFromHandlers({
57+
handlers,
58+
owner: { kind: "core", area: "dashboard-affinity-test" },
59+
defaultScope: "operator.read",
60+
}),
61+
);
62+
const context = {
63+
broadcastToConnIds,
64+
getClientConnIds: () => new Set([`control-ui-${revision}`]),
65+
getGatewayMethodRegistry: () => methodRegistry,
66+
getRuntimeConfig: () => ({}),
67+
resolveGatewayContext: () => context,
68+
} as unknown as GatewayRequestContext;
69+
return { broadcastToConnIds, context, requests };
70+
}
71+
3672
describe("dashboard tool", () => {
3773
it("declares every action, no client capability guard, sizing, and the dashboard threshold", () => {
3874
const tool = createDashboardTool();
@@ -94,6 +130,58 @@ describe("dashboard tool", () => {
94130
});
95131
});
96132

133+
it("dispatches through the admitted Gateway and fences replacement or retirement", async () => {
134+
const admitted = createGatewayAffinityHarness(11);
135+
const replacement = createGatewayAffinityHarness(22);
136+
let current: GatewayRequestContext | undefined = admitted.context;
137+
const tool = createDashboardTool({ agentSessionKey: "agent:main:main" });
138+
139+
await withPluginRuntimeGatewayRequestScope(
140+
{
141+
context: replacement.context,
142+
isWebchatConnect: () => false,
143+
},
144+
async () =>
145+
await withGatewayToolCallerIdentity(
146+
{
147+
agentId: "main",
148+
sessionKey: "agent:main:main",
149+
gatewayContextResolver: () => current,
150+
},
151+
async () => {
152+
const read = await tool.execute("read", { action: "read" });
153+
const command = await tool.execute("focus", {
154+
action: "focus_tab",
155+
tabId: "main",
156+
});
157+
expect(read.details).toMatchObject({ revision: 11 });
158+
expect(command.details).toEqual({ ok: true, delivered: 1 });
159+
160+
current = replacement.context;
161+
await expect(tool.execute("late-read", { action: "read" })).rejects.toThrow(
162+
/dashboard|Gateway|gateway|unavailable/u,
163+
);
164+
current = undefined;
165+
await expect(
166+
tool.execute("late-focus", { action: "focus_tab", tabId: "main" }),
167+
).rejects.toThrow(/dashboard|Gateway|gateway|unavailable/u);
168+
},
169+
),
170+
);
171+
172+
expect(admitted.requests).toEqual([
173+
expect.objectContaining({
174+
type: "req",
175+
id: expect.stringMatching(/^plugin-subagent-/u),
176+
method: "board.get",
177+
params: expect.objectContaining({ sessionKey: "agent:main:main" }),
178+
}),
179+
]);
180+
expect(replacement.requests).toEqual([]);
181+
expect(admitted.broadcastToConnIds).toHaveBeenCalledOnce();
182+
expect(replacement.broadcastToConnIds).not.toHaveBeenCalled();
183+
});
184+
97185
it("returns content ownership and valid update paths in model-visible snapshot details", async () => {
98186
const widget = (
99187
name: string,

‎src/agents/tools/dashboard-tool.ts‎

Lines changed: 48 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import type {
55
BoardOp,
66
BoardSnapshot,
77
} from "../../../packages/gateway-protocol/src/index.js";
8+
import type { GatewayContextResolver } from "../../gateway/server-methods/types.js";
89
import type { AnyAgentTool } from "./common.js";
910
import {
1011
readNumberParam,
@@ -13,6 +14,7 @@ import {
1314
textResult,
1415
ToolInputError,
1516
} from "./common.js";
17+
import { getGatewayToolCallerIdentity } from "./gateway-caller-context.js";
1618
import {
1719
callInProcessGatewayTool,
1820
getInProcessGatewayToolContext,
@@ -88,11 +90,14 @@ const DashboardToolSchema = Type.Object(
8890
{ additionalProperties: false },
8991
);
9092

91-
type DashboardCommandEmitter = (params: {
92-
sessionKey: string;
93-
agentId?: string;
94-
command: BoardCommand;
95-
}) => number;
93+
type DashboardCommandEmitter = (
94+
params: {
95+
sessionKey: string;
96+
agentId?: string;
97+
command: BoardCommand;
98+
},
99+
resolveGatewayContext?: GatewayContextResolver,
100+
) => number;
96101

97102
type DashboardGatewayContext = {
98103
getClientConnIds?: (
@@ -229,12 +234,17 @@ function opForAction(action: string, params: Record<string, unknown>): BoardOp {
229234
}
230235
}
231236

232-
function emitBoardCommand(params: {
233-
sessionKey: string;
234-
agentId?: string;
235-
command: BoardCommand;
236-
}): number {
237-
const context = getInProcessGatewayToolContext() as DashboardGatewayContext | undefined;
237+
function emitBoardCommand(
238+
params: {
239+
sessionKey: string;
240+
agentId?: string;
241+
command: BoardCommand;
242+
},
243+
resolveGatewayContext?: GatewayContextResolver,
244+
): number {
245+
const context = getInProcessGatewayToolContext(resolveGatewayContext) as
246+
| DashboardGatewayContext
247+
| undefined;
238248
if (!context) {
239249
throw new ToolInputError("dashboard command unavailable outside gateway runtime");
240250
}
@@ -295,35 +305,47 @@ export function createDashboardTool(opts: DashboardToolOptions = {}): AnyAgentTo
295305
const params = rawArgs as Record<string, unknown>;
296306
const action = readToolStringParam(params, "action", { required: true });
297307
const sessionKey = requireSessionKey(opts.agentSessionKey);
308+
const admittedResolver = getGatewayToolCallerIdentity()?.gatewayContextResolver;
309+
const gatewayOptions = admittedResolver
310+
? { resolveGatewayContext: admittedResolver }
311+
: undefined;
312+
const callGateway = <T>(method: string, gatewayParams: Record<string, unknown>) =>
313+
gatewayCall<T>(method, gatewayParams, gatewayOptions);
298314
if (action === "read") {
299315
return snapshotResult(
300-
await gatewayCall<BoardSnapshot>("board.get", {
316+
await callGateway<BoardSnapshot>("board.get", {
301317
sessionKey,
302318
agentId: opts.agentId,
303319
}),
304320
);
305321
}
306322
if (action === "focus_tab") {
307-
const delivered = emitCommand({
308-
sessionKey,
309-
agentId: opts.agentId,
310-
command: {
311-
kind: "focus_tab",
312-
tabId: readTabId(params),
323+
const delivered = emitCommand(
324+
{
325+
sessionKey,
326+
agentId: opts.agentId,
327+
command: {
328+
kind: "focus_tab",
329+
tabId: readTabId(params),
330+
},
313331
},
314-
});
332+
admittedResolver,
333+
);
315334
return commandResult(delivered);
316335
}
317336
if (action === "set_chat_dock") {
318337
const dock = readDock(params, "dock");
319338
if (!dock) {
320339
throw new ToolInputError("dock required");
321340
}
322-
const delivered = emitCommand({
323-
sessionKey,
324-
agentId: opts.agentId,
325-
command: { kind: "set_chat_dock", dock },
326-
});
341+
const delivered = emitCommand(
342+
{
343+
sessionKey,
344+
agentId: opts.agentId,
345+
command: { kind: "set_chat_dock", dock },
346+
},
347+
admittedResolver,
348+
);
327349
return commandResult(delivered);
328350
}
329351
if (action === "widget_put") {
@@ -337,7 +359,7 @@ export function createDashboardTool(opts: DashboardToolOptions = {}): AnyAgentTo
337359
const after = readToolStringParam(params, "after");
338360
const props = readPluginProps(params);
339361
return snapshotResult(
340-
await gatewayCall<BoardSnapshot>("board.widget.put", {
362+
await callGateway<BoardSnapshot>("board.widget.put", {
341363
sessionKey,
342364
agentId: opts.agentId,
343365
name: readToolStringParam(params, "name", { required: true }),
@@ -360,7 +382,7 @@ export function createDashboardTool(opts: DashboardToolOptions = {}): AnyAgentTo
360382
);
361383
}
362384
return snapshotResult(
363-
await gatewayCall<BoardSnapshot>("board.update", {
385+
await callGateway<BoardSnapshot>("board.update", {
364386
sessionKey,
365387
agentId: opts.agentId,
366388
ops: [opForAction(action, params)],

‎src/agents/tools/gateway-caller-context.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { expectDefined } from "@openclaw/normalization-core";
22
import { Type } from "typebox";
33
import { describe, expect, it, vi } from "vitest";
44
import { createExecutionIdentityAdmissionToken } from "../../audit/execution-identity-admission.js";
5+
import type { GatewayRequestContext } from "../../gateway/server-methods/types.js";
56
import { getPluginToolMeta, setPluginToolMeta } from "../../plugins/tools.js";
67
import {
78
isToolWrappedWithBeforeToolCallHook,
@@ -91,6 +92,26 @@ describe("gateway caller context wrapper", () => {
9192
expect(seen).toEqual([identity, identity]);
9293
});
9394

95+
it("pins caller identity to the Gateway present at admission", async () => {
96+
const admitted = {} as GatewayRequestContext;
97+
const replacement = {} as GatewayRequestContext;
98+
let current = admitted;
99+
100+
await withGatewayToolCallerIdentity(
101+
{
102+
agentId: "agent-a",
103+
sessionKey: "agent-a:session",
104+
gatewayContextResolver: () => current,
105+
},
106+
() => {
107+
const resolveGatewayContext = getGatewayToolCallerIdentity()?.gatewayContextResolver;
108+
expect(resolveGatewayContext?.()).toBe(admitted);
109+
current = replacement;
110+
expect(resolveGatewayContext?.()).toBeUndefined();
111+
},
112+
);
113+
});
114+
94115
it("scopes nested approval ownership without replacing the native runtime owner", async () => {
95116
let nestedOwner: string | undefined;
96117
let restoredOwner: string | undefined;

0 commit comments

Comments
 (0)