| 1 | import assert from "node:assert/strict"; |
| 2 | import { createServer } from "node:http"; |
| 3 | import { once } from "node:events"; |
| 4 | import { mkdtemp, readFile, rm } from "node:fs/promises"; |
| 5 | import { tmpdir } from "node:os"; |
| 6 | import path from "node:path"; |
| 7 | import test from "node:test"; |
| 8 | import { fileURLToPath } from "node:url"; |
| 9 | |
| 10 | import * as bridgeCore from "../../bridge-core/src/lib.mjs"; |
| 11 | import * as feishuLib from "../src/lib.mjs"; |
| 12 | |
| 13 | const indexPath = fileURLToPath(new URL("../src/index.mjs", import.meta.url)); |
| 14 | const indexSource = await readFile(indexPath, "utf8"); |
| 15 | |
| 16 | function extract(source, name) { |
| 17 | const marker = new RegExp(`^(?:async )?function ${name}\\(`, "m"); |
| 18 | const start = source.search(marker); |
| 19 | assert.notEqual(start, -1, `missing function ${name}`); |
| 20 | const rest = source.slice(start); |
| 21 | const next = rest.slice(1).search(/\n(?:async )?function \w+\(/); |
| 22 | return next === -1 ? rest : rest.slice(0, next + 1); |
| 23 | } |
| 24 | |
| 25 | function loadFunctions(names, env) { |
| 26 | const code = names.map((name) => extract(indexSource, name)).join("\n") + `\nreturn { ${names.join(", ")} };`; |
| 27 | return new Function(...Object.keys(env), code)(...Object.values(env)); |
| 28 | } |
| 29 | |
| 30 | async function withStore(t, setup) { |
| 31 | const dir = await mkdtemp(path.join(tmpdir(), "cw-feishu-reattach-")); |
| 32 | t.after(() => rm(dir, { recursive: true, force: true })); |
| 33 | const filePath = path.join(dir, "thread-map.json"); |
| 34 | const store = await bridgeCore.ThreadStore.open(filePath, { messageLimit: 200 }); |
| 35 | if (setup) await setup(store); |
| 36 | return { store, filePath }; |
| 37 | } |
| 38 | |
| 39 | async function withRuntime(t, handler) { |
| 40 | const server = createServer(handler); |
| 41 | server.listen(0, "127.0.0.1"); |
| 42 | await once(server, "listening"); |
| 43 | t.after(() => new Promise((resolve) => server.close(resolve))); |
| 44 | const runtimeUrl = `http://127.0.0.1:${server.address().port}`; |
| 45 | return { |
| 46 | runtimeUrl, |
| 47 | ...bridgeCore.createRuntimeClient({ runtimeUrl, runtimeToken: "fixture-token" }) |
| 48 | }; |
| 49 | } |
| 50 | |
| 51 | function makeIdentity(chatId = "oc_chat", messageId = "om_orig") { |
| 52 | return { |
| 53 | chatId, |
| 54 | chatType: "p2p", |
| 55 | openId: "ou_alice", |
| 56 | unionId: "", |
| 57 | userId: "", |
| 58 | messageId |
| 59 | }; |
| 60 | } |
| 61 | |
| 62 | test("reattach replays offline completed turn from lastSeq even when a newer turn is running", async (t) => { |
| 63 | const seenRequests = []; |
| 64 | const runtime = await withRuntime(t, (req, res) => { |
| 65 | seenRequests.push(`${req.method} ${req.url}`); |
| 66 | res.setHeader("connection", "close"); |
| 67 | if (req.url === "/v1/threads/thr-1") { |
| 68 | res.setHeader("content-type", "application/json"); |
| 69 | res.end(JSON.stringify({ |
| 70 | id: "thr-1", |
| 71 | latest_seq: 6, |
| 72 | turns: [ |
| 73 | { id: "turn-1", status: "completed" }, |
| 74 | { id: "turn-2", status: "in_progress" } |
| 75 | ] |
| 76 | })); |
| 77 | return; |
| 78 | } |
| 79 | if (req.url === "/v1/threads/thr-1/events?since_seq=2") { |
| 80 | res.setHeader("content-type", "text/event-stream"); |
| 81 | const events = [ |
| 82 | { seq: 3, thread_id: "thr-1", turn_id: "turn-1", event: "item.delta", payload: { kind: "agent_message", delta: "world!" } }, |
| 83 | { seq: 4, thread_id: "thr-1", turn_id: "turn-1", event: "turn.completed", payload: { turn: { status: "completed" } } }, |
| 84 | { seq: 5, thread_id: "thr-1", turn_id: "turn-2", event: "item.delta", payload: { kind: "agent_message", delta: "other turn" } } |
| 85 | ]; |
| 86 | res.end(events.map((e) => `data: ${JSON.stringify(e)}\n\n`).join("")); |
| 87 | return; |
| 88 | } |
| 89 | res.statusCode = 404; |
| 90 | res.end("{}"); |
| 91 | }); |
| 92 | |
| 93 | const { store, filePath } = await withStore(t, async (s) => { |
| 94 | await s.recordThreadOwner("oc_chat", "thr-1"); |
| 95 | await s.setChat("oc_chat", { |
| 96 | threadId: "thr-1", |
| 97 | activeTurnId: "turn-1", |
| 98 | activeReplyToMessageId: "om_orig", |
| 99 | replyToMessageId: "om_later_status", |
| 100 | lastSeq: 2, |
| 101 | responseText: "Hello ", |
| 102 | authorizedIdentity: makeIdentity("oc_chat", "om_orig") |
| 103 | }); |
| 104 | }); |
| 105 | |
| 106 | const sent = []; |
| 107 | const { reattachActiveTurns } = loadFunctions(["reattachActiveTurns", "streamTurnEvents"], { |
| 108 | ...bridgeCore, |
| 109 | ...feishuLib, |
| 110 | threadStore: store, |
| 111 | activeTurnTasks: new Map(), |
| 112 | runtimeJson: runtime.runtimeJson, |
| 113 | authHeaders: runtime.authHeaders, |
| 114 | config: { |
| 115 | runtimeUrl: runtime.runtimeUrl, |
| 116 | allowlist: ["oc_chat"], |
| 117 | allowGroups: false, |
| 118 | allowUnlisted: false, |
| 119 | maxReplyChars: 3500, |
| 120 | turnTimeoutMs: 5000 |
| 121 | }, |
| 122 | sendText: async (chatId, text, options) => { |
| 123 | sent.push({ chatId, text, options }); |
| 124 | } |
| 125 | }); |
| 126 | |
| 127 | await reattachActiveTurns(); |
| 128 | |
| 129 | assert.deepEqual(seenRequests, [ |
| 130 | "GET /v1/threads/thr-1", |
| 131 | "GET /v1/threads/thr-1/events?since_seq=2" |
| 132 | ]); |
| 133 | assert.deepEqual(sent, [ |
| 134 | { |
| 135 | chatId: "oc_chat", |
| 136 | text: "Hello world!", |
| 137 | options: { replyToMessageId: "om_orig" } |
| 138 | } |
| 139 | ]); |
| 140 | |
| 141 | const reopened = await bridgeCore.ThreadStore.open(filePath, { messageLimit: 200 }); |
| 142 | const finalState = await reopened.getChat("oc_chat"); |
| 143 | assert.equal(finalState.activeTurnId, null); |
| 144 | assert.equal(finalState.activeReplyToMessageId, null); |
| 145 | assert.equal(finalState.lastSeq, 4); |
| 146 | assert.equal(finalState.responseText, ""); |
| 147 | }); |
| 148 | |
| 149 | test("terminal cursor is preserved when delivery fails and cleared only after retry succeeds", async (t) => { |
| 150 | const runtime = await withRuntime(t, (req, res) => { |
| 151 | res.setHeader("connection", "close"); |
| 152 | if (req.url === "/v1/threads/thr-1") { |
| 153 | res.setHeader("content-type", "application/json"); |
| 154 | res.end(JSON.stringify({ |
| 155 | id: "thr-1", |
| 156 | latest_seq: 4, |
| 157 | turns: [{ id: "turn-1", status: "completed" }] |
| 158 | })); |
| 159 | return; |
| 160 | } |
| 161 | if (req.url.startsWith("/v1/threads/thr-1/events?since_seq=")) { |
| 162 | const since = Number(new URL(req.url, "http://localhost").searchParams.get("since_seq")); |
| 163 | res.setHeader("content-type", "text/event-stream"); |
| 164 | const events = [ |
| 165 | { seq: 3, thread_id: "thr-1", turn_id: "turn-1", event: "item.delta", payload: { kind: "agent_message", delta: "final answer" } }, |
| 166 | { seq: 4, thread_id: "thr-1", turn_id: "turn-1", event: "turn.completed", payload: { turn: { status: "completed" } } } |
| 167 | ].filter((e) => e.seq > since); |
| 168 | res.end(events.map((e) => `data: ${JSON.stringify(e)}\n\n`).join("")); |
| 169 | return; |
| 170 | } |
| 171 | res.statusCode = 404; |
| 172 | res.end("{}"); |
| 173 | }); |
| 174 | |
| 175 | const { store, filePath } = await withStore(t, async (s) => { |
| 176 | await s.recordThreadOwner("oc_chat", "thr-1"); |
| 177 | await s.setChat("oc_chat", { |
| 178 | threadId: "thr-1", |
| 179 | activeTurnId: "turn-1", |
| 180 | activeReplyToMessageId: "om_orig", |
| 181 | lastSeq: 2, |
| 182 | responseText: "", |
| 183 | authorizedIdentity: makeIdentity("oc_chat", "om_orig") |
| 184 | }); |
| 185 | }); |
| 186 | |
| 187 | let shouldFail = true; |
| 188 | const delivered = []; |
| 189 | const { reattachActiveTurns } = loadFunctions(["reattachActiveTurns", "streamTurnEvents"], { |
| 190 | ...bridgeCore, |
| 191 | ...feishuLib, |
| 192 | threadStore: store, |
| 193 | activeTurnTasks: new Map(), |
| 194 | runtimeJson: runtime.runtimeJson, |
| 195 | authHeaders: runtime.authHeaders, |
| 196 | config: { |
| 197 | runtimeUrl: runtime.runtimeUrl, |
| 198 | allowlist: ["oc_chat"], |
| 199 | allowGroups: false, |
| 200 | allowUnlisted: false, |
| 201 | maxReplyChars: 3500, |
| 202 | turnTimeoutMs: 5000 |
| 203 | }, |
| 204 | sendText: async (chatId, text, options) => { |
| 205 | if (shouldFail) throw new Error("transient feishu send failure"); |
| 206 | delivered.push({ chatId, text, options }); |
| 207 | } |
| 208 | }); |
| 209 | |
| 210 | await reattachActiveTurns(); |
| 211 | |
| 212 | const afterFailure = await (await bridgeCore.ThreadStore.open(filePath, { messageLimit: 200 })).getChat("oc_chat"); |
| 213 | assert.equal(afterFailure.activeTurnId, "turn-1"); |
| 214 | assert.equal(afterFailure.activeReplyToMessageId, "om_orig"); |
| 215 | assert.equal(afterFailure.lastSeq, 3); |
| 216 | assert.equal(afterFailure.responseText, "final answer"); |
| 217 | assert.equal(delivered.length, 0); |
| 218 | |
| 219 | shouldFail = false; |
| 220 | await reattachActiveTurns(); |
| 221 | |
| 222 | assert.deepEqual(delivered, [ |
| 223 | { |
| 224 | chatId: "oc_chat", |
| 225 | text: "final answer", |
| 226 | options: { replyToMessageId: "om_orig" } |
| 227 | } |
| 228 | ]); |
| 229 | const afterSuccess = await (await bridgeCore.ThreadStore.open(filePath, { messageLimit: 200 })).getChat("oc_chat"); |
| 230 | assert.equal(afterSuccess.activeTurnId, null); |
| 231 | assert.equal(afterSuccess.activeReplyToMessageId, null); |
| 232 | assert.equal(afterSuccess.lastSeq, 4); |
| 233 | assert.equal(afterSuccess.responseText, ""); |
| 234 | }); |
| 235 | |
| 236 | test("cursor patches are guarded by (chatId, threadId, turnId) when chat rebinds mid-stream", async (t) => { |
| 237 | const { store } = await withStore(t, async (s) => { |
| 238 | await s.setChat("oc_chat", { |
| 239 | threadId: "thr-1", |
| 240 | activeTurnId: "turn-1", |
| 241 | lastSeq: 1, |
| 242 | responseText: "old" |
| 243 | }); |
| 244 | }); |
| 245 | |
| 246 | assert.equal( |
| 247 | await feishuLib.patchTurnCursor(store, "oc_chat", "thr-1", "turn-1", { lastSeq: 2, responseText: "updated" }), |
| 248 | true |
| 249 | ); |
| 250 | assert.equal((await store.getChat("oc_chat")).lastSeq, 2); |
| 251 | |
| 252 | await store.setChat("oc_chat", { |
| 253 | threadId: "thr-2", |
| 254 | activeTurnId: null, |
| 255 | lastSeq: 0, |
| 256 | responseText: "" |
| 257 | }); |
| 258 | |
| 259 | assert.equal( |
| 260 | await feishuLib.patchTurnCursor(store, "oc_chat", "thr-1", "turn-1", { lastSeq: 99, responseText: "stale" }), |
| 261 | false |
| 262 | ); |
| 263 | const current = await store.getChat("oc_chat"); |
| 264 | assert.equal(current.threadId, "thr-2"); |
| 265 | assert.equal(current.lastSeq, 0); |
| 266 | assert.equal(current.responseText, ""); |
| 267 | }); |
| 268 | |
| 269 | test("concurrent prompt cannot overwrite pending delivery state", async (t) => { |
| 270 | let postTurnCount = 0; |
| 271 | const runtime = await withRuntime(t, (req, res) => { |
| 272 | res.setHeader("connection", "close"); |
| 273 | res.setHeader("content-type", "application/json"); |
| 274 | if (req.method === "POST" && req.url.endsWith("/turns")) { |
| 275 | postTurnCount += 1; |
| 276 | res.end(JSON.stringify({ turn: { id: `turn-new-${postTurnCount}`, thread_id: "thr-1" } })); |
| 277 | return; |
| 278 | } |
| 279 | res.end(JSON.stringify({ id: "thr-1", latest_seq: 10, turns: [{ id: "turn-1", status: "completed" }] })); |
| 280 | }); |
| 281 | |
| 282 | const { store } = await withStore(t, async (s) => { |
| 283 | await s.recordThreadOwner("oc_chat", "thr-1"); |
| 284 | await s.setChat("oc_chat", { |
| 285 | threadId: "thr-1", |
| 286 | activeTurnId: "turn-1", |
| 287 | activeReplyToMessageId: "om_orig", |
| 288 | replyToMessageId: "om_second", |
| 289 | lastSeq: 2, |
| 290 | responseText: "unsent reply", |
| 291 | authorizedIdentity: makeIdentity("oc_chat", "om_orig") |
| 292 | }); |
| 293 | }); |
| 294 | |
| 295 | const sent = []; |
| 296 | const { runPrompt } = loadFunctions(["turnActor", "runPrompt"], { |
| 297 | ...bridgeCore, |
| 298 | ...feishuLib, |
| 299 | threadStore: store, |
| 300 | activeTurnTasks: new Map(), |
| 301 | runtimeJson: runtime.runtimeJson, |
| 302 | ensureThread: async () => store.getChat("oc_chat"), |
| 303 | streamTurnEvents: async () => true, |
| 304 | config: { model: "auto", mode: "agent", allowShell: true, trustMode: false, autoApprove: false }, |
| 305 | sendText: async (chatId, text, options) => { |
| 306 | sent.push({ chatId, text, options }); |
| 307 | } |
| 308 | }); |
| 309 | |
| 310 | await runPrompt("oc_chat", "another prompt", makeIdentity("oc_chat", "om_second")); |
| 311 | |
| 312 | assert.equal(postTurnCount, 0); |
| 313 | assert.equal(sent.length, 1); |
| 314 | assert.match(sent[0].text, /turn-1/); |
| 315 | const persisted = await store.getChat("oc_chat"); |
| 316 | assert.equal(persisted.activeTurnId, "turn-1"); |
| 317 | assert.equal(persisted.activeReplyToMessageId, "om_orig"); |
| 318 | assert.equal(persisted.lastSeq, 2); |
| 319 | assert.equal(persisted.responseText, "unsent reply"); |
| 320 | }); |
| 321 | |
| 322 | test("sendText honors pinned replyToMessageId even after chat replyToMessageId changes", async (t) => { |
| 323 | const { store } = await withStore(t, async (s) => { |
| 324 | await s.setChat("oc_chat", { |
| 325 | threadId: "thr-1", |
| 326 | replyToMessageId: "om_newer" |
| 327 | }); |
| 328 | }); |
| 329 | |
| 330 | const repliedTo = []; |
| 331 | const createdFor = []; |
| 332 | const { sendText } = loadFunctions(["sendText"], { |
| 333 | ...bridgeCore, |
| 334 | ...feishuLib, |
| 335 | threadStore: store, |
| 336 | config: { maxReplyChars: 3500 }, |
| 337 | client: { |
| 338 | im: { |
| 339 | v1: { |
| 340 | message: { |
| 341 | reply: async ({ path: p }) => { |
| 342 | repliedTo.push(p.message_id); |
| 343 | return { code: 0 }; |
| 344 | }, |
| 345 | create: async ({ data }) => { |
| 346 | createdFor.push(data.receive_id); |
| 347 | return { code: 0 }; |
| 348 | } |
| 349 | } |
| 350 | } |
| 351 | } |
| 352 | } |
| 353 | }); |
| 354 | |
| 355 | await sendText("oc_chat", "pinned reply", { replyToMessageId: "om_orig" }); |
| 356 | await sendText("oc_chat", "chat level", { replyToMessageId: null }); |
| 357 | await sendText("oc_chat", "default reply"); |
| 358 | |
| 359 | assert.deepEqual(repliedTo, ["om_orig", "om_newer"]); |
| 360 | assert.deepEqual(createdFor, ["oc_chat"]); |
| 361 | }); |
| 362 |