| 1 | import test from "node:test"; |
| 2 | import assert from "node:assert/strict"; |
| 3 | import { spawn } from "node:child_process"; |
| 4 | import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; |
| 5 | import { tmpdir } from "node:os"; |
| 6 | import path from "node:path"; |
| 7 | import { fileURLToPath, pathToFileURL } from "node:url"; |
| 8 | |
| 9 | import { ThreadStore, THREAD_NOT_OWNED_MESSAGE, decideApproval } from "../src/lib.mjs"; |
| 10 | import { startStub } from "./support/stub-server.mjs"; |
| 11 | |
| 12 | const here = path.dirname(fileURLToPath(import.meta.url)); |
| 13 | const integrations = path.join(here, "..", ".."); |
| 14 | const NOT_OWNED = new RegExp(THREAD_NOT_OWNED_MESSAGE.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")); |
| 15 | const NOTE = "ALICE_PRIVATE_NOTE"; |
| 16 | const PROMPT_TAIL = "Keep status updates concise. Ask for tool approvals when needed; do not assume mobile messages imply blanket approval."; |
| 17 | const BRIDGE_WORKSPACE = "/fixture/bridge-workspace"; |
| 18 | |
| 19 | async function until(check, label, timeoutMs = 30000) { |
| 20 | const started = Date.now(); |
| 21 | for (;;) { |
| 22 | const value = check(); |
| 23 | if (value) return value; |
| 24 | if (Date.now() - started > timeoutMs) assert.fail(`timed out waiting for ${label}`); |
| 25 | await new Promise((resolve) => setTimeout(resolve, 25)); |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | async function withBridge(name, env, run, { seedMap = null, seedThreads = [], prepare = null } = {}) { |
| 30 | const stub = await startStub(); |
| 31 | for (const thread of seedThreads) stub.seedThread(thread); |
| 32 | if (prepare) prepare(stub); |
| 33 | const scratch = await mkdtemp(path.join(tmpdir(), "cw-bridge-ownership-")); |
| 34 | const mapPath = path.join(scratch, "thread-map.json"); |
| 35 | const seeded = typeof seedMap === "function" ? seedMap(stub) : seedMap; |
| 36 | if (seeded) await writeFile(mapPath, JSON.stringify(seeded)); |
| 37 | const logs = []; |
| 38 | const child = spawn( |
| 39 | process.execPath, |
| 40 | ["--import", pathToFileURL(path.join(here, "support/register.mjs")).href, path.join(integrations, name, "src/index.mjs")], |
| 41 | { |
| 42 | env: { |
| 43 | PATH: process.env.PATH, |
| 44 | FAKE_CHAT_URL: stub.url, |
| 45 | CODEWHALE_RUNTIME_URL: stub.url, |
| 46 | CODEWHALE_RUNTIME_TOKEN: "fixture-runtime-token", |
| 47 | CODEWHALE_WORKSPACE: BRIDGE_WORKSPACE, |
| 48 | ...env(stub, mapPath) |
| 49 | }, |
| 50 | stdio: ["ignore", "pipe", "pipe"] |
| 51 | } |
| 52 | ); |
| 53 | child.stdout.on("data", (chunk) => logs.push(String(chunk))); |
| 54 | child.stderr.on("data", (chunk) => logs.push(String(chunk))); |
| 55 | const repliesTo = (who) => stub.state.replies.filter((reply) => reply.to === who).map((reply) => reply.text); |
| 56 | const say = async (push, who, text, expect) => { |
| 57 | const before = repliesTo(who).length; |
| 58 | push(who, text); |
| 59 | return until(() => { |
| 60 | const fresh = repliesTo(who).slice(before); |
| 61 | return fresh.some((reply) => expect.test(reply)) ? fresh : null; |
| 62 | }, `${name}: reply to ${who} for ${JSON.stringify(text)} matching ${expect}`).catch((error) => { |
| 63 | console.log(`replies=${JSON.stringify(stub.state.replies)} logs=${logs.join("")}`); |
| 64 | throw error; |
| 65 | }); |
| 66 | }; |
| 67 | try { |
| 68 | await run({ stub, say, mapPath }); |
| 69 | } finally { |
| 70 | child.kill("SIGKILL"); |
| 71 | await stub.close(); |
| 72 | await rm(scratch, { recursive: true, force: true }); |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | const bridges = { |
| 77 | wecom: { |
| 78 | name: "wecom-bridge", |
| 79 | systemPrompt: `You are being controlled from a WeCom (企业微信) phone chat. ${PROMPT_TAIL}`, |
| 80 | alice: "alice", bob: "bob", |
| 81 | chatKey: (who) => `single:${who}`, |
| 82 | env: (stub, mapPath) => ({ |
| 83 | WECOM_BOT_ID: "fixture-bot", WECOM_BOT_SECRET: "fixture-not-a-secret", |
| 84 | WECOM_CHAT_ALLOWLIST: "alice,bob", WECOM_THREAD_MAP_PATH: mapPath |
| 85 | }), |
| 86 | push: (stub) => (who, text) => stub.pushWecom(who, text) |
| 87 | }, |
| 88 | feishu: { |
| 89 | name: "feishu-bridge", |
| 90 | systemPrompt: `You are being controlled from a Feishu/Lark phone chat. ${PROMPT_TAIL}`, |
| 91 | alice: "oc_alice", bob: "oc_bob", |
| 92 | chatKey: (who) => who, |
| 93 | env: (stub, mapPath) => ({ |
| 94 | FEISHU_APP_ID: "fixture-app", FEISHU_APP_SECRET: "fixture-not-a-secret", |
| 95 | CODEWHALE_CHAT_ALLOWLIST: "oc_alice,oc_bob", FEISHU_THREAD_MAP_PATH: mapPath |
| 96 | }), |
| 97 | push: (stub) => (who, text) => stub.pushFeishu(`ou_${who}`, who, text) |
| 98 | }, |
| 99 | telegram: { |
| 100 | name: "telegram-bridge", |
| 101 | systemPrompt: `You are being controlled from a Telegram phone chat. ${PROMPT_TAIL}`, |
| 102 | alice: "111", bob: "222", |
| 103 | chatKey: (who) => who, |
| 104 | env: (stub, mapPath) => ({ |
| 105 | TELEGRAM_BOT_TOKEN: "1000:fixture-not-a-token", TELEGRAM_API_BASE: `${stub.url}/tg`, |
| 106 | TELEGRAM_CHAT_ALLOWLIST: "111,222", TELEGRAM_THREAD_MAP_PATH: mapPath, TELEGRAM_POLL_TIMEOUT_SECONDS: "1" |
| 107 | }), |
| 108 | push: (stub) => (who, text) => stub.pushTelegram(Number(who), text) |
| 109 | } |
| 110 | }; |
| 111 | |
| 112 | const turnPosts = (stub, threadId) => stub.state.runtimeRequests.filter((request) => request.route === `POST /v1/threads/${threadId}/turns`); |
| 113 | |
| 114 | for (const [label, bridge] of Object.entries(bridges)) { |
| 115 | test(`${label}: a chat lists and resumes only the threads it started`, async () => { |
| 116 | await withBridge(bridge.name, bridge.env, async ({ stub, say, mapPath }) => { |
| 117 | const push = bridge.push(stub); |
| 118 | const { alice, bob } = bridge; |
| 119 | |
| 120 | await say(push, alice, "/new", /Created thread/); |
| 121 | const aliceThread = stub.state.threads[0].id; |
| 122 | await say(push, alice, `remember ${NOTE}`, /STUB-MODEL/); |
| 123 | |
| 124 | const bobListing = (await say(push, bob, "/threads", /No threads started|thr-/)).join("\n"); |
| 125 | assert.ok(!bobListing.includes(aliceThread) && !bobListing.includes(NOTE), "another chat's thread is not listed"); |
| 126 | |
| 127 | const refused = (await say(push, bob, `/resume ${aliceThread}`, /Resumed|can only use threads/)).join("\n"); |
| 128 | assert.match(refused, NOT_OWNED); |
| 129 | const unknown = (await say(push, bob, "/resume thr-does-not-exist", /Resumed|can only use threads|failed/i)).join("\n"); |
| 130 | assert.match(unknown, NOT_OWNED, "an unknown id gets the same reply as a foreign one"); |
| 131 | assert.ok(!stub.state.runtimeRequests.some((request) => request.route === "GET /v1/threads/thr-does-not-exist"), |
| 132 | "an unowned id never reaches the Runtime"); |
| 133 | |
| 134 | const map = JSON.parse(await readFile(mapPath, "utf8")); |
| 135 | assert.notEqual(map.chats[bridge.chatKey(bob)]?.threadId, aliceThread, "the refusal leaves the chat unbound"); |
| 136 | |
| 137 | await say(push, bob, "hello from bob", /STUB-MODEL/); |
| 138 | assert.equal(turnPosts(stub, aliceThread).filter((request) => request.body?.prompt === "hello from bob").length, 0); |
| 139 | |
| 140 | const aliceListing = (await say(push, alice, "/threads", /thr-/)).join("\n"); |
| 141 | assert.ok(aliceListing.includes(aliceThread) && aliceListing.includes(NOTE)); |
| 142 | const created = (await say(push, alice, "/new", /Created thread/)).join("\n"); |
| 143 | const secondThread = created.match(/Created thread (\S+)/)[1]; |
| 144 | assert.notEqual(secondThread, aliceThread, "/new starts a thread even when the chat already has one"); |
| 145 | assert.ok(stub.state.threads.some((thread) => thread.id === secondThread), "the new thread exists in the Runtime"); |
| 146 | await say(push, alice, `/resume ${aliceThread}`, /Resumed thread/); |
| 147 | await say(push, alice, "still mine", /STUB-MODEL/); |
| 148 | assert.equal(turnPosts(stub, aliceThread).filter((request) => request.body?.prompt === "still mine").length, 1); |
| 149 | assert.notEqual(secondThread, aliceThread); |
| 150 | }); |
| 151 | }); |
| 152 | |
| 153 | test(`${label}: a thread no chat of this bridge started is neither listed nor resumable`, async () => { |
| 154 | await withBridge(bridge.name, bridge.env, async ({ stub, say }) => { |
| 155 | const push = bridge.push(stub); |
| 156 | const { bob } = bridge; |
| 157 | const listing = (await say(push, bob, "/threads", /No threads started|thr-/)).join("\n"); |
| 158 | assert.ok(!listing.includes("thr-desktop")); |
| 159 | const refused = (await say(push, bob, "/resume thr-desktop", /Resumed|can only use threads/)).join("\n"); |
| 160 | assert.match(refused, NOT_OWNED); |
| 161 | assert.ok(!stub.state.runtimeRequests.some((request) => request.route.includes("/v1/threads/thr-desktop"))); |
| 162 | }, { seedThreads: [{ id: "thr-desktop", workspace: "/fixture/other-project", summary: `desktop work ${NOTE}`, runningTurnId: "turn-desktop" }] }); |
| 163 | }); |
| 164 | |
| 165 | test(`${label}: a thread shared by two chats in an existing thread map fails closed`, async () => { |
| 166 | const seedMap = { chats: { |
| 167 | [bridge.chatKey(bridge.alice)]: { threadId: "thr-shared", lastSeq: 0, activeTurnId: null }, |
| 168 | [bridge.chatKey(bridge.bob)]: { threadId: "thr-shared", lastSeq: 0, activeTurnId: null } |
| 169 | } }; |
| 170 | await withBridge(bridge.name, bridge.env, async ({ stub, say }) => { |
| 171 | const push = bridge.push(stub); |
| 172 | const reply = (await say(push, bridge.bob, "continue please", /can only use threads|STUB-MODEL/)).join("\n"); |
| 173 | assert.match(reply, NOT_OWNED); |
| 174 | assert.equal(turnPosts(stub, "thr-shared").length, 0, "no turn reaches the shared thread"); |
| 175 | const listing = (await say(push, bridge.alice, "/threads", /No threads started|thr-/)).join("\n"); |
| 176 | assert.ok(!listing.includes("thr-shared")); |
| 177 | const created = (await say(push, bridge.bob, "/new", /Created thread|can only use threads/)).join("\n"); |
| 178 | assert.doesNotMatch(created, NOT_OWNED, "/new gives the chat a thread of its own"); |
| 179 | const fresh = created.match(/Created thread (\S+)/)[1]; |
| 180 | assert.notEqual(fresh, "thr-shared"); |
| 181 | await say(push, bridge.bob, "hello after new", /STUB-MODEL/); |
| 182 | assert.equal(turnPosts(stub, fresh).length, 1); |
| 183 | assert.equal(turnPosts(stub, "thr-shared").length, 0); |
| 184 | }, { seedMap, seedThreads: [{ id: "thr-shared", workspace: "/fixture/bridge-workspace", summary: "shared" }] }); |
| 185 | }); |
| 186 | |
| 187 | test(`${label}: a thread only one chat points at in an existing thread map stays with that chat`, async () => { |
| 188 | const seedMap = { chats: { [bridge.chatKey(bridge.alice)]: { threadId: "thr-legacy", lastSeq: 0, activeTurnId: null } } }; |
| 189 | await withBridge(bridge.name, bridge.env, async ({ stub, say }) => { |
| 190 | const push = bridge.push(stub); |
| 191 | await say(push, bridge.alice, "carry on", /STUB-MODEL/); |
| 192 | assert.equal(turnPosts(stub, "thr-legacy").length, 1); |
| 193 | const refused = (await say(push, bridge.bob, "/resume thr-legacy", /Resumed|can only use threads/)).join("\n"); |
| 194 | assert.match(refused, NOT_OWNED); |
| 195 | }, { seedMap, seedThreads: [{ id: "thr-legacy", workspace: BRIDGE_WORKSPACE, systemPrompt: bridge.systemPrompt, summary: "legacy" }] }); |
| 196 | }); |
| 197 | |
| 198 | test(`${label}: a chat bound to a thread started outside the bridge at upgrade does not keep it`, async () => { |
| 199 | const seedMap = { chats: { [bridge.chatKey(bridge.bob)]: { threadId: "thr-desktop", lastSeq: 0, activeTurnId: null } } }; |
| 200 | await withBridge(bridge.name, bridge.env, async ({ stub, say, mapPath }) => { |
| 201 | const push = bridge.push(stub); |
| 202 | const listing = (await say(push, bridge.bob, "/threads", /No threads started|thr-/)).join("\n"); |
| 203 | assert.ok(!listing.includes("thr-desktop") && !listing.includes(NOTE), "the thread is not listed"); |
| 204 | const reply = (await say(push, bridge.bob, "what was I doing?", /can only use threads|STUB-MODEL/)).join("\n"); |
| 205 | assert.match(reply, NOT_OWNED); |
| 206 | assert.equal(turnPosts(stub, "thr-desktop").length, 0, "no turn reaches the thread"); |
| 207 | const refused = (await say(push, bridge.bob, "/resume thr-desktop", /Resumed|can only use threads/)).join("\n"); |
| 208 | assert.match(refused, NOT_OWNED); |
| 209 | const map = JSON.parse(await readFile(mapPath, "utf8")); |
| 210 | assert.ok(!map.threadOwners.some((entry) => entry.threadId === "thr-desktop"), "no ownership is recorded for it"); |
| 211 | }, { seedMap, seedThreads: [{ id: "thr-desktop", workspace: "/fixture/other-project", summary: `desktop work ${NOTE}` }] }); |
| 212 | }); |
| 213 | |
| 214 | test(`${label}: a bridge thread kept at upgrade is confirmed once and stays owned after a restart`, async () => { |
| 215 | const seedMap = { chats: { [bridge.chatKey(bridge.alice)]: { threadId: "thr-legacy", lastSeq: 0, activeTurnId: null } } }; |
| 216 | await withBridge(bridge.name, bridge.env, async ({ stub, say, mapPath }) => { |
| 217 | const push = bridge.push(stub); |
| 218 | await say(push, bridge.alice, "carry on", /STUB-MODEL/); |
| 219 | const map = JSON.parse(await readFile(mapPath, "utf8")); |
| 220 | const entry = map.threadOwners.find((owner) => owner.threadId === "thr-legacy"); |
| 221 | assert.ok(entry && entry.legacy === undefined, "the grant is confirmed and no longer marked"); |
| 222 | }, { seedMap, seedThreads: [{ id: "thr-legacy", workspace: BRIDGE_WORKSPACE, systemPrompt: bridge.systemPrompt, summary: "legacy" }] }); |
| 223 | }); |
| 224 | |
| 225 | test(`${label}: a chat on a disowned shared thread cannot decide an approval on it`, async () => { |
| 226 | const bobKey = bridge.chatKey(bridge.bob); |
| 227 | const actor = { wecom: "wecom-user:bob", feishu: "feishu-openId:ou_oc_bob", telegram: "telegram-user:222" }[label]; |
| 228 | const seedMap = { chats: { |
| 229 | [bridge.chatKey(bridge.alice)]: { threadId: "thr-shared", lastSeq: 0, activeTurnId: null }, |
| 230 | [bobKey]: { threadId: "thr-shared", lastSeq: 0, activeTurnId: null, |
| 231 | turnOrigins: [{ threadId: "thr-shared", turnId: "turn-bob", actorId: actor }], |
| 232 | authorizedIdentity: { chatId: bobKey, chatType: label === "feishu" ? "p2p" : "private", userId: bridge.bob, openId: "ou_oc_bob", isBot: false } } |
| 233 | } }; |
| 234 | await withBridge(bridge.name, bridge.env, async ({ stub, say }) => { |
| 235 | const push = bridge.push(stub); |
| 236 | const reply = (await say(push, bridge.bob, "/allow appr-1", /Approval|can only use threads|not waiting/)).join("\n"); |
| 237 | assert.match(reply, NOT_OWNED); |
| 238 | assert.equal(stub.state.approvalDecisions.length, 0, "the decision never reaches the Runtime"); |
| 239 | }, { seedMap, seedThreads: [{ id: "thr-shared", workspace: BRIDGE_WORKSPACE, systemPrompt: bridge.systemPrompt, summary: "shared", runningTurnId: "turn-bob", |
| 240 | pendingApprovals: [{ id: "appr-1", turn_id: "turn-bob" }] }] }); |
| 241 | }); |
| 242 | |
| 243 | test(`${label}: a chat on its own thread can still decide an approval`, async () => { |
| 244 | const aliceKey = bridge.chatKey(bridge.alice); |
| 245 | const actor = { wecom: "wecom-user:alice", feishu: "feishu-openId:ou_oc_alice", telegram: "telegram-user:111" }[label]; |
| 246 | const seedMap = { chats: { [aliceKey]: { threadId: "thr-own", lastSeq: 0, activeTurnId: null, |
| 247 | turnOrigins: [{ threadId: "thr-own", turnId: "turn-alice", actorId: actor }], |
| 248 | authorizedIdentity: { chatId: aliceKey, chatType: label === "feishu" ? "p2p" : "private", userId: bridge.alice, openId: "ou_oc_alice", isBot: false } } } }; |
| 249 | await withBridge(bridge.name, bridge.env, async ({ stub, say }) => { |
| 250 | const push = bridge.push(stub); |
| 251 | await say(push, bridge.alice, "/allow appr-1", /Approval appr-1: allow/); |
| 252 | assert.deepEqual(stub.state.approvalDecisions.map((entry) => entry.id), ["appr-1"]); |
| 253 | }, { seedMap, seedThreads: [{ id: "thr-own", workspace: BRIDGE_WORKSPACE, systemPrompt: bridge.systemPrompt, summary: "own", runningTurnId: "turn-alice", |
| 254 | pendingApprovals: [{ id: "appr-1", turn_id: "turn-alice" }] }] }); |
| 255 | }); |
| 256 | } |
| 257 | |
| 258 | test("wecom: a chat bound to a thread started outside the bridge cannot steer that thread's running turn", async () => { |
| 259 | const bridge = bridges.wecom; |
| 260 | const seedMap = { chats: { "single:bob": { threadId: "thr-desktop", lastSeq: 0, activeTurnId: null } } }; |
| 261 | await withBridge(bridge.name, bridge.env, async ({ stub, say }) => { |
| 262 | const push = bridge.push(stub); |
| 263 | const reply = (await say(push, "bob", "rm the tests and push", /can only use threads|forwarded|active turn/)).join("\n"); |
| 264 | assert.match(reply, NOT_OWNED); |
| 265 | assert.ok(!stub.state.runtimeRequests.some((request) => /\/steer$/.test(request.route)), "no steer reaches the thread"); |
| 266 | }, { seedMap, seedThreads: [{ id: "thr-desktop", workspace: "/fixture/other-project", summary: `desktop work ${NOTE}`, runningTurnId: "turn-desktop" }] }); |
| 267 | }); |
| 268 | |
| 269 | test("feishu: a chat bound to a thread started outside the bridge does not receive its running turn on restart", async () => { |
| 270 | const bridge = bridges.feishu; |
| 271 | const seedMap = { chats: { oc_bob: { threadId: "thr-desktop", lastSeq: 0, activeTurnId: "turn-old", |
| 272 | authorizedIdentity: { chatId: "oc_bob", chatType: "p2p", openId: "ou_oc_bob" } } } }; |
| 273 | await withBridge(bridge.name, bridge.env, async ({ stub, say, mapPath }) => { |
| 274 | const push = bridge.push(stub); |
| 275 | await say(push, "oc_bob", "/help", /./); |
| 276 | await new Promise((resolve) => setTimeout(resolve, 1500)); |
| 277 | const toBob = stub.state.replies.filter((reply) => reply.to === "oc_bob").map((reply) => reply.text).join("\n"); |
| 278 | assert.ok(!toBob.includes("OTHER_CLIENT_OUTPUT") && !/Reattaching/.test(toBob), "no output from the thread is relayed"); |
| 279 | assert.ok(!stub.state.runtimeRequests.some((request) => request.route.endsWith("/events")), "the thread's events are never read"); |
| 280 | const map = JSON.parse(await readFile(mapPath, "utf8")); |
| 281 | assert.equal(map.chats.oc_bob.activeTurnId, null, "the stored turn id is cleared"); |
| 282 | }, { seedMap, prepare: (stub) => { |
| 283 | const entry = stub.seedThread({ id: "thr-desktop", workspace: "/fixture/other-project", summary: "desktop work", runningTurnId: "turn-desktop" }); |
| 284 | entry.events.push({ seq: 1, thread_id: "thr-desktop", turn_id: "turn-desktop", event: "item.delta", payload: { kind: "agent_message", delta: "OTHER_CLIENT_OUTPUT" } }); |
| 285 | entry.events.push({ seq: 2, thread_id: "thr-desktop", turn_id: "turn-desktop", event: "turn.completed", payload: { turn: { status: "completed" } } }); |
| 286 | } }); |
| 287 | }); |
| 288 | |
| 289 | const otherChatEvents = (entry) => { |
| 290 | entry.events.push({ seq: 1, thread_id: "thr-shared", turn_id: "turn-other", event: "item.delta", payload: { kind: "agent_message", delta: "OTHER_CHAT_OUTPUT" } }); |
| 291 | entry.events.push({ seq: 2, thread_id: "thr-shared", turn_id: "turn-other", event: "turn.completed", payload: { turn: { status: "completed" } } }); |
| 292 | }; |
| 293 | |
| 294 | test("feishu: a chat the migration disowned does not reattach to another chat's running turn on restart", async () => { |
| 295 | const bridge = bridges.feishu; |
| 296 | const seedMap = { chats: { |
| 297 | oc_alice: { threadId: "thr-shared", lastSeq: 0, activeTurnId: null }, |
| 298 | oc_bob: { threadId: "thr-shared", lastSeq: 0, activeTurnId: "turn-stale", |
| 299 | authorizedIdentity: { chatId: "oc_bob", chatType: "p2p", openId: "ou_oc_bob" } } |
| 300 | } }; |
| 301 | await withBridge(bridge.name, bridge.env, async ({ stub, say, mapPath }) => { |
| 302 | const push = bridge.push(stub); |
| 303 | const listing = (await say(push, "oc_bob", "/threads", /No threads started|thr-/)).join("\n"); |
| 304 | assert.ok(!listing.includes("thr-shared")); |
| 305 | await new Promise((resolve) => setTimeout(resolve, 500)); |
| 306 | const toBob = stub.state.replies.filter((reply) => reply.to === "oc_bob").map((reply) => reply.text).join("\n"); |
| 307 | assert.ok(!toBob.includes("OTHER_CHAT_OUTPUT") && !/Reattaching/.test(toBob), "no other chat's turn output is relayed"); |
| 308 | assert.ok(!stub.state.runtimeRequests.some((request) => request.route.includes("/v1/threads/thr-shared")), "the shared thread is never read"); |
| 309 | const map = JSON.parse(await readFile(mapPath, "utf8")); |
| 310 | assert.equal(map.chats.oc_bob.activeTurnId, null, "the stale turn id is cleared"); |
| 311 | }, { seedMap, prepare: (stub) => otherChatEvents(stub.seedThread({ id: "thr-shared", workspace: "/fixture/bridge-workspace", summary: "shared", runningTurnId: "turn-other" })) }); |
| 312 | }); |
| 313 | |
| 314 | test("telegram: a chat the migration disowned does not stream another chat's turn and can start over", async () => { |
| 315 | const bridge = bridges.telegram; |
| 316 | const seedMap = { chats: { |
| 317 | "111": { threadId: "thr-shared", lastSeq: 0, activeTurnId: null }, |
| 318 | "222": { threadId: "thr-shared", lastSeq: 0, activeTurnId: "turn-other", activeMessageKey: "stale-key", |
| 319 | authorizedIdentity: { chatId: "222", chatType: "private", userId: "222", isBot: false } } |
| 320 | } }; |
| 321 | await withBridge(bridge.name, bridge.env, async ({ stub, say, mapPath }) => { |
| 322 | const push = bridge.push(stub); |
| 323 | const created = (await say(push, "222", "/new", /Created thread|pending turn|can only use threads/)).join("\n"); |
| 324 | assert.match(created, /Created thread/, "the stale turn does not block /new"); |
| 325 | const toBob = stub.state.replies.filter((reply) => reply.to === "222").map((reply) => reply.text).join("\n"); |
| 326 | assert.ok(!toBob.includes("OTHER_CHAT_OUTPUT"), "no other chat's turn output is relayed"); |
| 327 | assert.ok(!stub.state.runtimeRequests.some((request) => request.route === "GET /v1/threads/thr-shared/events"), "the shared thread's events are never read"); |
| 328 | const map = JSON.parse(await readFile(mapPath, "utf8")); |
| 329 | assert.equal(map.chats["222"].activeTurnId, null); |
| 330 | }, { seedMap, prepare: (stub) => otherChatEvents(stub.seedThread({ id: "thr-shared", workspace: "/fixture/bridge-workspace", summary: "shared", runningTurnId: "turn-other" })) }); |
| 331 | }); |
| 332 | |
| 333 | async function withStore(fn, options = {}, seed = null) { |
| 334 | const dir = await mkdtemp(path.join(tmpdir(), "cw-thread-owners-")); |
| 335 | const file = path.join(dir, "map.json"); |
| 336 | try { |
| 337 | if (seed) await writeFile(file, JSON.stringify(seed)); |
| 338 | await fn(await ThreadStore.open(file, options), file); |
| 339 | } finally { |
| 340 | await rm(dir, { recursive: true, force: true }); |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | test("thread owners are durable, survive a chat state replacement and never transfer", async () => { |
| 345 | await withStore(async (store, file) => { |
| 346 | await store.recordThreadOwner("a", "t1"); |
| 347 | await store.setChat("a", { threadId: "t1" }); |
| 348 | await store.setChat("a", { threadId: "t2" }); |
| 349 | assert.ok(store.ownsThread("a", "t1")); |
| 350 | assert.ok(!store.ownsThread("b", "t1")); |
| 351 | assert.ok(!store.ownsThread("a", "t1", "other-scope")); |
| 352 | await assert.rejects(store.recordThreadOwner("b", "t1"), /can only use threads/); |
| 353 | await store.recordThreadOwner("a", "t1"); |
| 354 | const reopened = await ThreadStore.open(file); |
| 355 | assert.ok(reopened.ownsThread("a", "t1")); |
| 356 | assert.deepEqual(reopened.ownedThreadIds("a"), ["t1"]); |
| 357 | }); |
| 358 | }); |
| 359 | |
| 360 | test("thread owners are bounded per chat and drop the oldest first", async () => { |
| 361 | await withStore(async (store) => { |
| 362 | for (const id of ["t1", "t2", "t3"]) await store.recordThreadOwner("a", id); |
| 363 | await store.recordThreadOwner("b", "u1"); |
| 364 | assert.deepEqual(store.ownedThreadIds("a"), ["t3", "t2"]); |
| 365 | assert.ok(store.ownsThread("b", "u1")); |
| 366 | }, { ownerLimit: 2 }); |
| 367 | }); |
| 368 | |
| 369 | function runtimeOf(threads, { failing = new Set() } = {}) { |
| 370 | const calls = []; |
| 371 | const runtimeJson = async (route) => { |
| 372 | calls.push(route); |
| 373 | const id = decodeURIComponent(route.split("/").at(-1)); |
| 374 | if (failing.has(id)) throw Object.assign(new Error("connection refused"), { status: undefined }); |
| 375 | if (!(id in threads)) throw Object.assign(new Error("not found"), { status: 404 }); |
| 376 | return { thread: threads[id] }; |
| 377 | }; |
| 378 | return { runtimeJson, calls }; |
| 379 | } |
| 380 | |
| 381 | test("an existing store migrates once: unique threads wait for confirmation, shared ones are owned by no chat", async () => { |
| 382 | const seed = { chats: { |
| 383 | a: { threadId: "only-a" }, b: { threadId: "shared" }, c: { threadId: "shared" }, |
| 384 | w: { threadId: "w-now", bindingAccountId: "acct", threadBindings: [{ threadId: "w-old", accountId: "acct", actorId: "weixin-account:acct:user:w" }] } |
| 385 | } }; |
| 386 | const legacyOwnerScope = (chatId, state) => (state.bindingAccountId ? `weixin-account:${state.bindingAccountId}:user:${chatId}` : ""); |
| 387 | const confirmed = { system_prompt: "bridge", workspace: "/w" }; |
| 388 | const accept = (thread) => thread.system_prompt === "bridge"; |
| 389 | await withStore(async (store, file) => { |
| 390 | assert.ok(!store.ownsThread("a", "only-a"), "a migrated grant is not usable before it is confirmed"); |
| 391 | assert.ok(store.ownershipPending("a", "only-a"), "an unconfirmed grant is pending"); |
| 392 | assert.deepEqual(store.ownedThreadIds("a"), []); |
| 393 | const scope = "weixin-account:acct:user:w"; |
| 394 | assert.ok(store.ownsThread("w", "w-old", scope), "an old per-account binding was recorded by the bridge itself and needs no confirmation"); |
| 395 | assert.ok(!store.ownershipPending("w", "w-old", scope)); |
| 396 | const { runtimeJson, calls } = runtimeOf({ "only-a": confirmed, "w-now": confirmed, shared: confirmed }); |
| 397 | assert.equal(await store.verifyLegacyOwners(runtimeJson, accept), 0); |
| 398 | assert.deepEqual(calls.sort(), ["/v1/threads/only-a", "/v1/threads/w-now"], "only unshared migrated grants are looked up, once each"); |
| 399 | assert.ok(store.ownsThread("a", "only-a")); |
| 400 | assert.ok(!store.ownershipPending("a", "only-a")); |
| 401 | assert.ok(!store.ownsThread("b", "shared") && !store.ownsThread("c", "shared")); |
| 402 | assert.ok(store.ownsThread("w", "w-now", scope) && !store.ownsThread("w", "w-now")); |
| 403 | await store.recordThreadOwner("a", "fresh"); |
| 404 | await store.setChat("c", { threadId: "only-a" }); |
| 405 | const reopened = await ThreadStore.open(file, { legacyOwnerScope }); |
| 406 | assert.ok(!reopened.ownsThread("c", "only-a"), "the migration does not run again once owners are recorded"); |
| 407 | assert.ok(reopened.ownsThread("a", "only-a"), "a confirmed grant survives a restart"); |
| 408 | assert.equal(reopened.legacyOwnerCount(), 0); |
| 409 | }, { legacyOwnerScope }, seed); |
| 410 | }); |
| 411 | |
| 412 | test("a migrated grant is dropped when the thread was not started by the bridge or is gone, and kept unconfirmed when the Runtime cannot be asked", async () => { |
| 413 | const seed = { chats: { a: { threadId: "t-ok" }, b: { threadId: "t-foreign" }, c: { threadId: "t-gone" }, d: { threadId: "t-down" } } }; |
| 414 | const accept = (thread) => thread.system_prompt === "bridge" && thread.workspace === "/w"; |
| 415 | await withStore(async (store, file) => { |
| 416 | const threads = { |
| 417 | "t-ok": { system_prompt: "bridge", workspace: "/w" }, |
| 418 | "t-foreign": { workspace: "/w" }, |
| 419 | "t-down": { system_prompt: "bridge", workspace: "/w" } |
| 420 | }; |
| 421 | assert.equal(await store.verifyLegacyOwners(runtimeOf(threads, { failing: new Set(["t-down"]) }).runtimeJson, accept), 1); |
| 422 | assert.ok(store.ownsThread("a", "t-ok")); |
| 423 | assert.ok(!store.ownershipPending("a", "t-ok")); |
| 424 | for (const [chat, id] of [["b", "t-foreign"], ["c", "t-gone"], ["d", "t-down"]]) assert.ok(!store.ownsThread(chat, id), id); |
| 425 | assert.ok(!store.ownershipPending("b", "t-foreign") && !store.ownershipPending("c", "t-gone")); |
| 426 | assert.ok(store.ownershipPending("d", "t-down")); |
| 427 | const reopened = await ThreadStore.open(file); |
| 428 | assert.equal(reopened.legacyOwnerCount(), 1, "the unconfirmed grant is still pending after a restart"); |
| 429 | assert.ok(reopened.ownershipPending("d", "t-down")); |
| 430 | assert.ok(!reopened.data.threadOwners.some((entry) => entry.threadId === "t-foreign" || entry.threadId === "t-gone")); |
| 431 | assert.equal(await reopened.verifyLegacyOwners(runtimeOf(threads).runtimeJson, accept), 0); |
| 432 | assert.ok(reopened.ownsThread("d", "t-down"), "a later check confirms it"); |
| 433 | assert.ok(!reopened.ownershipPending("d", "t-down")); |
| 434 | }, {}, seed); |
| 435 | }); |
| 436 | |
| 437 | test("pending-ownership recovery preserves stored turns and retained admissions when Runtime thread reads return 503 at startup", async () => { |
| 438 | const tg = bridges.telegram; |
| 439 | const fsBridge = bridges.feishu; |
| 440 | await Promise.all([ |
| 441 | withBridge(tg.name, tg.env, async ({ stub }) => { |
| 442 | await until( |
| 443 | () => turnPosts(stub, "thr-own").some((request) => request.body?.prompt === "RETAINED_PROMPT"), |
| 444 | "retained admission should post after ownership confirms", |
| 445 | 45000 |
| 446 | ); |
| 447 | }, { |
| 448 | seedThreads: [{ id: "thr-own", workspace: BRIDGE_WORKSPACE, systemPrompt: tg.systemPrompt, summary: "own" }], |
| 449 | prepare: (stub) => { stub.state.failDetailUntil = Date.now() + 4000; }, |
| 450 | seedMap: (stub) => ({ chats: { "222": { |
| 451 | threadId: "thr-own", lastSeq: 0, activeTurnId: null, |
| 452 | authorizedIdentity: { chatId: "222", chatType: "private", userId: "222", isBot: false }, |
| 453 | pendingAdmission: { |
| 454 | botAccountId: "1000", runtimeUrl: stub.url, actorId: "telegram-user:222", |
| 455 | identity: { chatId: "222", chatType: "private", userId: "222", username: "", isBot: false }, |
| 456 | messageKey: "telegram:222:77", request: { prompt: "RETAINED_PROMPT", input_summary: "RETAINED_PROMPT" }, |
| 457 | operationKey: null, threadId: "thr-own", submitted: false, sinceSeq: null, |
| 458 | threadRequest: { workspace: BRIDGE_WORKSPACE, system_prompt: tg.systemPrompt } |
| 459 | } |
| 460 | } } }) |
| 461 | }), |
| 462 | withBridge(tg.name, tg.env, async ({ stub }) => { |
| 463 | await until( |
| 464 | () => stub.state.replies.some((reply) => reply.to === "111" && reply.text.includes("OWN_TURN_OUTPUT")), |
| 465 | "telegram stored turn should relay after ownership confirms", |
| 466 | 45000 |
| 467 | ); |
| 468 | }, { |
| 469 | seedMap: { chats: { "111": { |
| 470 | threadId: "thr-own", lastSeq: 0, activeTurnId: "turn-own", activeMessageKey: "k1", |
| 471 | authorizedIdentity: { chatId: "111", chatType: "private", userId: "111", isBot: false } |
| 472 | } } }, |
| 473 | prepare: (stub) => { |
| 474 | stub.state.failDetailUntil = Date.now() + 4000; |
| 475 | const entry = stub.seedThread({ id: "thr-own", workspace: BRIDGE_WORKSPACE, systemPrompt: tg.systemPrompt, summary: "own", runningTurnId: "turn-own" }); |
| 476 | entry.events.push({ seq: 1, thread_id: "thr-own", turn_id: "turn-own", event: "item.delta", payload: { kind: "agent_message", delta: "OWN_TURN_OUTPUT" } }); |
| 477 | entry.events.push({ seq: 2, thread_id: "thr-own", turn_id: "turn-own", event: "turn.completed", payload: { turn: { status: "completed" } } }); |
| 478 | } |
| 479 | }), |
| 480 | withBridge(fsBridge.name, fsBridge.env, async ({ stub }) => { |
| 481 | await until( |
| 482 | () => stub.state.replies.some((reply) => reply.to === "oc_alice" && reply.text.includes("OWN_FEISHU_OUTPUT")), |
| 483 | "feishu stored turn should reattach after ownership confirms", |
| 484 | 45000 |
| 485 | ); |
| 486 | }, { |
| 487 | seedMap: { chats: { oc_alice: { |
| 488 | threadId: "thr-own", lastSeq: 0, activeTurnId: "turn-own", |
| 489 | authorizedIdentity: { chatId: "oc_alice", chatType: "p2p", openId: "ou_oc_alice" } |
| 490 | } } }, |
| 491 | prepare: (stub) => { |
| 492 | stub.state.failDetailUntil = Date.now() + 4000; |
| 493 | const entry = stub.seedThread({ id: "thr-own", workspace: BRIDGE_WORKSPACE, systemPrompt: fsBridge.systemPrompt, summary: "own", runningTurnId: "turn-own" }); |
| 494 | entry.events.push({ seq: 1, thread_id: "thr-own", turn_id: "turn-own", event: "item.delta", payload: { kind: "agent_message", delta: "OWN_FEISHU_OUTPUT" } }); |
| 495 | entry.events.push({ seq: 2, thread_id: "thr-own", turn_id: "turn-own", event: "turn.completed", payload: { turn: { status: "completed" } } }); |
| 496 | } |
| 497 | }) |
| 498 | ]); |
| 499 | }); |
| 500 | |
| 501 | test("core approval decisions check ownership only when the caller supplies it", async () => { |
| 502 | await withStore(async (store) => { |
| 503 | await store.setChat("a", { threadId: "t1" }); |
| 504 | await store.recordTurnOrigin("a", "t1", "turn-1", "human-1"); |
| 505 | const posts = []; |
| 506 | const runtimeJson = async (route, options = {}) => { |
| 507 | if (options.method === "POST") { posts.push(route); return {}; } |
| 508 | return { thread: {}, pending_approvals: [{ id: "appr-1", turn_id: "turn-1" }] }; |
| 509 | }; |
| 510 | const args = { store, chatId: "a", actorId: "human-1", approvalId: "appr-1", decision: "allow" }; |
| 511 | await assert.rejects(decideApproval(runtimeJson, { ...args, ownsThread: (id) => store.ownsThread("a", id) }), /can only use threads/); |
| 512 | assert.deepEqual(posts, []); |
| 513 | await decideApproval(runtimeJson, args); |
| 514 | assert.deepEqual(posts, ["/v1/approvals/appr-1"], "a store that records no owners keeps its behaviour"); |
| 515 | }); |
| 516 | }); |
| 517 |