| 1 | import assert from "node:assert/strict"; |
| 2 | import { execFile } from "node:child_process"; |
| 3 | import { once } from "node:events"; |
| 4 | import { mkdtemp, rm, writeFile } from "node:fs/promises"; |
| 5 | import { createServer } from "node:http"; |
| 6 | import { tmpdir } from "node:os"; |
| 7 | import path from "node:path"; |
| 8 | import test from "node:test"; |
| 9 | import { fileURLToPath } from "node:url"; |
| 10 | import { promisify } from "node:util"; |
| 11 | |
| 12 | const run = promisify(execFile); |
| 13 | const entry = fileURLToPath(new URL("../src/index.mjs", import.meta.url)); |
| 14 | |
| 15 | const transport = ` |
| 16 | import { EventEmitter } from "node:events"; |
| 17 | let id = 0; |
| 18 | const calls = []; |
| 19 | export const generateReqId = () => String(++id); |
| 20 | export class WSClient extends EventEmitter { |
| 21 | connect() { |
| 22 | const frame = { body: { msgid: "message-1", chatid: "fixture-chat", from: { userid: "fixture-user" }, |
| 23 | msgtype: "text", text: { content: "Send an example" } } }; |
| 24 | this.listeners("message")[0](frame).then(() => { |
| 25 | process.stdout.write("REPLIES " + JSON.stringify(calls) + "\\n", () => process.exit(0)); |
| 26 | }); |
| 27 | } |
| 28 | async replyStream(_frame, id, text, finish) { |
| 29 | calls.push({ id, text, finish }); |
| 30 | } |
| 31 | } |
| 32 | `; |
| 33 | |
| 34 | const loader = ` |
| 35 | export function resolve(specifier, context, nextResolve) { |
| 36 | if (specifier === "@wecom/aibot-node-sdk") { |
| 37 | return { url: new URL("./transport.mjs", import.meta.url).href, shortCircuit: true }; |
| 38 | } |
| 39 | return nextResolve(specifier, context); |
| 40 | } |
| 41 | `; |
| 42 | |
| 43 | async function repliesFor(t, events, { endStream = true, timeoutMs = 900_000 } = {}) { |
| 44 | const dir = await mkdtemp(path.join(tmpdir(), "codewhale-wecom-replies-")); |
| 45 | t.after(() => rm(dir, { recursive: true, force: true })); |
| 46 | await writeFile(path.join(dir, "transport.mjs"), transport); |
| 47 | const loaderPath = path.join(dir, "loader.mjs"); |
| 48 | await writeFile(loaderPath, loader); |
| 49 | |
| 50 | const server = createServer((request, response) => { |
| 51 | const route = new URL(request.url, "http://localhost").pathname; |
| 52 | if (route === "/v1/threads/thread-1/events") { |
| 53 | response.writeHead(200, { "content-type": "text/event-stream" }); |
| 54 | response.write(events.map(([event, payload], index) => `data: ${JSON.stringify({ |
| 55 | event, payload, thread_id: "thread-1", turn_id: "turn-1", seq: index + 1, |
| 56 | })}\n\n`).join("")); |
| 57 | if (endStream) response.end(); |
| 58 | return; |
| 59 | } |
| 60 | const routes = { |
| 61 | "POST /v1/threads": { id: "thread-1" }, |
| 62 | "GET /v1/threads/thread-1": { latest_seq: 0, turns: [] }, |
| 63 | "POST /v1/threads/thread-1/turns": { turn: { id: "turn-1" } }, |
| 64 | }; |
| 65 | const body = routes[`${request.method} ${route}`]; |
| 66 | response.writeHead(body ? 200 : 404, { "content-type": "application/json" }); |
| 67 | response.end(JSON.stringify(body ?? { error: route })); |
| 68 | }); |
| 69 | server.listen(0, "127.0.0.1"); |
| 70 | await once(server, "listening"); |
| 71 | t.after(() => new Promise((resolve) => { |
| 72 | server.close(resolve); |
| 73 | server.closeAllConnections(); |
| 74 | })); |
| 75 | |
| 76 | const { stdout } = await run(process.execPath, ["--experimental-loader", loaderPath, entry], { |
| 77 | timeout: 8_000, |
| 78 | env: { |
| 79 | WECOM_BOT_ID: "fixture-bot", |
| 80 | WECOM_BOT_SECRET: "fixture-secret", |
| 81 | WECOM_CHAT_ALLOWLIST: "fixture-user", |
| 82 | WECOM_THREAD_MAP_PATH: path.join(dir, "thread-map.json"), |
| 83 | CODEWHALE_RUNTIME_TOKEN: "fixture-token", |
| 84 | CODEWHALE_RUNTIME_URL: `http://127.0.0.1:${server.address().port}`, |
| 85 | CODEWHALE_WORKSPACE: dir, |
| 86 | CODEWHALE_TURN_TIMEOUT_MS: String(timeoutMs), |
| 87 | }, |
| 88 | }); |
| 89 | const receipt = stdout.split("\n").find((line) => line.startsWith("REPLIES ")); |
| 90 | assert.ok(receipt); |
| 91 | const [started, ...replies] = JSON.parse(receipt.slice("REPLIES ".length)); |
| 92 | assert.equal(started?.text, "Started turn turn-1"); |
| 93 | return replies; |
| 94 | } |
| 95 | |
| 96 | test("a long WeCom reply stays within the message cap and arrives in full", async (t) => { |
| 97 | const preview = "例".repeat(800); |
| 98 | const remainder = "题".repeat(1500); |
| 99 | const chunks = await repliesFor(t, [ |
| 100 | ["item.delta", { kind: "agent_message", delta: preview }], |
| 101 | ["item.delta", { kind: "agent_message", delta: remainder }], |
| 102 | ["turn.completed", { turn: { id: "turn-1", status: "completed" } }], |
| 103 | ]); |
| 104 | assert.ok(chunks.every((reply) => Buffer.byteLength(reply.text) <= 3800), |
| 105 | `reply sizes: ${chunks.map((reply) => Buffer.byteLength(reply.text)).join(", ")}`); |
| 106 | assert.equal(chunks[0].text, preview); |
| 107 | assert.equal(chunks[0].finish, false); |
| 108 | const finished = chunks.filter((reply) => reply.finish); |
| 109 | assert.equal(finished.length, 2); |
| 110 | assert.equal(finished[0].id, chunks[0].id); |
| 111 | assert.notEqual(finished[0].id, finished[1].id); |
| 112 | assert.equal(finished.map((reply) => reply.text).join(""), preview + remainder); |
| 113 | }); |
| 114 | |
| 115 | test("an observation timeout finishes the open WeCom preview", async (t) => { |
| 116 | const partial = "Partial answer"; |
| 117 | const chunks = await repliesFor(t, [ |
| 118 | ["item.delta", { kind: "agent_message", delta: partial }], |
| 119 | ], { endStream: false, timeoutMs: 1_000 }); |
| 120 | assert.equal(chunks.length, 2); |
| 121 | const [preview, finished] = chunks; |
| 122 | assert.equal(preview.finish, false); |
| 123 | assert.equal(preview.text, partial); |
| 124 | assert.deepEqual(finished, { |
| 125 | id: preview.id, |
| 126 | text: `${partial}\n\nTurn observation timed out after 1s.`, |
| 127 | finish: true, |
| 128 | }); |
| 129 | }); |
| 130 |