|
| 1 | +import fs from "node:fs/promises"; |
| 2 | +import { createServer } from "node:http"; |
| 3 | +import os from "node:os"; |
| 4 | +import path from "node:path"; |
| 5 | +import { afterEach, beforeEach, describe, expect, it } from "vitest"; |
| 6 | +import { |
| 7 | + clearConfigCache, |
| 8 | + clearRuntimeConfigSnapshot, |
| 9 | + getRuntimeConfig, |
| 10 | + writeConfigFile, |
| 11 | +} from "../config/config.js"; |
| 12 | +import { resetConfigOverrides } from "../config/runtime-overrides.js"; |
| 13 | +import { resolveStorePath } from "../config/sessions/paths.js"; |
| 14 | +import { |
| 15 | + appendTranscriptMessage, |
| 16 | + loadSessionEntry, |
| 17 | + loadTranscriptEventsSync, |
| 18 | + upsertSessionEntry, |
| 19 | +} from "../config/sessions/session-accessor.js"; |
| 20 | +import { clearSessionStoreCacheForTest } from "../config/sessions/store-writer-state.js"; |
| 21 | +import type { OpenClawConfig } from "../config/types.openclaw.js"; |
| 22 | +import { resetAgentEventsForTest } from "../infra/agent-events.js"; |
| 23 | +import { captureEnv, deleteTestEnvValue, setTestEnvValue } from "../test-utils/env.js"; |
| 24 | +import { disconnectGatewayClient, startGatewayWithClient } from "./test-helpers.e2e.js"; |
| 25 | +import { buildMockOpenAiResponsesProvider } from "./test-openai-responses-model.js"; |
| 26 | + |
| 27 | +const ISOLATED_GATEWAY_ENV_KEYS = [ |
| 28 | + "HOME", |
| 29 | + "OPENCLAW_STATE_DIR", |
| 30 | + "OPENCLAW_CONFIG_PATH", |
| 31 | + "OPENCLAW_GATEWAY_TOKEN", |
| 32 | + "OPENCLAW_TEST_GATEWAY_OVERRIDE_TOKEN", |
| 33 | + "OPENCLAW_TEST_RUNTIME_OVERRIDE_TOKEN", |
| 34 | + "OPENCLAW_TEST_MINIMAL_GATEWAY", |
| 35 | + "OPENCLAW_SKIP_CHANNELS", |
| 36 | + "OPENCLAW_SKIP_GMAIL_WATCHER", |
| 37 | + "OPENCLAW_SKIP_CRON", |
| 38 | + "OPENCLAW_SKIP_CANVAS_HOST", |
| 39 | + "OPENCLAW_SKIP_BROWSER_CONTROL_SERVER", |
| 40 | + "OPENCLAW_SKIP_PROVIDERS", |
| 41 | + "OPENCLAW_BUNDLED_PLUGINS_DIR", |
| 42 | + "OPENCLAW_DISABLE_BUNDLED_PLUGINS", |
| 43 | +] as const; |
| 44 | + |
| 45 | +let sequence = 0; |
| 46 | + |
| 47 | +function nextId(prefix: string): string { |
| 48 | + return `${prefix}-${process.pid}-${process.env.VITEST_POOL_ID ?? "0"}-${sequence++}`; |
| 49 | +} |
| 50 | + |
| 51 | +function resetGatewayState(): void { |
| 52 | + resetConfigOverrides(); |
| 53 | + clearRuntimeConfigSnapshot(); |
| 54 | + clearConfigCache(); |
| 55 | + clearSessionStoreCacheForTest(); |
| 56 | + resetAgentEventsForTest({ preserveListeners: true }); |
| 57 | +} |
| 58 | + |
| 59 | +describe("gateway compaction hot reload", () => { |
| 60 | + beforeEach(resetGatewayState); |
| 61 | + afterEach(resetGatewayState); |
| 62 | + |
| 63 | + it( |
| 64 | + "applies a hot-reloaded compaction model to automatic chat preflight without restarting", |
| 65 | + { timeout: 90_000 }, |
| 66 | + async () => { |
| 67 | + const envSnapshot = captureEnv([...ISOLATED_GATEWAY_ENV_KEYS]); |
| 68 | + const tempHome = await fs.mkdtemp( |
| 69 | + path.join(os.tmpdir(), "openclaw-gw-compaction-hot-reload-"), |
| 70 | + ); |
| 71 | + const workspaceDir = path.join(tempHome, "openclaw"); |
| 72 | + const bundledPluginsDir = path.join(tempHome, "openclaw-test-empty-bundled-plugins"); |
| 73 | + const configPath = path.join(tempHome, ".openclaw", "openclaw.json"); |
| 74 | + await Promise.all([ |
| 75 | + fs.mkdir(workspaceDir, { recursive: true }), |
| 76 | + fs.mkdir(bundledPluginsDir, { recursive: true }), |
| 77 | + fs.mkdir(path.dirname(configPath), { recursive: true }), |
| 78 | + ]); |
| 79 | + const token = nextId("compaction-hot-reload-token"); |
| 80 | + for (const [key, value] of Object.entries({ |
| 81 | + HOME: tempHome, |
| 82 | + OPENCLAW_STATE_DIR: path.join(tempHome, ".openclaw"), |
| 83 | + OPENCLAW_GATEWAY_TOKEN: token, |
| 84 | + OPENCLAW_SKIP_CHANNELS: "1", |
| 85 | + OPENCLAW_SKIP_GMAIL_WATCHER: "1", |
| 86 | + OPENCLAW_SKIP_CRON: "1", |
| 87 | + OPENCLAW_SKIP_CANVAS_HOST: "1", |
| 88 | + OPENCLAW_SKIP_BROWSER_CONTROL_SERVER: "1", |
| 89 | + OPENCLAW_SKIP_PROVIDERS: "1", |
| 90 | + OPENCLAW_BUNDLED_PLUGINS_DIR: bundledPluginsDir, |
| 91 | + OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1", |
| 92 | + })) { |
| 93 | + setTestEnvValue(key, value); |
| 94 | + } |
| 95 | + deleteTestEnvValue("OPENCLAW_CONFIG_PATH"); |
| 96 | + deleteTestEnvValue("OPENCLAW_TEST_MINIMAL_GATEWAY"); |
| 97 | + |
| 98 | + const providerRequests: string[] = []; |
| 99 | + const summaryByModel = new Map<string, string>(); |
| 100 | + const providerServer = createServer((request, response) => { |
| 101 | + void (async () => { |
| 102 | + const chunks: Buffer[] = []; |
| 103 | + for await (const chunk of request) { |
| 104 | + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); |
| 105 | + } |
| 106 | + if (request.method !== "POST" || request.url !== "/v1/responses") { |
| 107 | + response.writeHead(404).end(); |
| 108 | + return; |
| 109 | + } |
| 110 | + const body = JSON.parse(Buffer.concat(chunks).toString("utf8")) as { model?: string }; |
| 111 | + const model = body.model ?? ""; |
| 112 | + providerRequests.push(model); |
| 113 | + const text = summaryByModel.get(model) ?? "Primary assistant answer."; |
| 114 | + const message = { |
| 115 | + type: "message", |
| 116 | + id: nextId("provider-message"), |
| 117 | + role: "assistant", |
| 118 | + status: "completed", |
| 119 | + content: [{ type: "output_text", text, annotations: [] }], |
| 120 | + }; |
| 121 | + response.writeHead(200, { "content-type": "text/event-stream" }); |
| 122 | + for (const event of [ |
| 123 | + { |
| 124 | + type: "response.output_item.added", |
| 125 | + item: { ...message, status: "in_progress", content: [] }, |
| 126 | + }, |
| 127 | + { type: "response.output_item.done", item: message }, |
| 128 | + { |
| 129 | + type: "response.completed", |
| 130 | + response: { |
| 131 | + status: "completed", |
| 132 | + usage: { input_tokens: 10, output_tokens: 10, total_tokens: 20 }, |
| 133 | + }, |
| 134 | + }, |
| 135 | + ]) { |
| 136 | + response.write(`data: ${JSON.stringify(event)}\n\n`); |
| 137 | + } |
| 138 | + response.end("data: [DONE]\n\n"); |
| 139 | + })().catch((error: unknown) => { |
| 140 | + response.writeHead(500).end(error instanceof Error ? error.message : String(error)); |
| 141 | + }); |
| 142 | + }); |
| 143 | + |
| 144 | + let gateway: Awaited<ReturnType<typeof startGatewayWithClient>> | undefined; |
| 145 | + try { |
| 146 | + await new Promise<void>((resolve, reject) => { |
| 147 | + providerServer.once("error", reject); |
| 148 | + providerServer.listen(0, "127.0.0.1", resolve); |
| 149 | + }); |
| 150 | + const providerAddress = providerServer.address(); |
| 151 | + if (!providerAddress || typeof providerAddress === "string") { |
| 152 | + throw new Error("mock OpenAI Responses server did not bind a loopback port"); |
| 153 | + } |
| 154 | + const baseUrl = `http://127.0.0.1:${providerAddress.port}/v1`; |
| 155 | + const primaryModel = buildMockOpenAiResponsesProvider(baseUrl, "gpt-primary"); |
| 156 | + const oldCompactionModel = buildMockOpenAiResponsesProvider(baseUrl, "gpt-old-summary"); |
| 157 | + const newCompactionModel = buildMockOpenAiResponsesProvider(baseUrl, "gpt-new-summary"); |
| 158 | + const availableModels = [primaryModel, oldCompactionModel, newCompactionModel]; |
| 159 | + const modelDefaults = { params: { transport: "sse", openaiWsWarmup: false } }; |
| 160 | + const newSummary = "HOT_RELOAD_COMPACTION_SUMMARY"; |
| 161 | + summaryByModel.set(oldCompactionModel.modelId, "STALE_COMPACTION_SUMMARY"); |
| 162 | + summaryByModel.set(newCompactionModel.modelId, newSummary); |
| 163 | + |
| 164 | + const initialConfig = { |
| 165 | + agents: { |
| 166 | + defaults: { |
| 167 | + workspace: workspaceDir, |
| 168 | + skipBootstrap: true, |
| 169 | + model: { primary: primaryModel.modelRef }, |
| 170 | + models: Object.fromEntries( |
| 171 | + availableModels.map(({ modelRef }) => [modelRef, modelDefaults]), |
| 172 | + ), |
| 173 | + compaction: { |
| 174 | + model: oldCompactionModel.modelRef, |
| 175 | + maxActiveTranscriptBytes: "1mb", |
| 176 | + keepRecentTokens: 1, |
| 177 | + recentTurnsPreserve: 1, |
| 178 | + qualityGuard: { enabled: false }, |
| 179 | + memoryFlush: { enabled: false }, |
| 180 | + }, |
| 181 | + }, |
| 182 | + entries: { dev: { default: true } }, |
| 183 | + }, |
| 184 | + models: { |
| 185 | + mode: "replace", |
| 186 | + providers: { |
| 187 | + [primaryModel.providerId]: { |
| 188 | + ...primaryModel.config, |
| 189 | + models: Array.from(availableModels, ({ config }) => ({ |
| 190 | + ...config.models[0], |
| 191 | + input: Array.from(config.models[0].input), |
| 192 | + })), |
| 193 | + }, |
| 194 | + }, |
| 195 | + }, |
| 196 | + gateway: { auth: { mode: "token", token } }, |
| 197 | + } satisfies OpenClawConfig; |
| 198 | + |
| 199 | + gateway = await startGatewayWithClient({ |
| 200 | + cfg: initialConfig, |
| 201 | + configPath, |
| 202 | + token, |
| 203 | + clientDisplayName: "vitest-compaction-hot-reload", |
| 204 | + }); |
| 205 | + const gatewayClient = gateway.client; |
| 206 | + const sessionKey = "agent:dev:main"; |
| 207 | + const sessionId = nextId("existing-compaction-session"); |
| 208 | + const scope = { |
| 209 | + agentId: "dev", |
| 210 | + sessionId, |
| 211 | + sessionKey, |
| 212 | + storePath: resolveStorePath(undefined, { agentId: "dev" }), |
| 213 | + }; |
| 214 | + await upsertSessionEntry(scope, { |
| 215 | + sessionId, |
| 216 | + updatedAt: Date.now(), |
| 217 | + compactionCount: 0, |
| 218 | + modelProvider: primaryModel.providerId, |
| 219 | + model: primaryModel.modelId, |
| 220 | + totalTokens: 20, |
| 221 | + totalTokensFresh: true, |
| 222 | + }); |
| 223 | + const persistedContext = "persisted conversation ".repeat(24); |
| 224 | + const durableContext = "durable model context ".repeat(24); |
| 225 | + for (let turn = 0; turn < 6; turn += 1) { |
| 226 | + const timestamp = Date.now() + turn; |
| 227 | + await appendTranscriptMessage(scope, { |
| 228 | + message: { |
| 229 | + role: "user", |
| 230 | + content: `Historical request ${turn}: ${persistedContext}`, |
| 231 | + timestamp, |
| 232 | + }, |
| 233 | + }); |
| 234 | + await appendTranscriptMessage(scope, { |
| 235 | + message: { |
| 236 | + role: "assistant", |
| 237 | + content: [{ type: "text", text: `Historical answer ${turn}: ${durableContext}` }], |
| 238 | + api: "openai-responses", |
| 239 | + provider: primaryModel.providerId, |
| 240 | + model: primaryModel.modelId, |
| 241 | + usage: { |
| 242 | + input: 10, |
| 243 | + output: 10, |
| 244 | + cacheRead: 0, |
| 245 | + cacheWrite: 0, |
| 246 | + totalTokens: 20, |
| 247 | + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, |
| 248 | + }, |
| 249 | + stopReason: "stop", |
| 250 | + timestamp, |
| 251 | + }, |
| 252 | + }); |
| 253 | + } |
| 254 | + expect(loadTranscriptEventsSync(scope).length).toBeGreaterThan(10); |
| 255 | + |
| 256 | + const sendChatAndWait = async (message: string) => { |
| 257 | + const started = await gatewayClient.request<{ runId: string; status: string }>( |
| 258 | + "chat.send", |
| 259 | + { sessionKey, message, idempotencyKey: nextId("compaction-chat") }, |
| 260 | + ); |
| 261 | + expect(started.status).toBe("started"); |
| 262 | + const completed = await gatewayClient.request<{ status: string }>( |
| 263 | + "agent.wait", |
| 264 | + { runId: started.runId, timeoutMs: 30_000 }, |
| 265 | + { timeoutMs: 35_000 }, |
| 266 | + ); |
| 267 | + expect(completed.status).toBe("ok"); |
| 268 | + }; |
| 269 | + |
| 270 | + await sendChatAndWait("Warm the existing prepared model runtime."); |
| 271 | + expect(providerRequests).toContain(primaryModel.modelId); |
| 272 | + expect(loadSessionEntry(scope)?.compactionCount ?? 0).toBe(0); |
| 273 | + |
| 274 | + await writeConfigFile({ |
| 275 | + ...initialConfig, |
| 276 | + agents: { |
| 277 | + ...initialConfig.agents, |
| 278 | + defaults: { |
| 279 | + ...initialConfig.agents.defaults, |
| 280 | + compaction: { |
| 281 | + ...initialConfig.agents.defaults.compaction, |
| 282 | + model: newCompactionModel.modelRef, |
| 283 | + maxActiveTranscriptBytes: "10b", |
| 284 | + }, |
| 285 | + }, |
| 286 | + }, |
| 287 | + }); |
| 288 | + await expect |
| 289 | + .poll(() => getRuntimeConfig().agents?.defaults?.compaction, { |
| 290 | + timeout: 5_000, |
| 291 | + interval: 50, |
| 292 | + }) |
| 293 | + .toMatchObject({ model: newCompactionModel.modelRef, maxActiveTranscriptBytes: "10b" }); |
| 294 | + |
| 295 | + const requestsBeforeCompaction = providerRequests.length; |
| 296 | + await sendChatAndWait("Compact the existing conversation before answering."); |
| 297 | + |
| 298 | + const newRequests = providerRequests.slice(requestsBeforeCompaction); |
| 299 | + expect(newRequests).toContain(newCompactionModel.modelId); |
| 300 | + expect(newRequests).not.toContain(oldCompactionModel.modelId); |
| 301 | + expect(loadSessionEntry(scope)?.compactionCount).toBe(1); |
| 302 | + expect(loadTranscriptEventsSync(scope)).toContainEqual( |
| 303 | + expect.objectContaining({ |
| 304 | + type: "compaction", |
| 305 | + summary: expect.stringContaining(newSummary), |
| 306 | + }), |
| 307 | + ); |
| 308 | + await expect(gatewayClient.request("health", {})).resolves.toEqual(expect.any(Object)); |
| 309 | + } finally { |
| 310 | + if (gateway) { |
| 311 | + await disconnectGatewayClient(gateway.client); |
| 312 | + await gateway.server.close({ reason: "compaction hot reload integration test complete" }); |
| 313 | + } |
| 314 | + providerServer.closeAllConnections(); |
| 315 | + await new Promise<void>((resolve) => { |
| 316 | + providerServer.close(() => resolve()); |
| 317 | + }); |
| 318 | + await fs.rm(tempHome, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }); |
| 319 | + envSnapshot.restore(); |
| 320 | + } |
| 321 | + }, |
| 322 | + ); |
| 323 | +}); |
0 commit comments