返回 CodeWhale
lib.test.mjs
根目录 / integrations / bridge-core / test / lib.test.mjs
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import path from "node:path";
6 import { spawn } from "node:child_process";
7
8 import {
9 activeTurnBlock,
10 commandAction,
11 createRuntimeClient,
12 envFirst,
13 parseBool,
14 parseCommand,
15 parseEnvText,
16 parseList,
17 parseQuestionAnswers,
18 parseTextContent,
19 preservedChatStateFields,
20 readJsonSafe,
21 readSse,
22 splitAtCodePoint,
23 splitMessage,
24 stripGroupPrefix,
25 ThreadStore,
26 writeFileDurable,
27 observeTurn
28 } from "../src/lib.mjs";
29
30 test("env and primitive parsers handle bridge env conventions", () => {
31 assert.equal(envFirst({ A: "", B: " value " }, "A", "B"), "value");
32 assert.deepEqual(parseList(" a, b ,, "), ["a", "b"]);
33 assert.equal(parseBool("yes"), true);
34 assert.equal(parseBool("0", true), false);
35 assert.deepEqual(parseEnvText("export A='one'\nB=\"two\"\n# nope"), { A: "one", B: "two" });
36 assert.deepEqual(parseEnvText("A='\nB=\"\nEMPTY=\"\""), { A: "'", B: '"', EMPTY: "" });
37 });
38
39 test("parseTextContent supports plain text and JSON text/content wrappers", () => {
40 assert.equal(parseTextContent("hello"), "hello");
41 assert.equal(parseTextContent(JSON.stringify({ text: "hello" })), "hello");
42 assert.equal(parseTextContent(JSON.stringify({ content: "hello" })), "hello");
43 assert.equal(parseTextContent(JSON.stringify({ text: " ", content: "fallback" })), "fallback");
44 assert.equal(parseTextContent(JSON.stringify({ text: "" })), "");
45 });
46
47 test("stripGroupPrefix supports direct chat types and prefixed group text", () => {
48 assert.deepEqual(
49 stripGroupPrefix("inspect", {
50 chatType: "private",
51 requirePrefix: true,
52 prefix: "/cw",
53 directChatTypes: ["private"]
54 }),
55 { accepted: true, text: "inspect" }
56 );
57 assert.deepEqual(
58 stripGroupPrefix("/cw inspect", {
59 chatType: "group",
60 requirePrefix: true,
61 prefix: "/cw",
62 directChatTypes: ["private"]
63 }),
64 { accepted: true, text: "inspect" }
65 );
66 });
67
68 test("stripGroupPrefix accepts prompts after a line break or tab", () => {
69 const options = { chatType: "group", requirePrefix: true, prefix: "/cw" };
70 const prompt = "Inspect this\n indented example";
71 assert.deepEqual(stripGroupPrefix(`/cw\n${prompt}`, options), { accepted: true, text: prompt });
72 assert.deepEqual(stripGroupPrefix(`/cw\t${prompt}`, options), { accepted: true, text: prompt });
73 assert.deepEqual(stripGroupPrefix(`/cwbot ${prompt}`, options), { accepted: false, text: "" });
74 assert.deepEqual(stripGroupPrefix("/cw", options), { accepted: true, text: "/help" });
75 });
76
77 test("commands map common actions while menu/start stay opt in", () => {
78 assert.deepEqual(parseCommand("/allow@CodeWhaleBot ap_1 remember", { stripBotMention: true }), {
79 name: "allow",
80 args: "ap_1 remember"
81 });
82 assert.deepEqual(parseCommand("/allow@CodeWhaleBot ap_1 remember"), {
83 name: "allow@codewhalebot",
84 args: "ap_1 remember"
85 });
86 assert.deepEqual(commandAction(parseCommand("/status")), { kind: "status" });
87 assert.deepEqual(commandAction(parseCommand("/menu")), { kind: "prompt", prompt: "/menu" });
88 assert.deepEqual(commandAction(parseCommand("/menu"), { allowMenu: true }), { kind: "menu" });
89 assert.deepEqual(commandAction(parseCommand("/start"), { allowStart: true }), { kind: "help" });
90 });
91
92 test("multi-select questions accept comma-separated option labels", () => {
93 const question = {
94 id: "actions",
95 multi_select: true,
96 options: [{ label: "Inspect files" }, { label: "List tests" }, { label: "Open, then close" }]
97 };
98 const request = { questions: [question] };
99 const answer = (label) => ({ id: question.id, label, value: label });
100 const selected = [answer("Inspect files"), answer("List tests")];
101 assert.deepEqual(parseQuestionAnswers(request, "inspect files, List tests"), selected);
102 assert.deepEqual(parseQuestionAnswers(request, "Inspect files,List tests"), selected);
103 assert.deepEqual(parseQuestionAnswers(request, "1, 2"), selected);
104 assert.deepEqual(parseQuestionAnswers(request, "Open, then close"), [answer("Open, then close")]);
105 assert.equal(parseQuestionAnswers(request, "Inspect files, Unknown"), null);
106 assert.equal(parseQuestionAnswers({ questions: [{ ...question, multi_select: false }] }, "Inspect files, List tests"), null);
107 });
108
109 test("state/message/runtime helpers preserve bridge behavior", () => {
110 assert.deepEqual(
111 preservedChatStateFields({ model: "m", replyToMessageId: "r", ignored: true }, [
112 "model",
113 "replyToMessageId"
114 ]),
115 { model: "m", replyToMessageId: "r" }
116 );
117 assert.deepEqual(splitMessage("a🧪b", 2), ["a🧪", "b"]);
118 assert.deepEqual(splitMessage("alpha beta gamma", 12), ["alpha beta ", "gamma"]);
119 const fenced = splitMessage("```js\nconst first = 1;\nconst second = 2;\n```\nDone", 24);
120 assert.ok(fenced.length > 1);
121 assert.equal(fenced[0].endsWith("\n```"), true);
122 assert.equal(fenced[1].startsWith("```js\n"), true);
123 assert.equal(fenced.at(-1).includes("Done"), true);
124 for (const chunk of fenced) {
125 assert.ok(Array.from(chunk).length <= 24);
126 assert.equal((chunk.match(/```/g) || []).length % 2, 0);
127 }
128 assert.deepEqual(activeTurnBlock({ turns: [{ id: "t1", status: "queued" }] }), {
129 turnId: "t1",
130 message: "Thread already has active turn t1. Wait for it to finish or send /interrupt."
131 });
132 assert.deepEqual(activeTurnBlock({ turns: [{ status: "in_progress" }] }, null), {
133 turnId: "",
134 message: "Thread already has active turn (unknown). Wait for it to finish or send /interrupt."
135 });
136 });
137
138 test("a long first code line does not produce a fence-only reply", () => {
139 const opening = "```text\n";
140 const closing = "\n```";
141 const line = "x".repeat(3600);
142 const chunks = splitMessage(`${opening}${line}${closing}`);
143
144 assert.equal(chunks.length, 2);
145 for (const chunk of chunks) {
146 assert.ok(chunk.startsWith(opening));
147 assert.ok(chunk.endsWith(closing));
148 assert.ok(Array.from(chunk).length <= 3500);
149 }
150 assert.equal(chunks.map((chunk) => chunk.slice(opening.length, -closing.length)).join(""), line);
151
152 const prefixed = splitMessage(`\n${opening}${line}${closing}`);
153 assert.equal(prefixed.length, 2);
154 assert.ok(prefixed[0].trimStart().startsWith(opening));
155 assert.ok(prefixed[0].includes("xxx"));
156
157 const proseThenCode = splitMessage(`Intro line\n${opening}${"y".repeat(60)}${closing}`, 30);
158 assert.equal(proseThenCode[0], "Intro line\n");
159 assert.ok(proseThenCode[1].startsWith(opening));
160 assert.ok(proseThenCode[1].includes("yyy"));
161 for (const chunk of proseThenCode) {
162 assert.ok(Array.from(chunk).length <= 30);
163 assert.equal((chunk.match(/```/g) || []).length % 2, 0);
164 }
165 });
166
167 test("splitMessage preserves an outer Markdown fence around literal shorter fences", () => {
168 const opening = "````markdown\n";
169 const closing = "````";
170 const example = "```js\n" + 'console.log("示例");\n'.repeat(260) + "```\n";
171 const chunks = splitMessage(`${opening}${example}${closing}`, 3500, 3800);
172
173 assert.ok(chunks.length > 1);
174 for (const chunk of chunks) {
175 assert.ok(chunk.startsWith(opening), "each reply reopens the outer four-backtick fence");
176 assert.ok(chunk.endsWith(`\n${closing}`), "each reply closes the outer four-backtick fence");
177 assert.ok(Array.from(chunk).length <= 3500);
178 assert.ok(Buffer.byteLength(chunk, "utf8") <= 3800);
179 }
180 assert.equal(chunks.map((chunk) => chunk.slice(opening.length, -closing.length)).join(""), example);
181 });
182
183 test("splitMessage keeps the original text when there is no room to wrap a wide fence", () => {
184 const marker = "`".repeat(12);
185 const text = `${marker}md\nhello\nworld\n${marker}`;
186 for (const [maxChars, maxBytes] of [[24, 0], [100, 24]]) {
187 const chunks = splitMessage(text, maxChars, maxBytes);
188 assert.ok(chunks.length > 1);
189 assert.ok(chunks.every((chunk) => Array.from(chunk).length <= maxChars));
190 assert.ok(!maxBytes || chunks.every((chunk) => Buffer.byteLength(chunk, "utf8") <= maxBytes));
191 assert.equal(chunks.join(""), text);
192 }
193 });
194
195 test("ThreadStore supports chat state, message dedupe, and action tokens", async () => {
196 const dir = await mkdtemp(path.join(tmpdir(), "codewhale-bridge-core-"));
197 try {
198 const statePath = path.join(dir, "thread-map.json");
199 const store = await ThreadStore.open(statePath, {
200 messageLimit: 2,
201 actions: true,
202 actionLimit: 2
203 });
204
205 await store.setChat("chat-a", { threadId: "thread-a" });
206 assert.equal((await store.getChat("chat-a")).threadId, "thread-a");
207
208 assert.equal(await store.recordMessage("m1"), false);
209 assert.equal(await store.recordMessage("m1"), true);
210 assert.equal(await store.recordMessage("m2"), false);
211 assert.equal(await store.recordMessage("m3"), false);
212 assert.deepEqual(store.data.messages, ["m2", "m3"]);
213
214 const token = await store.putAction({ kind: "resume", threadId: "thread-a" }, { chatId: "chat-a" });
215 assert.equal((await store.getAction(token, { chatId: "chat-a" })).kind, "resume");
216 assert.equal((await store.takeAction(token, { chatId: "chat-a" })).threadId, "thread-a");
217 assert.equal(await store.getAction(token, { chatId: "chat-a" }), null);
218
219 const saved = await ThreadStore.open(statePath, { messageLimit: 2, actions: true });
220 assert.equal((await saved.getChat("chat-a")).threadId, "thread-a");
221 assert.deepEqual(saved.data.messages, ["m2", "m3"]);
222 } finally {
223 await rm(dir, { recursive: true, force: true });
224 }
225 });
226
227 test("action tokens remain distinct when clock and legacy randomness repeat", async (t) => {
228 const dir = await mkdtemp(path.join(tmpdir(), "codewhale-action-tokens-"));
229 try {
230 const store = await ThreadStore.open(path.join(dir, "state.json"), { actions: true });
231 t.mock.method(Date, "now", () => 1);
232 t.mock.method(Math, "random", () => 0.5);
233 const first = await store.putAction({ threadId: "thread-a" }, { chatId: "chat-a" });
234 const second = await store.putAction({ threadId: "thread-b" }, { chatId: "chat-a" });
235 assert.notEqual(first, second);
236 assert.match(first, /^[a-f0-9]{32}$/);
237 assert.equal((await store.getAction(first, { chatId: "chat-a" })).threadId, "thread-a");
238 assert.equal((await store.getAction(second, { chatId: "chat-a" })).threadId, "thread-b");
239 } finally {
240 await rm(dir, { recursive: true, force: true });
241 }
242 });
243
244 test("readJsonSafe tolerates empty and non-JSON bodies", async () => {
245 assert.deepEqual(await readJsonSafe(new Response("")), {});
246 assert.deepEqual(await readJsonSafe(new Response('{"ok":true}')), { ok: true });
247 assert.equal(await readJsonSafe(new Response("plain text")), "plain text");
248 });
249
250 test("readSse reassembles events split across chunks and strips CR", async () => {
251 const response = {
252 body: (async function* () {
253 yield Buffer.from('event: item.delta\r\ndata: {"seq":1}\r\n\r');
254 yield Buffer.from('\nevent: turn.completed\r\ndata: {"seq":2}\n\n');
255 })()
256 };
257 const events = [];
258 for await (const event of readSse(response)) events.push(event);
259 assert.deepEqual(events, [
260 { event: "item.delta", data: '{"seq":1}' },
261 { event: "turn.completed", data: '{"seq":2}' }
262 ]);
263 });
264
265 test("createRuntimeClient sends bearer auth and surfaces runtime errors", async () => {
266 const calls = [];
267 const originalFetch = globalThis.fetch;
268 globalThis.fetch = async (url, options) => {
269 calls.push({ url: String(url), options });
270 if (String(url).endsWith("/fail")) {
271 return new Response(JSON.stringify({ error: { message: "down" } }), { status: 503 });
272 }
273 return new Response(JSON.stringify({ ok: true }));
274 };
275 try {
276 const { runtimeJson, authHeaders } = createRuntimeClient({
277 runtimeUrl: "http://127.0.0.1:7878",
278 runtimeToken: "token-1"
279 });
280 assert.deepEqual(authHeaders(), { authorization: "Bearer token-1" });
281
282 assert.deepEqual(await runtimeJson("/v1/threads", { method: "POST", body: { a: 1 } }), {
283 ok: true
284 });
285 assert.equal(calls[0].url, "http://127.0.0.1:7878/v1/threads");
286 assert.equal(calls[0].options.method, "POST");
287 assert.equal(calls[0].options.headers.authorization, "Bearer token-1");
288 assert.equal(calls[0].options.headers["content-type"], "application/json");
289 assert.equal(calls[0].options.body, JSON.stringify({ a: 1 }));
290
291 await runtimeJson("/health", { auth: false });
292 assert.equal(calls[1].options.method, "GET");
293 assert.deepEqual(calls[1].options.headers, {});
294
295 await assert.rejects(() => runtimeJson("/fail"), /Runtime API request failed \(503\): down/);
296 } finally {
297 globalThis.fetch = originalFetch;
298 }
299 });
300
301 test("ThreadStore batches rapid saves into coalesced durable writes", async () => {
302 const dir = await mkdtemp(path.join(tmpdir(), "codewhale-bridge-core-"));
303 try {
304 const statePath = path.join(dir, "thread-map.json");
305 const store = await ThreadStore.open(statePath);
306 let writes = 0;
307 const originalWrite = store.writeSnapshot.bind(store);
308 store.writeSnapshot = async () => {
309 writes += 1;
310 return originalWrite();
311 };
312
313 await Promise.all(
314 Array.from({ length: 25 }, (_, index) =>
315 store.setChat(`chat-${index}`, { threadId: `thread-${index}` })
316 )
317 );
318 assert.ok(writes <= 2, `expected coalesced writes, saw ${writes}`);
319
320 const saved = await ThreadStore.open(statePath);
321 assert.equal((await saved.getChat("chat-0")).threadId, "thread-0");
322 assert.equal((await saved.getChat("chat-24")).threadId, "thread-24");
323 } finally {
324 await rm(dir, { recursive: true, force: true });
325 }
326 });
327
328 test("ThreadStore persists numeric cursors", async () => {
329 const dir = await mkdtemp(path.join(tmpdir(), "codewhale-bridge-core-"));
330 try {
331 const statePath = path.join(dir, "thread-map.json");
332 const store = await ThreadStore.open(statePath);
333
334 assert.equal(store.getCursor("telegram.update_offset", 7), 7);
335 assert.equal(await store.setCursor("telegram.update_offset", 42), 42);
336 assert.equal(store.getCursor("telegram.update_offset"), 42);
337
338 const saved = await ThreadStore.open(statePath);
339 assert.equal(saved.getCursor("telegram.update_offset"), 42);
340 } finally {
341 await rm(dir, { recursive: true, force: true });
342 }
343 });
344
345 test("writeFileDurable replaces the file through unique temp names and leaves none behind", async () => {
346 const dir = await mkdtemp(path.join(tmpdir(), "codewhale-bridge-core-"));
347 try {
348 const target = path.join(dir, "sync-buf.txt");
349 // Concurrent writers used to share one fixed `.tmp` path and race on it.
350 await Promise.all(Array.from({ length: 8 }, (_, index) => writeFileDurable(target, `cursor-${index}`)));
351 assert.match(await readFile(target, "utf8"), /^cursor-[0-7]$/);
352 assert.deepEqual(await readdir(dir), ["sync-buf.txt"]);
353 } finally {
354 await rm(dir, { recursive: true, force: true });
355 }
356 });
357
358 test("Windows sharing locks retry replacement and preserve old bytes on refusal", { skip: process.platform !== "win32", timeout: 30000 }, async () => {
359 const dir = await mkdtemp(path.join(tmpdir(), "codewhale-bridge-lock-"));
360 const target = path.join(dir, "state.txt");
361 const lockers = [];
362 async function lock() {
363 const child = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command",
364 '$file = [System.IO.File]::Open($env:CODEWHALE_TEST_LOCK_FILE, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::Read); try { [Console]::WriteLine("LOCKED"); [Console]::Out.Flush(); [Console]::ReadLine() | Out-Null } finally { $file.Dispose() }'],
365 { env: { ...process.env, CODEWHALE_TEST_LOCK_FILE: target }, stdio: ["pipe", "pipe", "pipe"] });
366 lockers.push(child);
367 // The child may already have exited when failure cleanup releases its pipe.
368 child.stdin.on("error", () => {});
369 await new Promise((resolve, reject) => {
370 let output = "", errors = "";
371 const timeout = setTimeout(() => reject(new Error(`file lock did not open: ${errors}`)), 10000);
372 child.once("error", (error) => { clearTimeout(timeout); reject(error); });
373 child.once("exit", (code) => { clearTimeout(timeout); reject(new Error(`file lock exited ${code}: ${errors}`)); });
374 child.stderr.on("data", (data) => { errors += data; });
375 child.stdout.on("data", (data) => {
376 output += data;
377 if (output.includes("LOCKED")) { clearTimeout(timeout); resolve(); }
378 });
379 });
380 return child;
381 }
382 try {
383 await writeFileDurable(target, "old");
384 const transient = await lock();
385 const release = setTimeout(() => transient.stdin.end("release\n"), 200);
386 try { await writeFileDurable(target, "new"); } finally { clearTimeout(release); if (!transient.stdin.writableEnded) transient.stdin.end("release\n"); }
387 assert.equal(await readFile(target, "utf8"), "new");
388 assert.deepEqual(await readdir(dir), ["state.txt"]);
389
390 const held = await lock();
391 const started = Date.now();
392 await assert.rejects(writeFileDurable(target, "must-not-publish"), (error) => ["EPERM", "EACCES", "EBUSY"].includes(error.code));
393 assert.ok(Date.now() - started < 10000, "permanent refusal must stay bounded");
394 assert.equal(await readFile(target, "utf8"), "new", "failed publication retains the old record");
395 assert.deepEqual(await readdir(dir), ["state.txt"], "failed publication cleans up its temporary file");
396 held.stdin.end("release\n");
397 } finally {
398 await Promise.all(lockers.map((child) => new Promise((resolve) => {
399 if (child.exitCode !== null || child.signalCode !== null) return resolve();
400 child.once("exit", resolve);
401 if (!child.stdin.writableEnded) child.stdin.end("release\n");
402 child.kill();
403 })));
404 await rm(dir, { recursive: true, force: true });
405 }
406 });
407
408 test("ThreadStore claims survive a restart: finished messages skip, an in-flight one is reported", async () => {
409 const dir = await mkdtemp(path.join(tmpdir(), "codewhale-bridge-core-"));
410 try {
411 const statePath = path.join(dir, "thread-map.json");
412 const store = await ThreadStore.open(statePath, { messageLimit: 10 });
413 assert.equal(await store.claimMessage("u:1"), "new");
414 await store.completeMessage("u:1");
415 assert.equal(await store.claimMessage("u:2"), "new");
416 // The process dies here, before completeMessage("u:2").
417 const restarted = await ThreadStore.open(statePath, { messageLimit: 10 });
418 assert.equal(await restarted.claimMessage("u:1"), "done");
419 assert.equal(await restarted.claimMessage("u:2"), "interrupted");
420 assert.equal(await restarted.claimMessage("u:2"), "interrupted", "keep the claim until the report succeeds");
421 await restarted.completeMessage("u:2");
422 assert.equal(await restarted.claimMessage("u:2"), "done", "reported once, then an ordinary duplicate");
423 assert.equal(await restarted.claimMessage("u:3"), "new");
424 } finally {
425 await rm(dir, { recursive: true, force: true });
426 }
427 });
428
429 // ─── splitMessage byte cap ───────────────────────────────────────
430
431 test("splitMessage splits CJK text by bytes when a byte cap is set", () => {
432 const cjk = "横".repeat(4000); // 4000 chars = 12000 UTF-8 bytes
433 const chunks = splitMessage(cjk, 3500, 3800);
434 assert.ok(chunks.length >= 3, `expected >=3 chunks, got ${chunks.length}`);
435 for (const c of chunks) assert.ok(Buffer.byteLength(c, "utf8") <= 3800);
436 assert.equal(chunks.join(""), cjk);
437 });
438
439 test("splitMessage byte cap keeps code fences balanced and splits on lines", () => {
440 let reply = "下面是修改后的代码:\n```js\n";
441 for (let i = 0; i < 120; i += 1) reply += `const v${i} = ${i}; // 这是第${i}行的中文注释说明\n`;
442 reply += "```\n完成。";
443 const chunks = splitMessage(reply, 3500, 3800);
444 assert.ok(chunks.length > 1);
445 for (const chunk of chunks) {
446 assert.ok(Buffer.byteLength(chunk, "utf8") <= 3800);
447 assert.equal((chunk.match(/^```/gm) || []).length % 2, 0, chunk.slice(-40));
448 }
449 assert.equal(chunks[0].endsWith("\n```"), true);
450 assert.equal(chunks[1].startsWith("```js\nconst v"), true);
451 });
452
453 test("splitMessage keeps short messages single under a byte cap", () => {
454 assert.deepEqual(splitMessage("hello", 3500, 3800), ["hello"]);
455 const mixed = "字".repeat(100) + "x".repeat(100); // 400 bytes
456 assert.equal(splitMessage(mixed, 3500, 3800).length, 1);
457 });
458
459 test("splitMessage byte cap is opt-in", () => {
460 const cjk = "横".repeat(4000);
461 const chunks = splitMessage(cjk, 3500, 0);
462 assert.equal(chunks.length, 2); // char limit only
463 assert.ok(Buffer.byteLength(chunks[0], "utf8") > 3800);
464 });
465
466 test("splitAtCodePoint never leaves half a surrogate pair on either side", () => {
467 assert.deepEqual(splitAtCodePoint("ab😀cd", 3), ["ab", "😀cd"]);
468 assert.deepEqual(splitAtCodePoint("ab😀cd", 4), ["ab😀", "cd"]);
469 assert.deepEqual(splitAtCodePoint("abc", 10), ["abc", ""]);
470 });
471
472 test("observeTurn advances the cursor only after a record's effect succeeds", async () => {
473 const threadId = "thread-1";
474 const events = [
475 { seq: 1, thread_id: threadId, turn_id: "turn-1", event: "item.delta", payload: { kind: "agent_message", delta: "hi" } },
476 { seq: 2, thread_id: threadId, turn_id: "turn-1", event: "approval.required", payload: { id: "a1" } }
477 ];
478 const body = events.map((record) => `data: ${JSON.stringify(record)}\n\n`).join("");
479 const cursors = [];
480 await assert.rejects(observeTurn({
481 fetchEvents: async () => new Response(body),
482 threadId,
483 turnId: "turn-1",
484 sinceSeq: 0,
485 timeoutMs: 1000,
486 saveCursor: async (cursor) => { cursors.push(cursor); },
487 onApproval: async () => { throw new Error("send failed"); },
488 onTerminal: async () => {}
489 }), /send failed/);
490 assert.deepEqual(cursors, [{ lastSeq: 1, responseText: "hi" }]);
491 });
492
492 lines Plain Text