|
| 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, RespondFn } 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 | + const respond: RespondFn = (ok, payload, error) => calls.push({ ok, payload, error }); |
| 108 | + await expectDefined( |
| 109 | + systemAgentHandlers["openclaw.chat"], |
| 110 | + 'systemAgentHandlers["openclaw.chat"] test invariant', |
| 111 | + )({ |
| 112 | + params, |
| 113 | + client, |
| 114 | + context, |
| 115 | + respond, |
| 116 | + } as never); |
| 117 | + return expectDefined(calls[0], "system-agent response"); |
| 118 | +} |
| 119 | + |
| 120 | +beforeEach(() => { |
| 121 | + createdEngines.length = 0; |
| 122 | + setupInferenceMocks.verifySetupInference.mockResolvedValue({ ok: true, binding: {} }); |
| 123 | + delegatedInferenceMocks.verifySystemAgentInferenceWithFallback.mockResolvedValue({ |
| 124 | + ok: true, |
| 125 | + binding: {}, |
| 126 | + }); |
| 127 | +}); |
| 128 | + |
| 129 | +afterEach(() => { |
| 130 | + vi.clearAllMocks(); |
| 131 | + resetCommandQueueStateForTest(); |
| 132 | +}); |
| 133 | + |
| 134 | +describe("openclaw.chat session ownership", () => { |
| 135 | + it("binds a new non-delegated session and rejects another principal", async () => { |
| 136 | + const sessions = new Map<string, SystemAgentChatSession>(); |
| 137 | + const context = makeContext(sessions); |
| 138 | + const owner = makeClient({ |
| 139 | + connId: "conn-owner", |
| 140 | + deviceId: "device-owner", |
| 141 | + authenticatedUserId: "[email protected]", |
| 142 | + }); |
| 143 | + const attacker = makeClient({ |
| 144 | + connId: "conn-attacker", |
| 145 | + deviceId: "device-attacker", |
| 146 | + authenticatedUserId: "[email protected]", |
| 147 | + }); |
| 148 | + |
| 149 | + expect(await callChat(context, { sessionId: "owned-session" }, owner)).toMatchObject({ |
| 150 | + ok: true, |
| 151 | + }); |
| 152 | + expect(sessions.get("owned-session")?.ownerKey).toBe("user:[email protected]"); |
| 153 | + const handle = expectDefined(createdEngines[0], "created system-agent engine").handle; |
| 154 | + |
| 155 | + const turn = await callChat( |
| 156 | + context, |
| 157 | + { sessionId: "owned-session", message: "show status" }, |
| 158 | + attacker, |
| 159 | + ); |
| 160 | + const approval = await callChat( |
| 161 | + context, |
| 162 | + { sessionId: "owned-session", message: "yes" }, |
| 163 | + attacker, |
| 164 | + ); |
| 165 | + const reset = await callChat(context, { sessionId: "owned-session", reset: true }, attacker); |
| 166 | + |
| 167 | + expect(turn).toMatchObject({ |
| 168 | + ok: false, |
| 169 | + payload: undefined, |
| 170 | + error: { code: "INVALID_REQUEST" }, |
| 171 | + }); |
| 172 | + expect(approval).toMatchObject({ |
| 173 | + ok: false, |
| 174 | + payload: undefined, |
| 175 | + error: { code: "INVALID_REQUEST" }, |
| 176 | + }); |
| 177 | + expect(reset).toMatchObject({ |
| 178 | + ok: false, |
| 179 | + payload: undefined, |
| 180 | + error: { code: "INVALID_REQUEST" }, |
| 181 | + }); |
| 182 | + expect(handle).not.toHaveBeenCalled(); |
| 183 | + expect( |
| 184 | + expectDefined(createdEngines[0], "created system-agent engine").dispose, |
| 185 | + ).not.toHaveBeenCalled(); |
| 186 | + }); |
| 187 | + |
| 188 | + it("lets the same authenticated principal resume after reconnecting", async () => { |
| 189 | + const sessions = new Map<string, SystemAgentChatSession>(); |
| 190 | + const context = makeContext(sessions); |
| 191 | + await callChat( |
| 192 | + context, |
| 193 | + { sessionId: "reconnect" }, |
| 194 | + makeClient({ |
| 195 | + connId: "conn-old", |
| 196 | + deviceId: "device-old", |
| 197 | + authenticatedUserId: "[email protected]", |
| 198 | + }), |
| 199 | + ); |
| 200 | + const handle = expectDefined(createdEngines[0], "created system-agent engine").handle; |
| 201 | + |
| 202 | + const resumed = await callChat( |
| 203 | + context, |
| 204 | + { sessionId: "reconnect", message: "continue" }, |
| 205 | + makeClient({ |
| 206 | + connId: "conn-new", |
| 207 | + deviceId: "device-new", |
| 208 | + authenticatedUserId: "[email protected]", |
| 209 | + }), |
| 210 | + ); |
| 211 | + |
| 212 | + expect(resumed.ok).toBe(true); |
| 213 | + expect(handle).toHaveBeenCalledWith("continue"); |
| 214 | + }); |
| 215 | + |
| 216 | + it("lets the same paired device resume after reconnecting", async () => { |
| 217 | + const sessions = new Map<string, SystemAgentChatSession>(); |
| 218 | + const context = makeContext(sessions); |
| 219 | + await callChat( |
| 220 | + context, |
| 221 | + { sessionId: "device-reconnect" }, |
| 222 | + makeClient({ connId: "conn-old", deviceId: "device-owner" }), |
| 223 | + ); |
| 224 | + const handle = expectDefined(createdEngines[0], "created system-agent engine").handle; |
| 225 | + |
| 226 | + const resumed = await callChat( |
| 227 | + context, |
| 228 | + { sessionId: "device-reconnect", message: "continue" }, |
| 229 | + makeClient({ connId: "conn-new", deviceId: "device-owner" }), |
| 230 | + ); |
| 231 | + |
| 232 | + expect(resumed.ok).toBe(true); |
| 233 | + expect(handle).toHaveBeenCalledWith("continue"); |
| 234 | + }); |
| 235 | + |
| 236 | + it("rejects non-delegated chat without a server-authenticated identity", async () => { |
| 237 | + const call = await callChat(makeContext(new Map()), { sessionId: "anonymous" }, null); |
| 238 | + |
| 239 | + expect(call).toMatchObject({ ok: false, error: { code: "INVALID_REQUEST" } }); |
| 240 | + }); |
| 241 | + |
| 242 | + it("keeps explicit delegation authoritative across connection identities", async () => { |
| 243 | + const sessions = new Map<string, SystemAgentChatSession>(); |
| 244 | + const context = makeContext(sessions); |
| 245 | + const delegation = { agentId: "main", sessionKey: "agent:main:main" }; |
| 246 | + await callChat( |
| 247 | + context, |
| 248 | + { sessionId: "delegated", delegation }, |
| 249 | + makeClient({ connId: "conn-owner", deviceId: "device-owner" }), |
| 250 | + ); |
| 251 | + const handle = expectDefined(createdEngines[0], "created delegated engine").handle; |
| 252 | + |
| 253 | + const resumed = await callChat( |
| 254 | + context, |
| 255 | + { sessionId: "delegated", message: "continue", delegation }, |
| 256 | + makeClient({ |
| 257 | + connId: "conn-other", |
| 258 | + deviceId: "device-other", |
| 259 | + authenticatedUserId: "[email protected]", |
| 260 | + }), |
| 261 | + ); |
| 262 | + |
| 263 | + expect(resumed.ok).toBe(true); |
| 264 | + expect(handle).toHaveBeenCalledWith("continue"); |
| 265 | + }); |
| 266 | + |
| 267 | + it("rejects delegated reuse of a non-delegated session", async () => { |
| 268 | + const engine = makeEngine(); |
| 269 | + const sessions = new Map<string, SystemAgentChatSession>([ |
| 270 | + ["shared", seededSession({ engine })], |
| 271 | + ]); |
| 272 | + |
| 273 | + const delegated = await callChat(makeContext(sessions), { |
| 274 | + sessionId: "shared", |
| 275 | + message: "yes", |
| 276 | + delegation: { agentId: "main", sessionKey: "agent:main:main" }, |
| 277 | + }); |
| 278 | + |
| 279 | + expect(delegated).toMatchObject({ ok: false, error: { code: "INVALID_REQUEST" } }); |
| 280 | + expect(engine.handle).not.toHaveBeenCalled(); |
| 281 | + }); |
| 282 | +}); |
| 283 | + |
| 284 | +describe("openclaw.chat session responses", () => { |
| 285 | + it("returns the stored welcome when no message is sent", async () => { |
| 286 | + const sessions = new Map<string, SystemAgentChatSession>([["s1", seededSession()]]); |
| 287 | + const call = await callChat(makeContext(sessions), { sessionId: "s1" }); |
| 288 | + |
| 289 | + expect(call).toMatchObject({ |
| 290 | + ok: true, |
| 291 | + payload: { sessionId: "s1", reply: "welcome text", action: "none" }, |
| 292 | + }); |
| 293 | + }); |
| 294 | + |
| 295 | + it("routes messages through the session engine", async () => { |
| 296 | + const engine = makeEngine(); |
| 297 | + const sessions = new Map<string, SystemAgentChatSession>([["s1", seededSession({ engine })]]); |
| 298 | + |
| 299 | + const call = await callChat(makeContext(sessions), { sessionId: "s1", message: "status" }); |
| 300 | + |
| 301 | + expect(engine.handle).toHaveBeenCalledWith("status"); |
| 302 | + expect(call.payload).toMatchObject({ reply: "did the thing", action: "none" }); |
| 303 | + }); |
| 304 | + |
| 305 | + it("forwards sensitive-input metadata", async () => { |
| 306 | + const engine = makeEngine(); |
| 307 | + engine.handle.mockResolvedValue({ |
| 308 | + text: "Enter the bot token", |
| 309 | + action: "none", |
| 310 | + sensitive: true, |
| 311 | + }); |
| 312 | + const sessions = new Map<string, SystemAgentChatSession>([["s1", seededSession({ engine })]]); |
| 313 | + |
| 314 | + const call = await callChat(makeContext(sessions), { sessionId: "s1", message: "yes" }); |
| 315 | + |
| 316 | + expect(call.payload).toMatchObject({ sensitive: true }); |
| 317 | + }); |
| 318 | + |
| 319 | + it("maps the TUI handoff to an open-agent action", async () => { |
| 320 | + const engine = makeEngine(); |
| 321 | + engine.handle.mockResolvedValue({ |
| 322 | + text: "", |
| 323 | + action: "open-tui", |
| 324 | + handoff: { kind: "open-tui" }, |
| 325 | + }); |
| 326 | + const sessions = new Map<string, SystemAgentChatSession>([["s1", seededSession({ engine })]]); |
| 327 | + |
| 328 | + const call = await callChat(makeContext(sessions), { |
| 329 | + sessionId: "s1", |
| 330 | + message: "talk to agent", |
| 331 | + }); |
| 332 | + |
| 333 | + expect(call.payload).toMatchObject({ action: "open-agent" }); |
| 334 | + expect(call.payload).not.toHaveProperty("agentDraft"); |
| 335 | + expect((call.payload as { reply: string }).reply).toContain("continue with your agent"); |
| 336 | + }); |
| 337 | + |
| 338 | + it("forwards the hatch draft intent with an agent handoff", async () => { |
| 339 | + const engine = makeEngine(); |
| 340 | + engine.handle.mockResolvedValue({ |
| 341 | + text: "Your agent is hatching.", |
| 342 | + action: "open-tui", |
| 343 | + agentDraft: "hatch", |
| 344 | + handoff: { kind: "open-tui", agentId: "researcher" }, |
| 345 | + }); |
| 346 | + const sessions = new Map<string, SystemAgentChatSession>([["s1", seededSession({ engine })]]); |
| 347 | + |
| 348 | + const call = await callChat(makeContext(sessions), { sessionId: "s1", message: "yes" }); |
| 349 | + |
| 350 | + expect(call.payload).toMatchObject({ |
| 351 | + action: "open-agent", |
| 352 | + agentDraft: "hatch", |
| 353 | + agentId: "researcher", |
| 354 | + }); |
| 355 | + }); |
| 356 | +}); |
0 commit comments