|
| 1 | +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; |
| 2 | +import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; |
| 3 | +import { tmpdir } from "node:os"; |
| 4 | +import path from "node:path"; |
| 5 | +import { afterEach, describe, expect, it, vi } from "vitest"; |
| 6 | +import type { OpenClawConfig } from "../src/config/types.openclaw.js"; |
| 7 | +import { createDeferred } from "../src/test-utils/deferred.js"; |
| 8 | +import { GatewayChatClient } from "../src/tui/gateway-chat.js"; |
| 9 | +import { |
| 10 | + createOpenClawTestInstance, |
| 11 | + type OpenClawTestInstance, |
| 12 | +} from "./helpers/openclaw-test-instance.js"; |
| 13 | + |
| 14 | +type MockModelRequest = { |
| 15 | + body: Record<string, unknown>; |
| 16 | +}; |
| 17 | + |
| 18 | +type MockModelServer = { |
| 19 | + baseUrl: string; |
| 20 | + requests: MockModelRequest[]; |
| 21 | + releaseHeldResponse: () => void; |
| 22 | + stop: () => Promise<void>; |
| 23 | +}; |
| 24 | + |
| 25 | +const TEST_TIMEOUT_MS = 150_000; |
| 26 | +const WAIT_OPTS = { timeout: 30_000, interval: 20 } as const; |
| 27 | + |
| 28 | +const instances: OpenClawTestInstance[] = []; |
| 29 | +const cleanupDirs: string[] = []; |
| 30 | +const modelServers: MockModelServer[] = []; |
| 31 | + |
| 32 | +afterEach(async () => { |
| 33 | + await Promise.all(instances.splice(0).map((instance) => instance.cleanup())); |
| 34 | + await Promise.all(modelServers.splice(0).map((server) => server.stop())); |
| 35 | + await Promise.all(cleanupDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))); |
| 36 | +}); |
| 37 | + |
| 38 | +async function readJsonRequest(req: IncomingMessage): Promise<Record<string, unknown>> { |
| 39 | + const chunks: Buffer[] = []; |
| 40 | + for await (const chunk of req) { |
| 41 | + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); |
| 42 | + } |
| 43 | + const body = Buffer.concat(chunks).toString("utf8"); |
| 44 | + return body ? (JSON.parse(body) as Record<string, unknown>) : {}; |
| 45 | +} |
| 46 | + |
| 47 | +function writeResponse(res: ServerResponse, text: string): void { |
| 48 | + const messageId = "msg_queued_rotation"; |
| 49 | + const message = { |
| 50 | + type: "message", |
| 51 | + id: messageId, |
| 52 | + role: "assistant", |
| 53 | + status: "completed", |
| 54 | + content: [{ type: "output_text", text, annotations: [] }], |
| 55 | + }; |
| 56 | + const events = [ |
| 57 | + { |
| 58 | + type: "response.output_item.added", |
| 59 | + output_index: 0, |
| 60 | + item: { ...message, status: "in_progress", content: [] }, |
| 61 | + }, |
| 62 | + { |
| 63 | + type: "response.output_text.delta", |
| 64 | + item_id: messageId, |
| 65 | + output_index: 0, |
| 66 | + content_index: 0, |
| 67 | + delta: text, |
| 68 | + }, |
| 69 | + { |
| 70 | + type: "response.output_text.done", |
| 71 | + item_id: messageId, |
| 72 | + output_index: 0, |
| 73 | + content_index: 0, |
| 74 | + text, |
| 75 | + }, |
| 76 | + { type: "response.output_item.done", output_index: 0, item: message }, |
| 77 | + { |
| 78 | + type: "response.completed", |
| 79 | + response: { |
| 80 | + id: "resp_queued_rotation", |
| 81 | + status: "completed", |
| 82 | + output: [message], |
| 83 | + usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 }, |
| 84 | + }, |
| 85 | + }, |
| 86 | + ]; |
| 87 | + res.writeHead(200, { |
| 88 | + "content-type": "text/event-stream", |
| 89 | + "cache-control": "no-store", |
| 90 | + connection: "keep-alive", |
| 91 | + }); |
| 92 | + res.end( |
| 93 | + `${events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join("")}data: [DONE]\n\n`, |
| 94 | + ); |
| 95 | +} |
| 96 | + |
| 97 | +async function startMockModelServer(): Promise<MockModelServer> { |
| 98 | + const requests: MockModelRequest[] = []; |
| 99 | + const heldResponse = createDeferred(); |
| 100 | + const server = createServer((req, res) => { |
| 101 | + void (async () => { |
| 102 | + const url = new URL(req.url ?? "/", "http://127.0.0.1"); |
| 103 | + if (req.method === "GET" && url.pathname === "/v1/models") { |
| 104 | + res.writeHead(200, { "content-type": "application/json" }); |
| 105 | + res.end(JSON.stringify({ data: [{ id: "queued-rotation", object: "model" }] })); |
| 106 | + return; |
| 107 | + } |
| 108 | + if (req.method !== "POST" || url.pathname !== "/v1/responses") { |
| 109 | + res.writeHead(404).end(); |
| 110 | + return; |
| 111 | + } |
| 112 | + requests.push({ body: await readJsonRequest(req) }); |
| 113 | + if (requests.length === 1) { |
| 114 | + await heldResponse.promise; |
| 115 | + if (res.destroyed) { |
| 116 | + return; |
| 117 | + } |
| 118 | + } |
| 119 | + writeResponse(res, requests.length === 1 ? "FIRST_TURN_COMPLETE" : "RESET_TURN_COMPLETE"); |
| 120 | + })(); |
| 121 | + }); |
| 122 | + await new Promise<void>((resolve, reject) => { |
| 123 | + server.once("error", reject); |
| 124 | + server.listen(0, "127.0.0.1", resolve); |
| 125 | + }); |
| 126 | + const address = server.address(); |
| 127 | + if (!address || typeof address === "string") { |
| 128 | + throw new Error("mock model server did not bind"); |
| 129 | + } |
| 130 | + let stopped = false; |
| 131 | + return { |
| 132 | + baseUrl: `http://127.0.0.1:${address.port}`, |
| 133 | + requests, |
| 134 | + releaseHeldResponse: () => heldResponse.resolve(), |
| 135 | + stop: async () => { |
| 136 | + if (stopped) { |
| 137 | + return; |
| 138 | + } |
| 139 | + stopped = true; |
| 140 | + heldResponse.resolve(); |
| 141 | + await new Promise<void>((resolve, reject) => { |
| 142 | + server.close((error) => (error ? reject(error) : resolve())); |
| 143 | + server.closeAllConnections(); |
| 144 | + }); |
| 145 | + }, |
| 146 | + }; |
| 147 | +} |
| 148 | + |
| 149 | +async function writeTurnTracerPlugin(pluginDir: string, tracePath: string): Promise<void> { |
| 150 | + await writeFile( |
| 151 | + path.join(pluginDir, "openclaw.plugin.json"), |
| 152 | + JSON.stringify({ |
| 153 | + id: "queued-rotation-tracer", |
| 154 | + name: "Queued Rotation Tracer", |
| 155 | + description: "Records agent-turn preparation for the queued session rotation E2E test.", |
| 156 | + configSchema: { type: "object", additionalProperties: false, properties: {} }, |
| 157 | + }), |
| 158 | + ); |
| 159 | + await writeFile( |
| 160 | + path.join(pluginDir, "index.mjs"), |
| 161 | + [ |
| 162 | + 'import { appendFileSync } from "node:fs";', |
| 163 | + "export default {", |
| 164 | + ' id: "queued-rotation-tracer",', |
| 165 | + ' name: "Queued Rotation Tracer",', |
| 166 | + " register(api) {", |
| 167 | + ' api.on("agent_turn_prepare", () => {', |
| 168 | + ` appendFileSync(${JSON.stringify(tracePath)}, JSON.stringify({ prepared: true }) + "\\n");`, |
| 169 | + " return {};", |
| 170 | + " });", |
| 171 | + " },", |
| 172 | + "};", |
| 173 | + "", |
| 174 | + ].join("\n"), |
| 175 | + ); |
| 176 | +} |
| 177 | + |
| 178 | +async function readTraceCount(tracePath: string): Promise<number> { |
| 179 | + try { |
| 180 | + return (await readFile(tracePath, "utf8")).split("\n").filter(Boolean).length; |
| 181 | + } catch (error) { |
| 182 | + if ((error as NodeJS.ErrnoException).code === "ENOENT") { |
| 183 | + return 0; |
| 184 | + } |
| 185 | + throw error; |
| 186 | + } |
| 187 | +} |
| 188 | + |
| 189 | +describe("Gateway queued session rotation", () => { |
| 190 | + it( |
| 191 | + "runs a replacement turn after /new cancels an active turn", |
| 192 | + async () => { |
| 193 | + const fixtureDir = await mkdtemp(path.join(tmpdir(), "openclaw-queued-rotation-")); |
| 194 | + cleanupDirs.push(fixtureDir); |
| 195 | + const pluginDir = path.join(fixtureDir, "plugin"); |
| 196 | + const tracePath = path.join(fixtureDir, "turns.ndjson"); |
| 197 | + await mkdir(pluginDir, { recursive: true }); |
| 198 | + await writeTurnTracerPlugin(pluginDir, tracePath); |
| 199 | + |
| 200 | + const modelServer = await startMockModelServer(); |
| 201 | + modelServers.push(modelServer); |
| 202 | + const modelRef = "queued-rotation/queued-rotation"; |
| 203 | + const config = { |
| 204 | + plugins: { |
| 205 | + enabled: true, |
| 206 | + allow: ["queued-rotation-tracer"], |
| 207 | + load: { paths: [pluginDir] }, |
| 208 | + entries: { "queued-rotation-tracer": { enabled: true } }, |
| 209 | + slots: { memory: "none" }, |
| 210 | + }, |
| 211 | + agents: { |
| 212 | + defaults: { |
| 213 | + workspace: path.join(fixtureDir, "workspace"), |
| 214 | + model: { primary: modelRef }, |
| 215 | + models: { [modelRef]: { agentRuntime: { id: "openclaw" } } }, |
| 216 | + skills: [], |
| 217 | + skipBootstrap: true, |
| 218 | + }, |
| 219 | + list: [{ id: "main", default: true, model: { primary: modelRef }, skills: [] }], |
| 220 | + }, |
| 221 | + tools: { profile: "minimal" }, |
| 222 | + models: { |
| 223 | + mode: "replace", |
| 224 | + providers: { |
| 225 | + "queued-rotation": { |
| 226 | + baseUrl: `${modelServer.baseUrl}/v1`, |
| 227 | + apiKey: "secret-token", |
| 228 | + api: "openai-responses", |
| 229 | + request: { allowPrivateNetwork: true }, |
| 230 | + models: [ |
| 231 | + { |
| 232 | + id: "queued-rotation", |
| 233 | + name: "queued-rotation", |
| 234 | + api: "openai-responses", |
| 235 | + reasoning: false, |
| 236 | + input: ["text"], |
| 237 | + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, |
| 238 | + contextWindow: 128_000, |
| 239 | + maxTokens: 4_096, |
| 240 | + }, |
| 241 | + ], |
| 242 | + }, |
| 243 | + }, |
| 244 | + }, |
| 245 | + messages: { queue: { mode: "followup", debounceMs: 0 } }, |
| 246 | + } satisfies OpenClawConfig; |
| 247 | + const instance = await createOpenClawTestInstance({ |
| 248 | + name: "queued-session-rotation", |
| 249 | + gatewayToken: "secret-token", |
| 250 | + config, |
| 251 | + env: { OPENCLAW_SKIP_PROVIDERS: undefined }, |
| 252 | + }); |
| 253 | + instances.push(instance); |
| 254 | + await instance.startGateway(); |
| 255 | + |
| 256 | + const client = new GatewayChatClient({ |
| 257 | + url: instance.url, |
| 258 | + token: "secret-token", |
| 259 | + allowInsecureLocalOperatorUi: false, |
| 260 | + }); |
| 261 | + client.start(); |
| 262 | + await client.waitForReady(); |
| 263 | + const sessionKey = "agent:main:queued-rotation-e2e"; |
| 264 | + try { |
| 265 | + const first = await client.sendChat({ |
| 266 | + sessionKey, |
| 267 | + message: "OPENCLAW_E2E_HELD_TURN", |
| 268 | + runId: "queued-rotation-held", |
| 269 | + }); |
| 270 | + expect(first.status).toBe("started"); |
| 271 | + await vi.waitFor(async () => { |
| 272 | + expect(modelServer.requests).toHaveLength(1); |
| 273 | + expect(await readTraceCount(tracePath)).toBe(1); |
| 274 | + }, WAIT_OPTS); |
| 275 | + |
| 276 | + const replacement = await client.sendChat({ |
| 277 | + sessionKey, |
| 278 | + message: "/new OPENCLAW_E2E_AFTER_RESET", |
| 279 | + runId: "queued-rotation-reset", |
| 280 | + }); |
| 281 | + expect(replacement.status).toBe("started"); |
| 282 | + |
| 283 | + // The accepted reset turn must keep its lifecycle through cancellation and |
| 284 | + // rotation; losing it here leaves the turn before both hook and model entry. |
| 285 | + await vi.waitFor(async () => { |
| 286 | + expect(modelServer.requests).toHaveLength(2); |
| 287 | + expect(await readTraceCount(tracePath)).toBe(2); |
| 288 | + }, WAIT_OPTS); |
| 289 | + expect(JSON.stringify(modelServer.requests[0]?.body)).toContain("OPENCLAW_E2E_HELD_TURN"); |
| 290 | + expect(JSON.stringify(modelServer.requests[1]?.body)).toContain("OPENCLAW_E2E_AFTER_RESET"); |
| 291 | + } finally { |
| 292 | + await client.abortChat({ sessionKey }).catch(() => undefined); |
| 293 | + client.stop(); |
| 294 | + modelServer.releaseHeldResponse(); |
| 295 | + } |
| 296 | + }, |
| 297 | + TEST_TIMEOUT_MS, |
| 298 | + ); |
| 299 | +}); |
0 commit comments