|
| 1 | +// Focused welcome-delivery tests for openclaw.chat: caretaker greeting wiring, |
| 2 | +// audit-cursor acknowledgement, and the onboarding template path. |
| 3 | + |
| 4 | +import { expectDefined } from "@openclaw/normalization-core"; |
| 5 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 6 | +import { resetCommandQueueStateForTest } from "../../process/command-queue.test-support.js"; |
| 7 | +import { systemAgentHandlers, type SystemAgentChatSession } from "./system-agent.js"; |
| 8 | +import type { GatewayClient, GatewayRequestContext } from "./types.js"; |
| 9 | + |
| 10 | +const setupInferenceMocks = vi.hoisted(() => ({ verifySetupInference: vi.fn() })); |
| 11 | +const transcriptStoreMocks = vi.hoisted(() => ({ |
| 12 | + appendTranscriptReset: vi.fn(), |
| 13 | + appendTranscriptTurn: vi.fn(), |
| 14 | + readTranscriptTail: vi.fn(() => []), |
| 15 | +})); |
| 16 | +const greetingMocks = vi.hoisted(() => ({ |
| 17 | + acknowledgeSystemAgentGreetingDelivery: vi.fn(), |
| 18 | + buildSystemAgentGreetingQuestion: vi.fn(), |
| 19 | + loadSystemAgentGreetingFacts: vi.fn(), |
| 20 | + resolveSystemAgentGreeting: vi.fn(), |
| 21 | +})); |
| 22 | +const onboardingWelcomeMocks = vi.hoisted(() => ({ buildOnboardingWelcome: vi.fn() })); |
| 23 | + |
| 24 | +vi.mock("../../system-agent/setup-inference.js", () => ({ |
| 25 | + verifySetupInference: setupInferenceMocks.verifySetupInference, |
| 26 | +})); |
| 27 | +vi.mock("../../system-agent/transcript-store.js", () => ({ |
| 28 | + appendTranscriptReset: transcriptStoreMocks.appendTranscriptReset, |
| 29 | + appendTranscriptTurn: transcriptStoreMocks.appendTranscriptTurn, |
| 30 | + readTranscriptTail: transcriptStoreMocks.readTranscriptTail, |
| 31 | +})); |
| 32 | +vi.mock("../../system-agent/greeting.js", () => ({ |
| 33 | + acknowledgeSystemAgentGreetingDelivery: greetingMocks.acknowledgeSystemAgentGreetingDelivery, |
| 34 | + buildSystemAgentGreetingQuestion: greetingMocks.buildSystemAgentGreetingQuestion, |
| 35 | + loadSystemAgentGreetingFacts: greetingMocks.loadSystemAgentGreetingFacts, |
| 36 | + resolveSystemAgentGreeting: greetingMocks.resolveSystemAgentGreeting, |
| 37 | +})); |
| 38 | +vi.mock("../../system-agent/onboarding-welcome.js", () => ({ |
| 39 | + buildOnboardingWelcome: onboardingWelcomeMocks.buildOnboardingWelcome, |
| 40 | +})); |
| 41 | + |
| 42 | +type FakeEngine = { |
| 43 | + handle: ReturnType<typeof vi.fn>; |
| 44 | + seedHistory: ReturnType<typeof vi.fn>; |
| 45 | + historyLength: ReturnType<typeof vi.fn>; |
| 46 | + historySince: ReturnType<typeof vi.fn>; |
| 47 | + getPendingOperatorProposal: ReturnType<typeof vi.fn>; |
| 48 | + resolveOperatorApproval: ReturnType<typeof vi.fn>; |
| 49 | + dispose: ReturnType<typeof vi.fn>; |
| 50 | + loadOverview: ReturnType<typeof vi.fn>; |
| 51 | + noteAssistantMessage: ReturnType<typeof vi.fn>; |
| 52 | + planGreeting: ReturnType<typeof vi.fn>; |
| 53 | +}; |
| 54 | + |
| 55 | +function makeEngine(): FakeEngine { |
| 56 | + // Mirrors persistEngineHistory's contract: noted assistant messages appear |
| 57 | + // in historySince so the welcome is persisted before acknowledgement. |
| 58 | + const history: Array<{ role: "user" | "assistant"; text: string }> = []; |
| 59 | + return { |
| 60 | + handle: vi.fn(async () => ({ text: "did the thing", action: "none" })), |
| 61 | + seedHistory: vi.fn(), |
| 62 | + historyLength: vi.fn(() => history.length), |
| 63 | + historySince: vi.fn((index: number) => history.slice(index)), |
| 64 | + getPendingOperatorProposal: vi.fn(() => null), |
| 65 | + resolveOperatorApproval: vi.fn(async () => null), |
| 66 | + dispose: vi.fn(async () => undefined), |
| 67 | + loadOverview: vi.fn(async () => ({})), |
| 68 | + noteAssistantMessage: vi.fn((text: string) => { |
| 69 | + history.push({ role: "assistant", text }); |
| 70 | + }), |
| 71 | + planGreeting: vi.fn(), |
| 72 | + }; |
| 73 | +} |
| 74 | + |
| 75 | +const createdEngines = vi.hoisted(() => [] as FakeEngine[]); |
| 76 | + |
| 77 | +vi.mock("../../system-agent/chat-engine.js", () => ({ |
| 78 | + SystemAgentChatEngine: function FakeSystemAgentChatEngine(this: FakeEngine) { |
| 79 | + const engine = makeEngine(); |
| 80 | + createdEngines.push(engine); |
| 81 | + Object.assign(this, engine); |
| 82 | + }, |
| 83 | +})); |
| 84 | + |
| 85 | +type RespondCall = { ok: boolean; payload?: unknown; error?: unknown }; |
| 86 | + |
| 87 | +const defaultClient = { |
| 88 | + connId: "conn-test", |
| 89 | + connect: { device: { id: "device-test" } }, |
| 90 | +} as GatewayClient; |
| 91 | + |
| 92 | +function makeContext(sessions: Map<string, SystemAgentChatSession>): GatewayRequestContext { |
| 93 | + return { systemAgentSessions: sessions } as unknown as GatewayRequestContext; |
| 94 | +} |
| 95 | + |
| 96 | +async function callChat( |
| 97 | + context: GatewayRequestContext, |
| 98 | + params: Record<string, unknown>, |
| 99 | +): Promise<RespondCall> { |
| 100 | + const calls: RespondCall[] = []; |
| 101 | + const respond = (ok: boolean, payload?: unknown, error?: unknown) => { |
| 102 | + calls.push({ ok, payload, error }); |
| 103 | + }; |
| 104 | + await expectDefined( |
| 105 | + systemAgentHandlers["openclaw.chat"], |
| 106 | + 'systemAgentHandlers["openclaw.chat"] test invariant', |
| 107 | + )({ params, respond, context, client: defaultClient } as never); |
| 108 | + return expectDefined(calls[0], "system-agent response"); |
| 109 | +} |
| 110 | + |
| 111 | +const quickActions = { |
| 112 | + id: "system-agent-quick-actions", |
| 113 | + header: "Quick actions", |
| 114 | + question: "What would you like me to do?", |
| 115 | + options: [ |
| 116 | + { label: "Show update", reply: "status" }, |
| 117 | + { label: "Talk to my agent", reply: "talk to agent" }, |
| 118 | + { label: "Review recent changes", reply: "audit" }, |
| 119 | + ], |
| 120 | +}; |
| 121 | + |
| 122 | +beforeEach(() => { |
| 123 | + createdEngines.length = 0; |
| 124 | + setupInferenceMocks.verifySetupInference.mockResolvedValue({ ok: true, binding: {} }); |
| 125 | + greetingMocks.loadSystemAgentGreetingFacts.mockReturnValue({ |
| 126 | + updateAvailable: null, |
| 127 | + channelHealth: { available: true, degraded: [] }, |
| 128 | + recentExternalEdit: false, |
| 129 | + auditSequence: 0, |
| 130 | + }); |
| 131 | + greetingMocks.resolveSystemAgentGreeting.mockResolvedValue({ |
| 132 | + text: "I'm OpenClaw. All systems nominal.", |
| 133 | + source: "model", |
| 134 | + }); |
| 135 | + greetingMocks.buildSystemAgentGreetingQuestion.mockReturnValue(quickActions); |
| 136 | + onboardingWelcomeMocks.buildOnboardingWelcome.mockResolvedValue({ |
| 137 | + text: "Inference is ready. Let's finish setup.", |
| 138 | + }); |
| 139 | +}); |
| 140 | + |
| 141 | +afterEach(() => { |
| 142 | + vi.clearAllMocks(); |
| 143 | + transcriptStoreMocks.readTranscriptTail.mockReturnValue([]); |
| 144 | + resetCommandQueueStateForTest(); |
| 145 | +}); |
| 146 | + |
| 147 | +describe("openclaw.chat caretaker welcome", () => { |
| 148 | + it("returns caretaker quick actions and persists the resolved greeting", async () => { |
| 149 | + greetingMocks.loadSystemAgentGreetingFacts.mockReturnValueOnce({ |
| 150 | + updateAvailable: "2026.7.20", |
| 151 | + channelHealth: { available: true, degraded: [] }, |
| 152 | + recentExternalEdit: true, |
| 153 | + auditSequence: 42, |
| 154 | + }); |
| 155 | + greetingMocks.resolveSystemAgentGreeting.mockResolvedValueOnce({ |
| 156 | + text: "I'm healthy. An update is ready, and I noticed a manual config edit.", |
| 157 | + source: "model", |
| 158 | + }); |
| 159 | + |
| 160 | + const call = await callChat(makeContext(new Map()), { sessionId: "caretaker-welcome" }); |
| 161 | + |
| 162 | + expect(call.payload).toMatchObject({ |
| 163 | + reply: "I'm healthy. An update is ready, and I noticed a manual config edit.", |
| 164 | + question: { |
| 165 | + header: "Quick actions", |
| 166 | + options: [ |
| 167 | + { label: "Show update", reply: "status" }, |
| 168 | + { label: "Talk to my agent", reply: "talk to agent" }, |
| 169 | + { label: "Review recent changes", reply: "audit" }, |
| 170 | + ], |
| 171 | + }, |
| 172 | + }); |
| 173 | + expect(greetingMocks.resolveSystemAgentGreeting).toHaveBeenCalledWith( |
| 174 | + expect.objectContaining({ allowInference: true }), |
| 175 | + ); |
| 176 | + expect(transcriptStoreMocks.appendTranscriptTurn).toHaveBeenCalledWith( |
| 177 | + expect.objectContaining({ |
| 178 | + role: "assistant", |
| 179 | + text: "I'm healthy. An update is ready, and I noticed a manual config edit.", |
| 180 | + }), |
| 181 | + ); |
| 182 | + expect(greetingMocks.acknowledgeSystemAgentGreetingDelivery).toHaveBeenCalledWith({ |
| 183 | + auditSequence: 42, |
| 184 | + }); |
| 185 | + expect(transcriptStoreMocks.appendTranscriptTurn.mock.invocationCallOrder[0]).toBeLessThan( |
| 186 | + greetingMocks.acknowledgeSystemAgentGreetingDelivery.mock.invocationCallOrder[0] ?? 0, |
| 187 | + ); |
| 188 | + }); |
| 189 | + |
| 190 | + it("does not plan a greeting when a fresh session is created with a message", async () => { |
| 191 | + const sessions = new Map<string, SystemAgentChatSession>(); |
| 192 | + greetingMocks.resolveSystemAgentGreeting.mockResolvedValueOnce({ |
| 193 | + text: "Hi, I'm OpenClaw — caretaker of this gateway, config, channels, and agents.", |
| 194 | + source: "template", |
| 195 | + }); |
| 196 | + |
| 197 | + const context = makeContext(sessions); |
| 198 | + const call = await callChat(context, { |
| 199 | + sessionId: "fresh-with-message", |
| 200 | + message: "status", |
| 201 | + }); |
| 202 | + |
| 203 | + expect(call.payload).toMatchObject({ reply: "did the thing", action: "none" }); |
| 204 | + expect(greetingMocks.resolveSystemAgentGreeting).toHaveBeenCalledWith( |
| 205 | + expect.objectContaining({ allowInference: false }), |
| 206 | + ); |
| 207 | + expect(createdEngines[0]?.planGreeting).not.toHaveBeenCalled(); |
| 208 | + expect(greetingMocks.acknowledgeSystemAgentGreetingDelivery).not.toHaveBeenCalled(); |
| 209 | + |
| 210 | + expect(sessions.get("fresh-with-message")?.welcomeAuditSequence).toBe(0); |
| 211 | + const welcome = await callChat(context, { sessionId: "fresh-with-message" }); |
| 212 | + expect(welcome.payload).toMatchObject({ |
| 213 | + reply: "Hi, I'm OpenClaw — caretaker of this gateway, config, channels, and agents.", |
| 214 | + }); |
| 215 | + expect(greetingMocks.acknowledgeSystemAgentGreetingDelivery).toHaveBeenCalledWith({ |
| 216 | + auditSequence: 0, |
| 217 | + }); |
| 218 | + expect(sessions.get("fresh-with-message")?.welcomeAuditSequence).toBeUndefined(); |
| 219 | + }); |
| 220 | + |
| 221 | + it("does not acknowledge audit entries when greeting delivery fails", async () => { |
| 222 | + const sessions = new Map<string, SystemAgentChatSession>(); |
| 223 | + const context = makeContext(sessions); |
| 224 | + greetingMocks.loadSystemAgentGreetingFacts.mockReturnValueOnce({ |
| 225 | + updateAvailable: null, |
| 226 | + channelHealth: { available: true, degraded: [] }, |
| 227 | + recentExternalEdit: true, |
| 228 | + auditSequence: 42, |
| 229 | + }); |
| 230 | + |
| 231 | + await expect( |
| 232 | + expectDefined( |
| 233 | + systemAgentHandlers["openclaw.chat"], |
| 234 | + 'systemAgentHandlers["openclaw.chat"] test invariant', |
| 235 | + )({ |
| 236 | + params: { sessionId: "failed-delivery" }, |
| 237 | + respond: () => { |
| 238 | + throw new Error("socket closed"); |
| 239 | + }, |
| 240 | + context, |
| 241 | + client: defaultClient, |
| 242 | + } as never), |
| 243 | + ).rejects.toThrow("socket closed"); |
| 244 | + |
| 245 | + expect(transcriptStoreMocks.appendTranscriptTurn).toHaveBeenCalled(); |
| 246 | + expect(greetingMocks.acknowledgeSystemAgentGreetingDelivery).not.toHaveBeenCalled(); |
| 247 | + expect(sessions.get("failed-delivery")?.welcomeAuditSequence).toBe(42); |
| 248 | + |
| 249 | + const retry = await callChat(context, { sessionId: "failed-delivery" }); |
| 250 | + expect(retry.payload).toMatchObject({ reply: "I'm OpenClaw. All systems nominal." }); |
| 251 | + expect(greetingMocks.acknowledgeSystemAgentGreetingDelivery).toHaveBeenCalledWith({ |
| 252 | + auditSequence: 42, |
| 253 | + }); |
| 254 | + expect(sessions.get("failed-delivery")?.welcomeAuditSequence).toBeUndefined(); |
| 255 | + }); |
| 256 | + |
| 257 | + it("keeps onboarding on its dedicated template path", async () => { |
| 258 | + const call = await callChat(makeContext(new Map()), { |
| 259 | + sessionId: "onboarding-welcome", |
| 260 | + welcomeVariant: "onboarding", |
| 261 | + }); |
| 262 | + |
| 263 | + expect(call.payload).toMatchObject({ reply: "Inference is ready. Let's finish setup." }); |
| 264 | + expect(onboardingWelcomeMocks.buildOnboardingWelcome).toHaveBeenCalledOnce(); |
| 265 | + expect(greetingMocks.loadSystemAgentGreetingFacts).not.toHaveBeenCalled(); |
| 266 | + expect(greetingMocks.resolveSystemAgentGreeting).not.toHaveBeenCalled(); |
| 267 | + expect(greetingMocks.acknowledgeSystemAgentGreetingDelivery).not.toHaveBeenCalled(); |
| 268 | + }); |
| 269 | +}); |
0 commit comments