|
| 1 | +// System-agent session lifecycle tests cover ownership, eviction, and reset boundaries. |
| 2 | + |
| 3 | +import { expectDefined } from "@openclaw/normalization-core"; |
| 4 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 5 | +import { buildSystemAgentSessionInvalidatedErrorDetails } from "../../../packages/gateway-protocol/src/index.js"; |
| 6 | +import { createDeferred } from "../../../test/helpers/promise.js"; |
| 7 | +import { resetCommandQueueStateForTest } from "../../process/command-queue.test-support.js"; |
| 8 | +import { systemAgentHandlers, type SystemAgentChatSession } from "./system-agent.js"; |
| 9 | +import type { GatewayClient, GatewayRequestContext, RespondFn } from "./types.js"; |
| 10 | + |
| 11 | +const inferenceFallbackMocks = vi.hoisted(() => ({ |
| 12 | + verifySystemAgentInferenceWithFallback: vi.fn(), |
| 13 | +})); |
| 14 | +const transcriptStoreMocks = vi.hoisted(() => ({ |
| 15 | + appendTranscriptReset: vi.fn(), |
| 16 | + appendTranscriptTurn: vi.fn(), |
| 17 | + readTranscriptTail: vi.fn( |
| 18 | + (): Array<{ role: "user" | "assistant"; text: string; at: number }> => [], |
| 19 | + ), |
| 20 | +})); |
| 21 | + |
| 22 | +vi.mock("../../system-agent/inference-fallback.js", () => ({ |
| 23 | + verifySystemAgentInferenceWithFallback: |
| 24 | + inferenceFallbackMocks.verifySystemAgentInferenceWithFallback, |
| 25 | +})); |
| 26 | +vi.mock("../../system-agent/transcript-store.js", () => transcriptStoreMocks); |
| 27 | +vi.mock("../../system-agent/greeting.js", () => ({ |
| 28 | + acknowledgeSystemAgentGreetingDelivery: vi.fn(), |
| 29 | + buildSystemAgentGreetingQuestion: vi.fn(() => undefined), |
| 30 | + loadSystemAgentGreetingFacts: vi.fn(() => ({ |
| 31 | + updateAvailable: null, |
| 32 | + channelHealth: { available: true, degraded: [] }, |
| 33 | + recentExternalEdit: false, |
| 34 | + auditSequence: 0, |
| 35 | + })), |
| 36 | + resolveSystemAgentGreeting: vi.fn(async () => ({ text: "welcome text", source: "template" })), |
| 37 | +})); |
| 38 | + |
| 39 | +type FakeEngine = { |
| 40 | + answerWizard: ReturnType<typeof vi.fn>; |
| 41 | + cancelWizard: ReturnType<typeof vi.fn>; |
| 42 | + decorateRejoinReply: ReturnType<typeof vi.fn>; |
| 43 | + dispose: ReturnType<typeof vi.fn>; |
| 44 | + getPendingOperatorProposal: ReturnType<typeof vi.fn>; |
| 45 | + handle: ReturnType<typeof vi.fn>; |
| 46 | + historyLength: ReturnType<typeof vi.fn>; |
| 47 | + historySince: ReturnType<typeof vi.fn>; |
| 48 | + loadOverview: ReturnType<typeof vi.fn>; |
| 49 | + noteAssistantMessage: ReturnType<typeof vi.fn>; |
| 50 | + resolveOperatorApproval: ReturnType<typeof vi.fn>; |
| 51 | + seedHistory: ReturnType<typeof vi.fn>; |
| 52 | +}; |
| 53 | + |
| 54 | +function makeEngine(): FakeEngine { |
| 55 | + return { |
| 56 | + answerWizard: vi.fn(), |
| 57 | + cancelWizard: vi.fn(), |
| 58 | + decorateRejoinReply: vi.fn((reply: unknown) => reply), |
| 59 | + dispose: vi.fn(async () => undefined), |
| 60 | + getPendingOperatorProposal: vi.fn(() => null), |
| 61 | + handle: vi.fn(async () => ({ text: "did the thing", action: "none" })), |
| 62 | + historyLength: vi.fn(() => 0), |
| 63 | + historySince: vi.fn(() => []), |
| 64 | + loadOverview: vi.fn(async () => ({})), |
| 65 | + noteAssistantMessage: vi.fn(), |
| 66 | + resolveOperatorApproval: vi.fn(async () => null), |
| 67 | + seedHistory: vi.fn(), |
| 68 | + }; |
| 69 | +} |
| 70 | + |
| 71 | +const createdEngines = vi.hoisted(() => [] as FakeEngine[]); |
| 72 | + |
| 73 | +vi.mock("../../system-agent/chat-engine.js", () => { |
| 74 | + class FakeSystemAgentWizardAnswerError extends Error {} |
| 75 | + return { |
| 76 | + SystemAgentWizardAnswerError: FakeSystemAgentWizardAnswerError, |
| 77 | + SystemAgentChatEngine: function FakeSystemAgentChatEngine(this: FakeEngine) { |
| 78 | + const engine = makeEngine(); |
| 79 | + createdEngines.push(engine); |
| 80 | + Object.assign(this, engine); |
| 81 | + }, |
| 82 | + }; |
| 83 | +}); |
| 84 | +vi.mock("../../system-agent/overview.js", () => ({ |
| 85 | + formatSystemAgentStartupMessage: vi.fn(() => "welcome text"), |
| 86 | +})); |
| 87 | + |
| 88 | +type RespondCall = { ok: boolean; payload?: unknown; error?: unknown }; |
| 89 | + |
| 90 | +const defaultClient = { |
| 91 | + connId: "conn-test", |
| 92 | + connect: { device: { id: "device-test" } }, |
| 93 | +} as GatewayClient; |
| 94 | + |
| 95 | +function makeContext(sessions: Map<string, SystemAgentChatSession>): GatewayRequestContext { |
| 96 | + return { systemAgentSessions: sessions } as unknown as GatewayRequestContext; |
| 97 | +} |
| 98 | + |
| 99 | +function seededSession(params?: { |
| 100 | + engine?: FakeEngine; |
| 101 | + lastUsedAt?: number; |
| 102 | + ownerKey?: string; |
| 103 | +}): SystemAgentChatSession { |
| 104 | + return { |
| 105 | + engine: params?.engine ?? makeEngine(), |
| 106 | + welcome: "welcome text", |
| 107 | + lastUsedAt: params?.lastUsedAt ?? 1, |
| 108 | + ownerKey: params?.ownerKey ?? "device:device-test", |
| 109 | + } as unknown as SystemAgentChatSession; |
| 110 | +} |
| 111 | + |
| 112 | +async function callChat( |
| 113 | + context: GatewayRequestContext, |
| 114 | + params: Record<string, unknown>, |
| 115 | +): Promise<RespondCall> { |
| 116 | + const calls: RespondCall[] = []; |
| 117 | + const respond: RespondFn = (ok, payload, error) => calls.push({ ok, payload, error }); |
| 118 | + await expectDefined( |
| 119 | + systemAgentHandlers["openclaw.chat"], |
| 120 | + 'systemAgentHandlers["openclaw.chat"] test invariant', |
| 121 | + )({ params, client: defaultClient, context, respond } as never); |
| 122 | + return expectDefined(calls[0], "system-agent response"); |
| 123 | +} |
| 124 | + |
| 125 | +const waitOneTask = () => |
| 126 | + new Promise<void>((resolve) => { |
| 127 | + setTimeout(resolve, 0); |
| 128 | + }); |
| 129 | + |
| 130 | +beforeEach(() => { |
| 131 | + createdEngines.length = 0; |
| 132 | + inferenceFallbackMocks.verifySystemAgentInferenceWithFallback.mockResolvedValue({ |
| 133 | + ok: true, |
| 134 | + binding: {}, |
| 135 | + }); |
| 136 | + transcriptStoreMocks.appendTranscriptReset.mockReset(); |
| 137 | + transcriptStoreMocks.appendTranscriptTurn.mockReset(); |
| 138 | + transcriptStoreMocks.readTranscriptTail.mockReset().mockReturnValue([]); |
| 139 | +}); |
| 140 | + |
| 141 | +afterEach(() => { |
| 142 | + vi.clearAllMocks(); |
| 143 | + resetCommandQueueStateForTest(); |
| 144 | +}); |
| 145 | + |
| 146 | +describe("openclaw.chat session lifecycle", () => { |
| 147 | + it("rejects a foreign-owner session with structured invalidation details", async () => { |
| 148 | + const sessions = new Map<string, SystemAgentChatSession>([ |
| 149 | + ["s1", seededSession({ ownerKey: "device:someone-else" })], |
| 150 | + ]); |
| 151 | + |
| 152 | + const call = await callChat(makeContext(sessions), { |
| 153 | + sessionId: "s1", |
| 154 | + message: "Hello?", |
| 155 | + }); |
| 156 | + |
| 157 | + // Persisted client session ids depend on the structured details to mint a |
| 158 | + // fresh id instead of retry-looping against the foreign live session. |
| 159 | + expect(call).toEqual({ |
| 160 | + ok: false, |
| 161 | + payload: undefined, |
| 162 | + error: { |
| 163 | + code: "INVALID_REQUEST", |
| 164 | + message: "OpenClaw session belongs to another caller.", |
| 165 | + details: buildSystemAgentSessionInvalidatedErrorDetails(), |
| 166 | + }, |
| 167 | + }); |
| 168 | + }); |
| 169 | + |
| 170 | + it("projects the live wizard interaction on a welcome-only rejoin", async () => { |
| 171 | + const engine = makeEngine(); |
| 172 | + const liveQuestion = { id: "wizard-q", header: "Pick", options: [{ label: "A" }] }; |
| 173 | + const liveStep = { id: "step-1", type: "text", message: "Enter a value" }; |
| 174 | + engine.decorateRejoinReply = vi.fn((reply: Record<string, unknown>) => ({ |
| 175 | + ...reply, |
| 176 | + sensitive: true, |
| 177 | + wizardInputPending: true, |
| 178 | + question: liveQuestion, |
| 179 | + step: liveStep, |
| 180 | + })); |
| 181 | + const session = seededSession({ engine }); |
| 182 | + (session as { welcomeQuestion?: unknown }).welcomeQuestion = { |
| 183 | + id: "welcome-q", |
| 184 | + header: "Welcome", |
| 185 | + options: [], |
| 186 | + }; |
| 187 | + const sessions = new Map<string, SystemAgentChatSession>([["s1", session]]); |
| 188 | + |
| 189 | + const call = await callChat(makeContext(sessions), { sessionId: "s1" }); |
| 190 | + |
| 191 | + // A reconnecting client must re-render the answer controls the session |
| 192 | + // still awaits; the live interaction outranks the stale welcome question. |
| 193 | + expect(call.ok).toBe(true); |
| 194 | + expect(call.payload).toMatchObject({ |
| 195 | + sessionId: "s1", |
| 196 | + sensitive: true, |
| 197 | + wizardInputPending: true, |
| 198 | + question: liveQuestion, |
| 199 | + step: liveStep, |
| 200 | + }); |
| 201 | + }); |
| 202 | + |
| 203 | + it("falls back to the welcome question when no interaction is live", async () => { |
| 204 | + const session = seededSession(); |
| 205 | + (session as { welcomeQuestion?: unknown }).welcomeQuestion = { |
| 206 | + id: "welcome-q", |
| 207 | + header: "Welcome", |
| 208 | + options: [], |
| 209 | + }; |
| 210 | + const sessions = new Map<string, SystemAgentChatSession>([["s1", session]]); |
| 211 | + |
| 212 | + const call = await callChat(makeContext(sessions), { sessionId: "s1" }); |
| 213 | + |
| 214 | + expect(call.ok).toBe(true); |
| 215 | + expect(call.payload).toMatchObject({ question: { id: "welcome-q" } }); |
| 216 | + expect((call.payload as { step?: unknown }).step).toBeUndefined(); |
| 217 | + }); |
| 218 | + |
| 219 | + it("keeps the session map bounded during concurrent unique initialization", async () => { |
| 220 | + const evictionStarted = createDeferred(); |
| 221 | + const releaseEviction = createDeferred(); |
| 222 | + const oldest = seededSession({ lastUsedAt: 0 }); |
| 223 | + oldest.engine.dispose = vi.fn(async () => { |
| 224 | + evictionStarted.resolve(); |
| 225 | + await releaseEviction.promise; |
| 226 | + }); |
| 227 | + const sessions = new Map<string, SystemAgentChatSession>([["oldest", oldest]]); |
| 228 | + for (let index = 1; index < 8; index += 1) { |
| 229 | + sessions.set(`existing-${index}`, seededSession({ lastUsedAt: index })); |
| 230 | + } |
| 231 | + |
| 232 | + const context = makeContext(sessions); |
| 233 | + const first = callChat(context, { sessionId: "new-1" }); |
| 234 | + const second = callChat(context, { sessionId: "new-2" }); |
| 235 | + await evictionStarted.promise; |
| 236 | + await waitOneTask(); |
| 237 | + releaseEviction.resolve(); |
| 238 | + await Promise.all([first, second]); |
| 239 | + |
| 240 | + expect(oldest.engine.dispose).toHaveBeenCalledOnce(); |
| 241 | + expect(sessions.size).toBe(8); |
| 242 | + expect([sessions.has("new-1"), sessions.has("new-2")]).toEqual([true, true]); |
| 243 | + }); |
| 244 | + |
| 245 | + it("resets a session on request", async () => { |
| 246 | + const engine = makeEngine(); |
| 247 | + const sessions = new Map<string, SystemAgentChatSession>([["s1", seededSession({ engine })]]); |
| 248 | + const context = makeContext(sessions); |
| 249 | + |
| 250 | + const reset = await callChat(context, { sessionId: "s1", reset: true }); |
| 251 | + |
| 252 | + expect(engine.handle).not.toHaveBeenCalled(); |
| 253 | + expect(engine.dispose).toHaveBeenCalledOnce(); |
| 254 | + expect(sessions.get("s1")?.engine).not.toBe(engine); |
| 255 | + expect(reset.ok).toBe(true); |
| 256 | + expect(transcriptStoreMocks.appendTranscriptReset).toHaveBeenCalledOnce(); |
| 257 | + expect( |
| 258 | + expectDefined(createdEngines[0], "replacement engine").seedHistory, |
| 259 | + ).not.toHaveBeenCalled(); |
| 260 | + |
| 261 | + transcriptStoreMocks.readTranscriptTail.mockReturnValue([ |
| 262 | + { role: "user", text: "After reset", at: 3 }, |
| 263 | + { role: "assistant", text: "Fresh answer", at: 4 }, |
| 264 | + ]); |
| 265 | + const fresh = await callChat(context, { sessionId: "fresh-after-reset" }); |
| 266 | + const freshEngine = expectDefined(createdEngines.at(-1), "fresh engine"); |
| 267 | + |
| 268 | + expect(fresh.ok).toBe(true); |
| 269 | + expect(freshEngine.seedHistory).toHaveBeenCalledWith([ |
| 270 | + { role: "user", text: "After reset" }, |
| 271 | + { role: "assistant", text: "Fresh answer" }, |
| 272 | + ]); |
| 273 | + expect(transcriptStoreMocks.readTranscriptTail).toHaveBeenLastCalledWith(30, { |
| 274 | + afterLastReset: true, |
| 275 | + }); |
| 276 | + }); |
| 277 | +}); |
0 commit comments