Skip to content

Commit 42f77a3

Browse files
committed
fix(gateway): bind system-agent sessions to callers
1 parent 7116ad6 commit 42f77a3

4 files changed

Lines changed: 409 additions & 100 deletions

File tree

‎src/gateway/server-methods/shared-types.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ type GatewaySystemAgentSession = {
135135
welcome: string;
136136
welcomeQuestion?: SystemAgentChatQuestion;
137137
lastUsedAt: number;
138-
delegationKey?: string;
138+
ownerKey: string;
139139
pendingApproval?: { id: string; proposalHash: string };
140140
};
141141

Lines changed: 355 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,355 @@
1+
// System-agent session tests cover caller ownership and response projection.
2+
3+
import { expectDefined } from "@openclaw/normalization-core";
4+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5+
import { resetCommandQueueStateForTest } from "../../process/command-queue.test-support.js";
6+
import { systemAgentHandlers, type SystemAgentChatSession } from "./system-agent.js";
7+
import type { GatewayClient, GatewayRequestContext } from "./types.js";
8+
9+
const setupInferenceMocks = vi.hoisted(() => ({ verifySetupInference: vi.fn() }));
10+
const delegatedInferenceMocks = vi.hoisted(() => ({
11+
verifySystemAgentInferenceWithFallback: vi.fn(),
12+
}));
13+
14+
vi.mock("../../system-agent/setup-inference.js", () => ({
15+
verifySetupInference: setupInferenceMocks.verifySetupInference,
16+
}));
17+
vi.mock("../../system-agent/inference-fallback.js", () => ({
18+
verifySystemAgentInferenceWithFallback:
19+
delegatedInferenceMocks.verifySystemAgentInferenceWithFallback,
20+
}));
21+
vi.mock("../../system-agent/transcript-store.js", () => ({
22+
appendTranscriptReset: vi.fn(),
23+
appendTranscriptTurn: vi.fn(),
24+
readTranscriptTail: vi.fn(() => []),
25+
}));
26+
27+
type FakeEngine = {
28+
handle: ReturnType<typeof vi.fn>;
29+
seedHistory: ReturnType<typeof vi.fn>;
30+
historyLength: ReturnType<typeof vi.fn>;
31+
historySince: ReturnType<typeof vi.fn>;
32+
getPendingOperatorProposal: ReturnType<typeof vi.fn>;
33+
resolveOperatorApproval: ReturnType<typeof vi.fn>;
34+
dispose: ReturnType<typeof vi.fn>;
35+
loadOverview: ReturnType<typeof vi.fn>;
36+
noteAssistantMessage: ReturnType<typeof vi.fn>;
37+
};
38+
39+
function makeEngine(): FakeEngine {
40+
return {
41+
handle: vi.fn(async () => ({ text: "did the thing", action: "none" })),
42+
seedHistory: vi.fn(),
43+
historyLength: vi.fn(() => 0),
44+
historySince: vi.fn(() => []),
45+
getPendingOperatorProposal: vi.fn(() => null),
46+
resolveOperatorApproval: vi.fn(async () => null),
47+
dispose: vi.fn(async () => undefined),
48+
loadOverview: vi.fn(async () => ({})),
49+
noteAssistantMessage: vi.fn(),
50+
};
51+
}
52+
53+
const createdEngines = vi.hoisted(() => [] as FakeEngine[]);
54+
55+
vi.mock("../../system-agent/chat-engine.js", () => ({
56+
SystemAgentChatEngine: function FakeSystemAgentChatEngine(this: FakeEngine) {
57+
const engine = makeEngine();
58+
createdEngines.push(engine);
59+
Object.assign(this, engine);
60+
},
61+
}));
62+
vi.mock("../../system-agent/overview.js", () => ({
63+
formatSystemAgentStartupMessage: vi.fn(() => "welcome text"),
64+
}));
65+
66+
type RespondCall = { ok: boolean; payload?: unknown; error?: unknown };
67+
68+
function makeClient(params: {
69+
connId: string;
70+
deviceId?: string;
71+
authenticatedUserId?: string;
72+
}): GatewayClient {
73+
return {
74+
connId: params.connId,
75+
connect: {
76+
client: { id: "openclaw-control-ui", mode: "webchat" },
77+
...(params.deviceId ? { device: { id: params.deviceId } } : {}),
78+
},
79+
...(params.authenticatedUserId ? { authenticatedUserId: params.authenticatedUserId } : {}),
80+
} as GatewayClient;
81+
}
82+
83+
const defaultClient = makeClient({ connId: "conn-test", deviceId: "device-test" });
84+
85+
function makeContext(sessions: Map<string, SystemAgentChatSession>): GatewayRequestContext {
86+
return { systemAgentSessions: sessions } as unknown as GatewayRequestContext;
87+
}
88+
89+
function seededSession(params?: {
90+
engine?: FakeEngine;
91+
ownerKey?: string;
92+
}): SystemAgentChatSession {
93+
return {
94+
engine: params?.engine ?? makeEngine(),
95+
welcome: "welcome text",
96+
lastUsedAt: 1,
97+
ownerKey: params?.ownerKey ?? "device:device-test",
98+
} as unknown as SystemAgentChatSession;
99+
}
100+
101+
async function callChat(
102+
context: GatewayRequestContext,
103+
params: Record<string, unknown>,
104+
client: GatewayClient | null = defaultClient,
105+
): Promise<RespondCall> {
106+
const calls: RespondCall[] = [];
107+
await expectDefined(
108+
systemAgentHandlers["openclaw.chat"],
109+
'systemAgentHandlers["openclaw.chat"] test invariant',
110+
)({
111+
params,
112+
client,
113+
context,
114+
respond: (ok, payload, error) => calls.push({ ok, payload, error }),
115+
} as never);
116+
return expectDefined(calls[0], "system-agent response");
117+
}
118+
119+
beforeEach(() => {
120+
createdEngines.length = 0;
121+
setupInferenceMocks.verifySetupInference.mockResolvedValue({ ok: true, binding: {} });
122+
delegatedInferenceMocks.verifySystemAgentInferenceWithFallback.mockResolvedValue({
123+
ok: true,
124+
binding: {},
125+
});
126+
});
127+
128+
afterEach(() => {
129+
vi.clearAllMocks();
130+
resetCommandQueueStateForTest();
131+
});
132+
133+
describe("openclaw.chat session ownership", () => {
134+
it("binds a new non-delegated session and rejects another principal", async () => {
135+
const sessions = new Map<string, SystemAgentChatSession>();
136+
const context = makeContext(sessions);
137+
const owner = makeClient({
138+
connId: "conn-owner",
139+
deviceId: "device-owner",
140+
authenticatedUserId: "[email protected]",
141+
});
142+
const attacker = makeClient({
143+
connId: "conn-attacker",
144+
deviceId: "device-attacker",
145+
authenticatedUserId: "[email protected]",
146+
});
147+
148+
expect(await callChat(context, { sessionId: "owned-session" }, owner)).toMatchObject({
149+
ok: true,
150+
});
151+
expect(sessions.get("owned-session")?.ownerKey).toBe("user:[email protected]");
152+
const handle = expectDefined(createdEngines[0], "created system-agent engine").handle;
153+
154+
const turn = await callChat(
155+
context,
156+
{ sessionId: "owned-session", message: "show status" },
157+
attacker,
158+
);
159+
const approval = await callChat(
160+
context,
161+
{ sessionId: "owned-session", message: "yes" },
162+
attacker,
163+
);
164+
const reset = await callChat(context, { sessionId: "owned-session", reset: true }, attacker);
165+
166+
expect(turn).toMatchObject({
167+
ok: false,
168+
payload: undefined,
169+
error: { code: "INVALID_REQUEST" },
170+
});
171+
expect(approval).toMatchObject({
172+
ok: false,
173+
payload: undefined,
174+
error: { code: "INVALID_REQUEST" },
175+
});
176+
expect(reset).toMatchObject({
177+
ok: false,
178+
payload: undefined,
179+
error: { code: "INVALID_REQUEST" },
180+
});
181+
expect(handle).not.toHaveBeenCalled();
182+
expect(
183+
expectDefined(createdEngines[0], "created system-agent engine").dispose,
184+
).not.toHaveBeenCalled();
185+
});
186+
187+
it("lets the same authenticated principal resume after reconnecting", async () => {
188+
const sessions = new Map<string, SystemAgentChatSession>();
189+
const context = makeContext(sessions);
190+
await callChat(
191+
context,
192+
{ sessionId: "reconnect" },
193+
makeClient({
194+
connId: "conn-old",
195+
deviceId: "device-old",
196+
authenticatedUserId: "[email protected]",
197+
}),
198+
);
199+
const handle = expectDefined(createdEngines[0], "created system-agent engine").handle;
200+
201+
const resumed = await callChat(
202+
context,
203+
{ sessionId: "reconnect", message: "continue" },
204+
makeClient({
205+
connId: "conn-new",
206+
deviceId: "device-new",
207+
authenticatedUserId: "[email protected]",
208+
}),
209+
);
210+
211+
expect(resumed.ok).toBe(true);
212+
expect(handle).toHaveBeenCalledWith("continue");
213+
});
214+
215+
it("lets the same paired device resume after reconnecting", async () => {
216+
const sessions = new Map<string, SystemAgentChatSession>();
217+
const context = makeContext(sessions);
218+
await callChat(
219+
context,
220+
{ sessionId: "device-reconnect" },
221+
makeClient({ connId: "conn-old", deviceId: "device-owner" }),
222+
);
223+
const handle = expectDefined(createdEngines[0], "created system-agent engine").handle;
224+
225+
const resumed = await callChat(
226+
context,
227+
{ sessionId: "device-reconnect", message: "continue" },
228+
makeClient({ connId: "conn-new", deviceId: "device-owner" }),
229+
);
230+
231+
expect(resumed.ok).toBe(true);
232+
expect(handle).toHaveBeenCalledWith("continue");
233+
});
234+
235+
it("rejects non-delegated chat without a server-authenticated identity", async () => {
236+
const call = await callChat(makeContext(new Map()), { sessionId: "anonymous" }, null);
237+
238+
expect(call).toMatchObject({ ok: false, error: { code: "INVALID_REQUEST" } });
239+
});
240+
241+
it("keeps explicit delegation authoritative across connection identities", async () => {
242+
const sessions = new Map<string, SystemAgentChatSession>();
243+
const context = makeContext(sessions);
244+
const delegation = { agentId: "main", sessionKey: "agent:main:main" };
245+
await callChat(
246+
context,
247+
{ sessionId: "delegated", delegation },
248+
makeClient({ connId: "conn-owner", deviceId: "device-owner" }),
249+
);
250+
const handle = expectDefined(createdEngines[0], "created delegated engine").handle;
251+
252+
const resumed = await callChat(
253+
context,
254+
{ sessionId: "delegated", message: "continue", delegation },
255+
makeClient({
256+
connId: "conn-other",
257+
deviceId: "device-other",
258+
authenticatedUserId: "[email protected]",
259+
}),
260+
);
261+
262+
expect(resumed.ok).toBe(true);
263+
expect(handle).toHaveBeenCalledWith("continue");
264+
});
265+
266+
it("rejects delegated reuse of a non-delegated session", async () => {
267+
const engine = makeEngine();
268+
const sessions = new Map<string, SystemAgentChatSession>([
269+
["shared", seededSession({ engine })],
270+
]);
271+
272+
const delegated = await callChat(makeContext(sessions), {
273+
sessionId: "shared",
274+
message: "yes",
275+
delegation: { agentId: "main", sessionKey: "agent:main:main" },
276+
});
277+
278+
expect(delegated).toMatchObject({ ok: false, error: { code: "INVALID_REQUEST" } });
279+
expect(engine.handle).not.toHaveBeenCalled();
280+
});
281+
});
282+
283+
describe("openclaw.chat session responses", () => {
284+
it("returns the stored welcome when no message is sent", async () => {
285+
const sessions = new Map<string, SystemAgentChatSession>([["s1", seededSession()]]);
286+
const call = await callChat(makeContext(sessions), { sessionId: "s1" });
287+
288+
expect(call).toMatchObject({
289+
ok: true,
290+
payload: { sessionId: "s1", reply: "welcome text", action: "none" },
291+
});
292+
});
293+
294+
it("routes messages through the session engine", async () => {
295+
const engine = makeEngine();
296+
const sessions = new Map<string, SystemAgentChatSession>([["s1", seededSession({ engine })]]);
297+
298+
const call = await callChat(makeContext(sessions), { sessionId: "s1", message: "status" });
299+
300+
expect(engine.handle).toHaveBeenCalledWith("status");
301+
expect(call.payload).toMatchObject({ reply: "did the thing", action: "none" });
302+
});
303+
304+
it("forwards sensitive-input metadata", async () => {
305+
const engine = makeEngine();
306+
engine.handle.mockResolvedValue({
307+
text: "Enter the bot token",
308+
action: "none",
309+
sensitive: true,
310+
});
311+
const sessions = new Map<string, SystemAgentChatSession>([["s1", seededSession({ engine })]]);
312+
313+
const call = await callChat(makeContext(sessions), { sessionId: "s1", message: "yes" });
314+
315+
expect(call.payload).toMatchObject({ sensitive: true });
316+
});
317+
318+
it("maps the TUI handoff to an open-agent action", async () => {
319+
const engine = makeEngine();
320+
engine.handle.mockResolvedValue({
321+
text: "",
322+
action: "open-tui",
323+
handoff: { kind: "open-tui" },
324+
});
325+
const sessions = new Map<string, SystemAgentChatSession>([["s1", seededSession({ engine })]]);
326+
327+
const call = await callChat(makeContext(sessions), {
328+
sessionId: "s1",
329+
message: "talk to agent",
330+
});
331+
332+
expect(call.payload).toMatchObject({ action: "open-agent" });
333+
expect(call.payload).not.toHaveProperty("agentDraft");
334+
expect((call.payload as { reply: string }).reply).toContain("continue with your agent");
335+
});
336+
337+
it("forwards the hatch draft intent with an agent handoff", async () => {
338+
const engine = makeEngine();
339+
engine.handle.mockResolvedValue({
340+
text: "Your agent is hatching.",
341+
action: "open-tui",
342+
agentDraft: "hatch",
343+
handoff: { kind: "open-tui", agentId: "researcher" },
344+
});
345+
const sessions = new Map<string, SystemAgentChatSession>([["s1", seededSession({ engine })]]);
346+
347+
const call = await callChat(makeContext(sessions), { sessionId: "s1", message: "yes" });
348+
349+
expect(call.payload).toMatchObject({
350+
action: "open-agent",
351+
agentDraft: "hatch",
352+
agentId: "researcher",
353+
});
354+
});
355+
});

0 commit comments

Comments
 (0)