| 1 | import test from "node:test"; |
| 2 | import assert from "node:assert/strict"; |
| 3 | import http from "node:http"; |
| 4 | import fs from "node:fs/promises"; |
| 5 | import os from "node:os"; |
| 6 | import path from "node:path"; |
| 7 | import { spawn } from "node:child_process"; |
| 8 | import { fileURLToPath } from "node:url"; |
| 9 | |
| 10 | const entry = fileURLToPath(new URL("../src/index.mjs", import.meta.url)); |
| 11 | const WEIXIN_PROMPT = "You are being controlled from WeChat on a phone through iLink Bot. Keep answers short and plain: no wide tables, and long code only when asked. Ask for tool approvals when needed; do not assume mobile messages imply blanket approval."; |
| 12 | const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); |
| 13 | async function until(check, message, timeout = 8000) { |
| 14 | const deadline = Date.now() + timeout; |
| 15 | while (Date.now() < deadline) { if (await check()) return; await delay(25); } |
| 16 | assert.fail(message); |
| 17 | } |
| 18 | function incoming(id, text, user = "alice", contextToken = "context-fixture") { |
| 19 | return { message_id: id, from_user_id: user, message_type: 1, context_token: contextToken, item_list: [{ type: 1, text_item: { text } }] }; |
| 20 | } |
| 21 | async function fixture(t, options = {}) { |
| 22 | const dir = await fs.mkdtemp(path.join(os.tmpdir(), "weixin-runtime-")); |
| 23 | const state = { polls: 0, batches: [], posts: [], sent: [], summaryQueries: [], lookups: 0, threadCreates: 0, compacts: 0, threadReads: [], streams: new Set(), turns: [], items: [], seq: 0, approvals: [], decisions: [], logs: "" }; |
| 24 | const json = (response, body, status = 200) => { response.writeHead(status, { "Content-Type": "application/json" }); response.end(JSON.stringify(body)); }; |
| 25 | const server = http.createServer(async (req, res) => { |
| 26 | let raw = ""; for await (const chunk of req) raw += chunk; |
| 27 | const body = raw ? JSON.parse(raw) : {}; |
| 28 | const url = new URL(req.url, "http://fixture"); |
| 29 | if (url.pathname.endsWith("/getupdates")) { |
| 30 | state.polls++; |
| 31 | await delay(35); |
| 32 | if (res.destroyed) return; |
| 33 | return json(res, { ret: 0, msgs: state.batches.shift() || [], get_updates_buf: String(state.polls) }); |
| 34 | } |
| 35 | if (url.pathname.endsWith("/sendmessage")) { |
| 36 | state.sent.push(body.msg); |
| 37 | if (options.send) return options.send(res, body.msg, state, json); |
| 38 | return json(res, { ret: 0, message_id: String(state.sent.length) }); |
| 39 | } |
| 40 | if (url.pathname.includes("/msg/notify")) return json(res, { ret: 0 }); |
| 41 | if (url.pathname === "/v1/runtime/info") return json(res, { version: "fixture", capabilities: options.capabilities ?? { turn_operation_idempotency: true, turn_operation_lookup: true } }); |
| 42 | if (url.pathname === "/health") return json(res, { status: "ok" }); |
| 43 | if (url.pathname === "/v1/workspace/status") return json(res, { workspace: dir }); |
| 44 | if (url.pathname === "/v1/threads" && req.method === "POST") { |
| 45 | state.threadRequest = body; |
| 46 | return json(res, { id: `thread-${++state.threadCreates}` }); |
| 47 | } |
| 48 | if (url.pathname === "/v1/threads/summary") { state.summaryQueries.push((url.searchParams.get("thread_ids") || "").split(",").filter(Boolean)); return json(res, options.summaries || []); } |
| 49 | if (/^\/v1\/threads\/[^/]+$/.test(url.pathname)) { |
| 50 | state.threadReads.push(url.pathname); |
| 51 | if (options.failDetailUntil && Date.now() < options.failDetailUntil) return json(res, { error: "unavailable" }, 503); |
| 52 | const id = url.pathname.split("/").at(-1); |
| 53 | const foreign = options.foreignThreads?.includes(id); |
| 54 | return json(res, { id, thread: { id, workspace: foreign ? "/other/project" : dir, system_prompt: foreign ? null : WEIXIN_PROMPT }, latest_seq: state.seq, turns: state.turns, items: state.items, pending_approvals: state.approvals }); |
| 55 | } |
| 56 | if (url.pathname.endsWith("/compact")) { state.compacts++; return json(res, { turn: { id: "turn-compact" } }); } |
| 57 | if (url.pathname === "/v1/threads/thread-1/turns") { |
| 58 | state.posts.push(body); |
| 59 | const turn = { id: "turn-1", thread_id: "thread-1", status: "in_progress" }; |
| 60 | state.turns = [turn]; |
| 61 | if (options.admission) return options.admission(req, res, turn, state, json); |
| 62 | return json(res, { turn }, 201); |
| 63 | } |
| 64 | if (url.pathname.includes("/turn-operations/")) { |
| 65 | state.lookups++; |
| 66 | if (options.lookup) return options.lookup(res, state, json); |
| 67 | return json(res, state.turns[0] || {}, state.turns.length ? 200 : 404); |
| 68 | } |
| 69 | if (url.pathname === "/v1/threads/thread-1/events") { |
| 70 | res.writeHead(200, { "Content-Type": "text/event-stream" }); res.flushHeaders(); |
| 71 | state.streams.add(res); res.on("close", () => state.streams.delete(res)); |
| 72 | return; |
| 73 | } |
| 74 | if (url.pathname === "/v1/approvals/approval-1") { state.decisions.push(body); state.approvals = []; return json(res, {}); } |
| 75 | return json(res, { error: url.pathname }, 404); |
| 76 | }); |
| 77 | await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); |
| 78 | const baseUrl = `http://127.0.0.1:${server.address().port}`; |
| 79 | const account = { accountId: "bot-A", token: "fixture-bot-token", baseUrl }; |
| 80 | await fs.writeFile(path.join(dir, "account.json"), JSON.stringify(account)); |
| 81 | const children = []; |
| 82 | state.start = (extra = {}) => { |
| 83 | const child = spawn(process.execPath, [entry], { env: { ...process.env, CODEWHALE_RUNTIME_URL: baseUrl, CODEWHALE_RUNTIME_TOKEN: "fixture-runtime-token", CODEWHALE_WORKSPACE: dir, WEIXIN_STATE_DIR: dir, WEIXIN_CHAT_ALLOWLIST: "alice,bob", CODEWHALE_TURN_TIMEOUT_MS: "1500", ...extra }, stdio: ["ignore", "pipe", "pipe"] }); |
| 84 | children.push(child); |
| 85 | child.stdout.on("data", (data) => { state.logs += data; }); |
| 86 | child.stderr.on("data", (data) => { state.logs += data; }); |
| 87 | return child; |
| 88 | }; |
| 89 | state.disk = async () => { try { return JSON.parse(await fs.readFile(path.join(dir, "thread-map.json"), "utf8")); } catch { return {}; } }; |
| 90 | state.event = (event, payload, turnId = "turn-1") => { |
| 91 | state.seq++; |
| 92 | const record = { event, payload, thread_id: "thread-1", turn_id: turnId, seq: state.seq }; |
| 93 | for (const response of state.streams) response.write(`data: ${JSON.stringify(record)}\n\n`); |
| 94 | }; |
| 95 | state.complete = (text, status = "completed") => { |
| 96 | state.items = [{ turn_id: "turn-1", kind: "agent_message", detail: text, summary: "truncated" }]; |
| 97 | state.turns[0].status = status; |
| 98 | state.event("turn.completed", { turn: state.turns[0] }); |
| 99 | }; |
| 100 | state.dir = dir; state.account = account; |
| 101 | t.after(async () => { |
| 102 | for (const child of children) child.kill("SIGKILL"); |
| 103 | for (const response of state.streams) response.destroy(); |
| 104 | server.closeAllConnections(); |
| 105 | await new Promise((resolve) => server.close(resolve)); |
| 106 | await fs.rm(dir, { recursive: true, force: true }); |
| 107 | }); |
| 108 | return state; |
| 109 | } |
| 110 | |
| 111 | test("multiline /prompt text reaches the Runtime with its indentation", async (t) => { |
| 112 | const f = await fixture(t); |
| 113 | const prompt = "Review this example:\n first item\n second item\n\nThen summarize it."; |
| 114 | f.batches.push([incoming(1, `/prompt ${prompt}`)]); |
| 115 | f.start(); |
| 116 | |
| 117 | await until(() => f.posts.length > 0, "prompt did not reach the Runtime"); |
| 118 | assert.equal(f.posts[0].prompt, prompt); |
| 119 | }); |
| 120 | |
| 121 | test("production process keeps polling and owner approvals live, dedupes real message IDs", async (t) => { |
| 122 | const f = await fixture(t); f.batches.push([incoming(0, "private original prompt"), incoming(undefined, "must not run")]); f.start(); |
| 123 | await until(() => f.streams.size, "accepted turn did not start observation"); |
| 124 | const polls = f.polls; |
| 125 | f.approvals = [{ id: "approval-1", turn_id: "turn-1", tool_name: "fixture-tool" }]; |
| 126 | f.event("approval.required", f.approvals[0]); |
| 127 | await until(() => f.sent.some((msg) => msg.item_list[0].text_item.text.includes("fixture-tool")), "approval notice missing"); |
| 128 | const code = f.sent.find((msg) => msg.item_list[0].text_item.text.includes("fixture-tool")).item_list[0].text_item.text.match(/Reply 1 ([a-z2-9]{6}) to allow/)[1]; |
| 129 | f.batches.push([incoming(0, "private original prompt"), incoming(2, "/allow approval-1", "bob"), incoming(3, `1 ${code}`)]); |
| 130 | await until(() => f.decisions.length === 1 && f.polls > polls, "initiating owner could not approve or polling stopped during stream"); |
| 131 | assert.equal(f.posts.length, 1); assert.ok(f.polls > polls); assert.deepEqual(f.decisions, [{ decision: "allow", remember: false }]); |
| 132 | f.event("item.delta", { kind: "agent_message", delta: "answer" }); f.complete("answer"); |
| 133 | await until(async () => !(await f.disk()).chats?.alice?.activeTurnId, "accepted output did not settle"); |
| 134 | const disk = await f.disk(); assert.ok(disk.messages.length >= 3); assert.equal(disk.chats.alice.contextToken, "context-fixture"); |
| 135 | assert.equal(f.logs.includes("private original prompt"), false); |
| 136 | }); |
| 137 | |
| 138 | test("restart reattaches exact accepted turn and preserves accumulator across EOF", async (t) => { |
| 139 | const f = await fixture(t); f.batches.push([incoming(1, "work")]); const first = f.start(); |
| 140 | await until(() => f.streams.size, "first stream missing"); f.event("item.delta", { kind: "agent_message", delta: "first " }); |
| 141 | await until(async () => (await f.disk()).chats?.alice?.turnDelivery?.responseText === "first ", "delta was not durable"); |
| 142 | for (const response of f.streams) response.end(); |
| 143 | await delay(75); assert.equal((await f.disk()).chats.alice.activeTurnId, "turn-1"); |
| 144 | first.kill("SIGKILL"); await new Promise((resolve) => first.once("exit", resolve)); |
| 145 | f.items = [{ turn_id: "turn-1", kind: "agent_message", detail: "first second" }]; f.turns[0].status = "completed"; f.seq++; |
| 146 | f.start(); await until(() => f.sent.some((msg) => msg.item_list[0].text_item.text === "first second"), "restart lost final output"); |
| 147 | assert.equal(f.posts.length, 1); assert.equal(f.sent.filter((msg) => msg.item_list[0].text_item.text === "first second").length, 1); |
| 148 | }); |
| 149 | |
| 150 | test("ambiguous admission uses stable operation lookup rather than a duplicate POST", async (t) => { |
| 151 | const f = await fixture(t, { admission: (_req, response) => response.destroy() }); f.batches.push([incoming(1, "work")]); f.start(); |
| 152 | await until(() => f.streams.size, "operation lookup did not recover accepted turn"); |
| 153 | assert.equal(f.posts.length, 1); assert.equal(f.lookups, 1); assert.match(f.posts[0].operation_key, /^[a-f0-9]{64}$/); |
| 154 | assert.equal((await f.disk()).chats.alice.activeTurnId, "turn-1"); |
| 155 | }); |
| 156 | |
| 157 | test("proven rejection holds the output until the member asks to continue; uncertain send is retained without resending", async (t) => { |
| 158 | const f = await fixture(t, { send: (response, msg, state, json) => { |
| 159 | if (state.sent.length === 1) return json(response, { ret: -2 }); |
| 160 | return response.destroy(); |
| 161 | } }); f.batches.push([incoming(1, "work")]); f.start(); |
| 162 | await until(() => f.streams.size, "stream missing"); f.event("item.delta", { kind: "agent_message", delta: "retained answer" }); f.complete("retained answer"); |
| 163 | await until(async () => (await f.disk()).chats?.alice?.turnDelivery?.outputs?.[0]?.status === "held", "rejected send was not held"); |
| 164 | await delay(1200); assert.equal(f.sent.length, 1); |
| 165 | f.batches.push([incoming(2, "继续")]); |
| 166 | await until(async () => (await f.disk()).chats?.alice?.turnDelivery?.outputs?.[0]?.status === "uncertain", "uncertain send was discarded"); |
| 167 | assert.equal(f.sent.length, 2); assert.equal(f.sent[0].client_id, f.sent[1].client_id); |
| 168 | await delay(1200); assert.equal(f.sent.length, 2); assert.equal((await f.disk()).chats.alice.activeTurnId, "turn-1"); |
| 169 | }); |
| 170 | |
| 171 | test("changed bot account cannot reuse or flush a retained old conversation", async (t) => { |
| 172 | const f = await fixture(t); f.batches.push([incoming(1, "work")]); const first = f.start(); |
| 173 | await until(() => f.streams.size, "stream missing"); first.kill("SIGKILL"); await new Promise((resolve) => first.once("exit", resolve)); |
| 174 | f.items = [{ turn_id: "turn-1", kind: "agent_message", detail: "old private answer" }]; f.turns[0].status = "completed"; |
| 175 | await fs.writeFile(path.join(f.dir, "account.json"), JSON.stringify({ ...f.account, accountId: "bot-B" })); |
| 176 | f.batches.push([incoming(2, "new account prompt")]); f.start(); |
| 177 | await until(() => f.sent.some((msg) => msg.item_list[0].text_item.text.includes("pending turn or retained reply")), "replacement account prompt was not handled"); |
| 178 | assert.equal(f.posts.length, 1); assert.equal(f.sent.some((msg) => msg.item_list[0].text_item.text.includes("old private answer")), false); |
| 179 | assert.equal(f.sent.find((msg) => msg.item_list[0].text_item.text.includes("pending turn or retained reply")).context_token, undefined); |
| 180 | assert.equal((await f.disk()).chats.alice.turnDelivery.accountId, "bot-A"); |
| 181 | }); |
| 182 | |
| 183 | test("unattributed legacy context token is not reused for an outgoing message", async (t) => { |
| 184 | const f = await fixture(t); |
| 185 | await fs.writeFile(path.join(f.dir, "thread-map.json"), JSON.stringify({ |
| 186 | chats: { alice: { bindingAccountId: "bot-A", contextToken: "legacy-context" } }, |
| 187 | messages: [], inflight: {}, |
| 188 | })); |
| 189 | f.batches.push([incoming(1, "/help", "alice", "")]); f.start(); |
| 190 | await until(() => f.sent.some((msg) => msg.item_list[0].text_item.text.includes("显示此帮助")), "help response was not sent"); |
| 191 | assert.equal(f.sent.at(-1).context_token, undefined); |
| 192 | }); |
| 193 | |
| 194 | test("both Engine capability flags are required before reconciling an uncertain admission", async (t) => { |
| 195 | const f = await fixture(t, { capabilities: { turn_operation_idempotency: true, turn_operation_lookup: false }, admission: (_req, response) => response.destroy() }); |
| 196 | f.batches.push([incoming(1, "legacy admission")]); f.start(); |
| 197 | await until(async () => (await f.disk()).chats?.alice?.pendingAdmission?.submitted, "uncertain request was not retained"); |
| 198 | const polls = f.polls; await until(() => f.polls > polls + 3, "uncertain admission stopped inbound polling"); |
| 199 | await delay(1100); assert.equal(f.posts.length, 1); assert.equal(f.lookups, 0); assert.equal(f.posts[0].operation_key, undefined); |
| 200 | assert.equal((await f.disk()).chats.alice.pendingAdmission.request.prompt, "legacy admission"); |
| 201 | }); |
| 202 | |
| 203 | test("pre-admission inflight claim recovers through the actual production store", async (t) => { |
| 204 | const f = await fixture(t); const key = JSON.stringify(["bot-A", "alice", "1"]); |
| 205 | await fs.writeFile(path.join(f.dir, "thread-map.json"), JSON.stringify({ chats: {}, messages: [key], inflight: { [key]: { at: "fixture" } } })); |
| 206 | f.batches.push([incoming(1, "recover claimed prompt")]); f.start(); |
| 207 | await until(() => f.streams.size, "inflight prompt was silently skipped"); |
| 208 | assert.equal(f.posts.length, 1); assert.equal((await f.disk()).inflight[key], undefined); |
| 209 | assert.equal((await f.disk()).chats.alice.turnDelivery.messageKey, key); |
| 210 | }); |
| 211 | |
| 212 | test("pending new-thread and turn descriptors stay frozen across restart configuration changes", async (t) => { |
| 213 | const f = await fixture(t); const key = JSON.stringify(["bot-A", "alice", "1"]); |
| 214 | const request = { prompt: "frozen prompt", input_summary: "frozen prompt", model: "frozen-model", mode: "agent", allow_shell: false, trust_mode: false, auto_approve: false, operation_key: "frozen-operation" }; |
| 215 | const threadRequest = { model: "frozen-model", workspace: "/frozen/workspace", mode: "agent", allow_shell: false, trust_mode: false, auto_approve: false, archived: false, system_prompt: "frozen system prompt" }; |
| 216 | await fs.writeFile(path.join(f.dir, "thread-map.json"), JSON.stringify({ chats: { alice: { pendingAdmission: { accountId: "bot-A", actorId: "weixin-account:bot-A:user:alice", messageKey: key, request, threadRequest, operationKey: request.operation_key, threadId: null, submitted: false, sinceSeq: null } } }, messages: [], inflight: {} })); |
| 217 | f.start({ CODEWHALE_WORKSPACE: "/changed/workspace", CODEWHALE_MODEL: "changed-model", CODEWHALE_ALLOW_SHELL: "true" }); |
| 218 | await until(() => f.streams.size, "pending request did not recover"); |
| 219 | assert.deepEqual(f.threadRequest, threadRequest); assert.deepEqual(f.posts[0], request); assert.equal(f.posts.length, 1); |
| 220 | }); |
| 221 | |
| 222 | test("completed accepted conversation is not reused by a replacement bot account", async (t) => { |
| 223 | const f = await fixture(t); f.batches.push([incoming(1, "work")]); const first = f.start(); |
| 224 | await until(() => f.streams.size, "stream missing"); f.event("item.delta", { kind: "agent_message", delta: "old answer" }); f.complete("old answer"); |
| 225 | await until(async () => (await f.disk()).chats?.alice?.turnDelivery?.terminal && !(await f.disk()).chats.alice.activeTurnId, "old turn did not settle"); |
| 226 | first.kill("SIGKILL"); await new Promise((resolve) => first.once("exit", resolve)); |
| 227 | await fs.writeFile(path.join(f.dir, "account.json"), JSON.stringify({ ...f.account, accountId: "bot-B" })); |
| 228 | f.batches.push([incoming(2, "replacement prompt")]); f.start(); |
| 229 | await until(() => f.sent.some((msg) => msg.item_list[0].text_item.text.includes("another or unverified bot account")), "completed old binding was silently reused"); |
| 230 | assert.equal(f.posts.length, 1); assert.equal((await f.disk()).chats.alice.bindingAccountId, "bot-A"); |
| 231 | }); |
| 232 | |
| 233 | test("canceled turn retains and sends partial assistant output with terminal status", async (t) => { |
| 234 | const f = await fixture(t); f.batches.push([incoming(1, "work")]); f.start(); |
| 235 | await until(() => f.streams.size, "stream missing"); f.event("item.delta", { kind: "agent_message", delta: "partial answer" }); f.complete("partial answer", "canceled"); |
| 236 | await until(() => f.sent.some((msg) => msg.item_list[0].text_item.text === "partial answer\n\nTurn canceled."), "cancellation dropped partial output"); |
| 237 | assert.equal(f.posts.length, 1); |
| 238 | }); |
| 239 | |
| 240 | test("unanswered admission response leaves polling and status controls live", async (t) => { |
| 241 | const f = await fixture(t, { admission: () => {} }); f.batches.push([incoming(1, "slow admission")]); f.start(); |
| 242 | await until(() => f.posts.length === 1, "admission request missing"); |
| 243 | const started = Date.now(); const polls = f.polls; f.batches.push([incoming(2, "/status")]); |
| 244 | await until(() => f.sent.some((msg) => msg.item_list[0].text_item.text.includes("user_id=alice")), "admission blocked status control until timeout", 3500); |
| 245 | await until(() => f.polls > polls, "inbound polling did not advance while admission remained unanswered", 3500); |
| 246 | assert.ok(Date.now() - started < 7000); assert.equal(f.posts.length, 1); |
| 247 | assert.equal((await f.disk()).chats.alice.pendingAdmission.submitted, true); |
| 248 | }); |
| 249 | |
| 250 | test("replacement account explicitly starts fresh while retaining the old uncertain receipt", async (t) => { |
| 251 | const f = await fixture(t); |
| 252 | const old = { threadId: "old-thread", bindingAccountId: "bot-A", activeTurnId: "old-turn", contextToken: "old-context", turnDelivery: { |
| 253 | accountId: "bot-A", actorId: "weixin-account:bot-A:user:alice", messageKey: "old-key", turnId: "old-turn", |
| 254 | outputs: [{ text: "old private answer", status: "uncertain", clientId: "old-client" }], |
| 255 | } }; |
| 256 | await fs.writeFile(path.join(f.dir, "thread-map.json"), JSON.stringify({ chats: { alice: old }, messages: [], inflight: {} })); |
| 257 | await fs.writeFile(path.join(f.dir, "account.json"), JSON.stringify({ ...f.account, accountId: "bot-B" })); |
| 258 | f.batches.push([incoming(1, "/new", "alice", "bot-B-context")]); f.start(); |
| 259 | await until(() => f.sent.some((msg) => msg.item_list[0].text_item.text === "Created thread thread-1"), "replacement account remained blocked"); |
| 260 | const current = (await f.disk()).chats.alice; |
| 261 | assert.equal(current.bindingAccountId, "bot-B"); assert.equal(current.activeTurnId, null); assert.equal(current.turnDelivery, undefined); |
| 262 | assert.equal(current.contextToken, "bot-B-context"); assert.equal(current.contextTokenAccountId, "bot-B"); |
| 263 | const retained = Object.values(current.retiredAccountStates); |
| 264 | assert.equal(retained.length, 1); assert.equal(retained[0].threadId, "old-thread"); |
| 265 | assert.deepEqual(retained[0].turnDelivery, old.turnDelivery); assert.equal(retained[0].activeTurnId, "old-turn"); |
| 266 | assert.equal(retained[0].contextToken, "old-context"); |
| 267 | assert.equal(f.sent.find((msg) => msg.item_list[0].text_item.text === "Created thread thread-1").context_token, "bot-B-context"); |
| 268 | await delay(1100); assert.equal(f.posts.length, 0); assert.deepEqual(f.threadReads, ["/v1/threads/old-thread"], "only the startup confirmation reads it"); |
| 269 | assert.equal(f.sent.some((msg) => msg.item_list[0].text_item.text.includes("old private answer")), false); |
| 270 | }); |
| 271 | |
| 272 | for (const receiptKind of ["pendingAdmission", "turnDelivery"]) test(`unbound ${receiptKind} keeps its account context until explicit replacement`, async (t) => { |
| 273 | const f = await fixture(t); |
| 274 | const receipt = { accountId: "bot-A", actorId: "weixin-account:bot-A:user:alice", messageKey: "old-key", |
| 275 | ...(receiptKind === "pendingAdmission" |
| 276 | ? { request: { prompt: "old private prompt" }, submitted: false } |
| 277 | : { outputs: [{ text: "old private answer", status: "uncertain" }] }), |
| 278 | }; |
| 279 | const old = { contextToken: "bot-A-context", contextTokenAccountId: "bot-A", [receiptKind]: receipt }; |
| 280 | await fs.writeFile(path.join(f.dir, "thread-map.json"), JSON.stringify({ chats: { alice: old }, messages: [], inflight: {} })); |
| 281 | await fs.writeFile(path.join(f.dir, "account.json"), JSON.stringify({ ...f.account, accountId: "bot-B" })); |
| 282 | f.batches.push([incoming(1, "/help", "alice", "bot-B-context")]); f.start(); |
| 283 | await until(() => f.sent.length === 1, "new account help was not handled"); |
| 284 | assert.equal(f.sent[0].context_token, undefined); |
| 285 | assert.equal((await f.disk()).chats.alice.contextToken, "bot-A-context"); |
| 286 | assert.deepEqual((await f.disk()).chats.alice[receiptKind], receipt); |
| 287 | f.batches.push([incoming(2, "/new", "alice", "bot-B-context")]); |
| 288 | await until(() => f.sent.some((msg) => msg.item_list[0].text_item.text === "Created thread thread-1"), "explicit replacement did not complete"); |
| 289 | const current = (await f.disk()).chats.alice; |
| 290 | const retained = Object.values(current.retiredAccountStates); |
| 291 | assert.equal(retained.length, 1); |
| 292 | assert.equal(retained[0].contextToken, "bot-A-context"); |
| 293 | assert.equal(retained[0].contextTokenAccountId, "bot-A"); |
| 294 | assert.deepEqual(retained[0][receiptKind], receipt); |
| 295 | assert.equal(current.contextToken, "bot-B-context"); |
| 296 | assert.equal(current.contextTokenAccountId, "bot-B"); |
| 297 | assert.equal(current.bindingAccountId, "bot-B"); |
| 298 | assert.equal(current[receiptKind], undefined); |
| 299 | assert.equal(f.sent.at(-1).context_token, "bot-B-context"); |
| 300 | assert.equal(f.posts.length, 0); |
| 301 | assert.equal(f.threadReads.length, 0); |
| 302 | }); |
| 303 | |
| 304 | test("unattributed pending admission cannot have its context replaced by an inbound token", async (t) => { |
| 305 | const f = await fixture(t); |
| 306 | const old = { contextToken: "unattributed-context", pendingAdmission: { request: { prompt: "retained prompt" } } }; |
| 307 | await fs.writeFile(path.join(f.dir, "thread-map.json"), JSON.stringify({ chats: { alice: old }, messages: [], inflight: {} })); |
| 308 | f.batches.push([incoming(1, "/help")]); f.start(); |
| 309 | await until(() => f.sent.length === 1, "help was not handled"); |
| 310 | assert.equal(f.sent[0].context_token, undefined); |
| 311 | assert.equal((await f.disk()).chats.alice.contextToken, old.contextToken); |
| 312 | assert.deepEqual((await f.disk()).chats.alice.pendingAdmission, old.pendingAdmission); |
| 313 | assert.equal(f.threadCreates, 0); |
| 314 | }); |
| 315 | |
| 316 | for (const limit of ["count", "bytes"]) test(`replacement account refuses ${limit} overflow without losing private receipts`, async (t) => { |
| 317 | const f = await fixture(t); |
| 318 | const retiredAccountStates = limit === "count" |
| 319 | ? Object.fromEntries(Array.from({ length: 200 }, (_, i) => [`receipt-${i}`, { threadId: `old-${i}` }])) |
| 320 | : { receipt: { prompt: "x".repeat(1024 * 1024) } }; |
| 321 | const old = { threadId: "old-thread", bindingAccountId: "bot-A", retiredAccountStates, |
| 322 | pendingAdmission: { accountId: "bot-A", request: { prompt: "retained private prompt" } } }; |
| 323 | await fs.writeFile(path.join(f.dir, "thread-map.json"), JSON.stringify({ chats: { alice: old }, messages: [], inflight: {} })); |
| 324 | await fs.writeFile(path.join(f.dir, "account.json"), JSON.stringify({ ...f.account, accountId: "bot-B" })); |
| 325 | f.batches.push([incoming(1, "/new", "alice", "bot-B-context")]); f.start(); |
| 326 | await until(() => f.sent.some((msg) => msg.item_list[0].text_item.text.includes("Retired account receipt storage is full")), "retirement storage limit was not reported"); |
| 327 | const current = (await f.disk()).chats.alice; |
| 328 | assert.equal(f.threadCreates, 0); |
| 329 | assert.equal(current.threadId, old.threadId); |
| 330 | assert.equal(current.bindingAccountId, old.bindingAccountId); |
| 331 | assert.deepEqual(current.retiredAccountStates, retiredAccountStates); |
| 332 | assert.deepEqual(current.pendingAdmission, old.pendingAdmission); |
| 333 | assert.equal(f.posts.length, 0); |
| 334 | assert.equal(f.sent.some((msg) => msg.item_list[0].text_item.text.includes("retained private prompt")), false); |
| 335 | }); |
| 336 | |
| 337 | test("same-account new-thread command cannot discard a pending admission", async (t) => { |
| 338 | const f = await fixture(t, { admission: () => {} }); f.batches.push([incoming(1, "pending")]); f.start(); |
| 339 | await until(() => f.posts.length === 1, "pending admission missing"); |
| 340 | f.batches.push([incoming(2, "/new")]); |
| 341 | await until(() => f.sent.some((msg) => msg.item_list[0].text_item.text.includes("New conversation failed: This chat still has a pending turn or retained reply")), "same-account pending state was overwritten or the control gave no answer"); |
| 342 | assert.equal(f.threadCreates, 1); assert.equal((await f.disk()).chats.alice.pendingAdmission.request.prompt, "pending"); |
| 343 | }); |
| 344 | |
| 345 | test("resume and thread summaries retain account-and-chat ownership across new conversations", async (t) => { |
| 346 | const f = await fixture(t, { summaries: [ |
| 347 | { id: "thread-1", title: "Alice private title" }, { id: "unbound-thread", title: "Other account private title" }, |
| 348 | ] }); |
| 349 | f.batches.push([incoming(1, "/new"), incoming(2, "/resume thread-1", "bob"), incoming(3, "/threads", "bob"), incoming(4, "/threads")]); |
| 350 | f.start(); |
| 351 | await until(() => f.sent.length === 4, "ownership controls were not handled"); |
| 352 | const texts = f.sent.map((msg) => msg.item_list[0].text_item.text); |
| 353 | assert.match(texts[1], /not owned by this account and chat/); |
| 354 | assert.match(texts[2], /No recent runtime threads owned/); |
| 355 | assert.match(texts[3], /Alice private title/); assert.ok(!texts.some((text) => text.includes("Other account private title"))); |
| 356 | assert.deepEqual(f.summaryQueries, [["thread-1"]], "the bridge requests only locally bound threads owned by this account and chat"); |
| 357 | assert.equal(f.threadReads.length, 0, "rejected resume must not read another chat's thread"); |
| 358 | assert.equal((await f.disk()).chats.bob.threadId, undefined); |
| 359 | f.batches.push([incoming(5, "/new"), incoming(6, "/resume thread-1")]); |
| 360 | await until(() => f.sent.some((msg) => msg.item_list[0].text_item.text === "Resumed thread thread-1"), "owner could not resume its prior conversation"); |
| 361 | assert.equal((await f.disk()).chats.alice.threadId, "thread-1"); assert.equal(f.threadCreates, 2); assert.equal(f.threadReads.length, 1); |
| 362 | }); |
| 363 | |
| 364 | test("replacement account cannot resume the retired account's owned thread", async (t) => { |
| 365 | const f = await fixture(t); |
| 366 | await fs.writeFile(path.join(f.dir, "thread-map.json"), JSON.stringify({ chats: { alice: { threadId: "thread-1", bindingAccountId: "bot-A" } }, messages: [], inflight: {} })); |
| 367 | await fs.writeFile(path.join(f.dir, "account.json"), JSON.stringify({ ...f.account, accountId: "bot-B" })); |
| 368 | f.batches.push([incoming(1, "/resume thread-1")]); f.start(); |
| 369 | await until(() => f.sent.some((msg) => msg.item_list[0].text_item.text.includes("not owned by this account and chat")), "foreign account resumed a private conversation"); |
| 370 | assert.deepEqual(f.threadReads, ["/v1/threads/thread-1"], "only the startup confirmation reads it"); assert.equal((await f.disk()).chats.alice.bindingAccountId, "bot-A"); |
| 371 | }); |
| 372 | |
| 373 | test("restart between durable thread binding and admission update keeps the frozen prompt", async (t) => { |
| 374 | const f = await fixture(t); const key = JSON.stringify(["bot-A", "alice", "1"]); |
| 375 | const request = { prompt: "durable prompt", input_summary: "durable prompt", model: "frozen-model", mode: "agent", allow_shell: false, trust_mode: false, auto_approve: false, operation_key: "frozen-operation" }; |
| 376 | await fs.writeFile(path.join(f.dir, "thread-map.json"), JSON.stringify({ chats: { alice: { |
| 377 | threadId: "thread-1", bindingAccountId: "bot-A", pendingAdmission: { |
| 378 | accountId: "bot-A", actorId: "weixin-account:bot-A:user:alice", messageKey: key, request, |
| 379 | operationKey: request.operation_key, threadId: null, submitted: false, sinceSeq: null, |
| 380 | }, |
| 381 | } }, messages: [key], inflight: { [key]: "interrupted" } })); |
| 382 | f.batches.push([incoming(1, "durable prompt")]); f.start(); |
| 383 | await until(() => f.streams.size, "durable thread binding lost its pending prompt on restart"); |
| 384 | assert.equal(f.threadCreates, 0); assert.equal(f.posts.length, 1); assert.deepEqual(f.posts[0], request); |
| 385 | assert.equal((await f.disk()).chats.alice.turnDelivery.messageKey, key); |
| 386 | }); |
| 387 | |
| 388 | const NOT_OWNED = "This chat can only use threads it started. Send /new to start a new thread."; |
| 389 | const sharedMap = (extra = {}) => JSON.stringify({ chats: { |
| 390 | alice: { threadId: "thread-1", bindingAccountId: "bot-A" }, |
| 391 | bob: { threadId: "thread-1", bindingAccountId: "bot-A", ...extra }, |
| 392 | }, messages: [], inflight: {} }); |
| 393 | |
| 394 | test("a chat on a thread shared in an existing thread map cannot compact it", async (t) => { |
| 395 | const f = await fixture(t); |
| 396 | await fs.writeFile(path.join(f.dir, "thread-map.json"), sharedMap()); |
| 397 | f.batches.push([incoming(1, "/compact", "bob")]); f.start(); |
| 398 | await until(() => f.sent.length === 1, "the compact request was not answered"); |
| 399 | assert.equal(f.sent[0].item_list[0].text_item.text, NOT_OWNED); |
| 400 | assert.equal(f.compacts, 0, "compaction never reaches the shared thread"); |
| 401 | }); |
| 402 | |
| 403 | test("an unsent admission aimed at a thread the chat does not own is dropped", async (t) => { |
| 404 | const f = await fixture(t); const key = JSON.stringify(["bot-A", "bob", "1"]); |
| 405 | const request = { prompt: "queued", input_summary: "queued", model: "m", mode: "agent", allow_shell: false, trust_mode: false, auto_approve: false, operation_key: "queued-operation" }; |
| 406 | await fs.writeFile(path.join(f.dir, "thread-map.json"), sharedMap({ pendingAdmission: { |
| 407 | accountId: "bot-A", actorId: "weixin-account:bot-A:user:bob", messageKey: key, request, |
| 408 | operationKey: request.operation_key, threadId: "thread-1", submitted: false, sinceSeq: null, |
| 409 | } })); |
| 410 | f.start(); |
| 411 | await until(() => f.sent.some((msg) => msg.item_list[0].text_item.text === NOT_OWNED), "the admission was neither sent nor dropped"); |
| 412 | assert.equal(f.posts.length, 0, "no turn reaches the shared thread"); |
| 413 | assert.equal((await f.disk()).chats.bob.pendingAdmission, null); |
| 414 | }); |
| 415 | |
| 416 | test("a chat bound at upgrade to a thread the bridge did not start cannot use it", async (t) => { |
| 417 | const f = await fixture(t, { foreignThreads: ["thread-desktop"] }); |
| 418 | await fs.writeFile(path.join(f.dir, "thread-map.json"), JSON.stringify({ chats: { bob: { threadId: "thread-desktop", bindingAccountId: "bot-A" } }, messages: [], inflight: {} })); |
| 419 | f.batches.push([incoming(1, "/compact", "bob")]); f.start(); |
| 420 | await until(() => f.sent.length === 1, "the compact request was not answered"); |
| 421 | assert.equal(f.sent[0].item_list[0].text_item.text, NOT_OWNED); |
| 422 | f.batches.push([incoming(2, "continue the desktop work", "bob")]); |
| 423 | await until(() => f.sent.length === 2, "the prompt was not answered"); |
| 424 | assert.equal(f.sent[1].item_list[0].text_item.text, NOT_OWNED); |
| 425 | assert.equal(f.compacts, 0); assert.equal(f.posts.length, 0, "nothing reaches the thread"); |
| 426 | assert.equal((await f.disk()).threadOwners.some((entry) => entry.threadId === "thread-desktop"), false); |
| 427 | }); |
| 428 | |
| 429 | test("a chat on a thread shared in an existing thread map cannot decide an approval on it", async (t) => { |
| 430 | const f = await fixture(t); |
| 431 | await fs.writeFile(path.join(f.dir, "thread-map.json"), sharedMap({ turnOrigins: [{ threadId: "thread-1", turnId: "turn-1", actorId: "weixin-account:bot-A:user:bob" }] })); |
| 432 | f.approvals = [{ id: "approval-1", turn_id: "turn-1", tool_name: "fixture-tool" }]; |
| 433 | f.batches.push([incoming(1, "/allow approval-1", "bob")]); f.start(); |
| 434 | await until(() => f.sent.length === 1, "the approval was not answered"); |
| 435 | assert.equal(f.sent[0].item_list[0].text_item.text, NOT_OWNED); |
| 436 | assert.deepEqual(f.decisions, [], "the decision never reaches the Runtime"); |
| 437 | }); |
| 438 | |
| 439 | test("an unsent admission on a pending-ownership thread is preserved when Runtime thread reads return 503 at startup", async (t) => { |
| 440 | const f = await fixture(t, { failDetailUntil: Date.now() + 3000 }); |
| 441 | const key = JSON.stringify(["bot-A", "alice", "1"]); |
| 442 | const request = { prompt: "retained", input_summary: "retained", model: "m", mode: "agent", allow_shell: false, trust_mode: false, auto_approve: false, operation_key: "retained-operation" }; |
| 443 | await fs.writeFile(path.join(f.dir, "thread-map.json"), JSON.stringify({ chats: { alice: { |
| 444 | threadId: "thread-1", bindingAccountId: "bot-A", |
| 445 | pendingAdmission: { |
| 446 | accountId: "bot-A", actorId: "weixin-account:bot-A:user:alice", messageKey: key, request, |
| 447 | operationKey: request.operation_key, threadId: "thread-1", submitted: false, sinceSeq: null, |
| 448 | }, |
| 449 | } }, messages: [], inflight: {} })); |
| 450 | f.start(); |
| 451 | await until(() => f.posts.length === 1 || f.sent.some((msg) => msg.item_list[0].text_item.text === NOT_OWNED), "admission neither posted nor dropped", 40000); |
| 452 | assert.equal(f.sent.some((msg) => msg.item_list[0].text_item.text === NOT_OWNED), false, "must not drop pending admission as unowned"); |
| 453 | assert.equal(f.posts.length, 1, "retained admission posts after ownership confirms"); |
| 454 | assert.equal(f.posts[0].prompt, "retained"); |
| 455 | }); |
| 456 |