A local-first multi-agent app development platform, built on PenguinHarness
test(server): move the messaging suites onto the shared fakes (#929)
Yaowei Zhengc3d84c28971c
diff --git a/packages/server/test/fixtures/feishu.ts b/packages/server/test/fixtures/feishu.tsnew file mode 100644index 00000000..41e17b78--- /dev/null+++ b/packages/server/test/fixtures/feishu.ts@@ -0,0 +1,296 @@+/**+ * The suite's one Feishu SDK fake (the connector's FeishuSdk seam): every client call is+ * recorded, each opened connection is handed back so a test can push inbound events, and+ * each failure a test needs is a switch. Nothing here opens a network connection.+ */+import type { FeishuCard } from "../../src/runtime/messaging/feishu-card.js";+import { collectUnderCap } from "../../src/runtime/messaging/media.js";+import type {+ FeishuApiClient,+ FeishuCredentials,+ FeishuEventHandlers,+ FeishuImageData,+ FeishuInboundEvent,+ FeishuSdk,+} from "../../src/runtime/messaging/feishu-sdk.js";++export interface SentText {+ kind: "send" | "reply";+ target: string;+ text: string;+}++/**+ * One picture or attachment that reached the channel. Byte count rather than the bytes:+ * what the assertions care about is which file went where, in what order, and that the+ * caps let it through.+ */+export interface SentMedia {+ kind: "image" | "file";+ target: string;+ fileName: string;+ bytes: number;+}++/** Everything one client sent, in order — the ordering of text against media is the point. */+export type Sent = SentText | SentMedia;++/** One resource download the bridge asked for, cap included (the fake stands in for the SDK adapter). */+export interface ImageFetch {+ messageId: string;+ fileKey: string;+ maxBytes: number;+}++/** The rich-text content out of a card, which is the whole of what a card carries here. */+export function cardContent(card: FeishuCard): string {+ const element = card.body.elements[0];+ if (card.schema !== "2.0" || element?.tag !== "markdown") {+ throw new Error(`unexpected card envelope: ${JSON.stringify(card)}`);+ }+ return element.content;+}++/** The bytes as a stream, so the fakes read them through the real capped reader. */+export async function* oneChunk(bytes: Buffer): AsyncGenerator<Uint8Array> {+ yield bytes;+}++/** A PNG's magic bytes plus a little payload: enough for a data URL to be asserted verbatim. */+export const IMAGE_BYTES = Buffer.from([+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x01, 0x02, 0x03,+]);++/** An inbound file's contents — text, so a failed write shows up as the wrong bytes on disk. */+export const FILE_BYTES = Buffer.from("quarterly revenue: 42\n", "utf8");++export class FakeClient implements FeishuApiClient {+ readonly sends: Sent[] = [];+ /**+ * The card sends specifically, as the rich-text content they carried.+ *+ * A card is ALSO recorded in `sends` as an ordinary text send, so the routing, ordering+ * and threading assertions read the same whichever transport carried the message — those+ * are what they are about. This list is what separates the two, and it is what a test+ * asserting the plain path checks is empty.+ */+ readonly cards: SentText[] = [];+ /** When each send was recorded, parallel to `sends`: what the pacing test measures. */+ readonly sentAt: number[] = [];+ readonly imageFetches: ImageFetch[] = [];+ readonly fileFetches: ImageFetch[] = [];+ checks = 0;+ constructor(+ readonly creds: FeishuCredentials,+ private readonly sdk: FakeFeishuSdk,+ ) {}+ async checkCredentials(): Promise<null> {+ this.checks++;+ if (this.sdk.failCheck !== null) throw new Error(this.sdk.failCheck);+ return null;+ }+ async sendText(chatId: string, text: string): Promise<void> {+ if (this.sdk.failSendWith !== null) throw this.sdk.failSendWith;+ if (this.sdk.failSend !== null) throw new Error(this.sdk.failSend);+ this.sdk.noteSend();+ this.record({ kind: "send", target: chatId, text });+ await this.sdk.hold();+ }+ async replyText(messageId: string, text: string): Promise<void> {+ this.sdk.noteSend();+ this.record({ kind: "reply", target: messageId, text });+ await this.sdk.hold();+ }+ async sendCard(chatId: string, card: FeishuCard): Promise<void> {+ // The typed failures fire on a card exactly as they do on a text bubble: Feishu refuses a+ // missing scope on EVERY send, whatever the msg_type, so a fake that let a card through+ // would make the card path quietly immune to the failure the text path is asserted on.+ if (this.sdk.failSendWith !== null) throw this.sdk.failSendWith;+ if (this.sdk.failCard !== null) throw this.sdk.failCard;+ if (this.sdk.failSend !== null) throw new Error(this.sdk.failSend);+ this.sdk.noteSend();+ this.recordCard({ kind: "send", target: chatId, text: cardContent(card) });+ await this.sdk.hold();+ }+ async replyCard(messageId: string, card: FeishuCard): Promise<void> {+ if (this.sdk.failSendWith !== null) throw this.sdk.failSendWith;+ if (this.sdk.failCard !== null) throw this.sdk.failCard;+ this.sdk.noteSend();+ this.recordCard({ kind: "reply", target: messageId, text: cardContent(card) });+ await this.sdk.hold();+ }+ private recordCard(sent: SentText): void {+ this.cards.push(sent);+ this.record(sent);+ }+ private record(sent: SentText): void {+ this.sends.push(sent);+ this.sentAt.push(Date.now());+ }+ async botOpenId(): Promise<string | null> {+ this.sdk.botIdentityLookups++;+ // A stalled endpoint: the TCP connection is accepted and the answer never comes.+ if (this.sdk.stallBotOpenId) return new Promise<never>(() => {});+ return this.sdk.botOpenId;+ }+ async fetchMessageImage(args: ImageFetch): Promise<FeishuImageData> {+ this.imageFetches.push(args);+ if (this.sdk.failImageFetchWith !== null) throw this.sdk.failImageFetchWith;+ if (this.sdk.failImageFetch !== null) throw new Error(this.sdk.failImageFetch);+ // The cap is enforced through the REAL machinery the adapter uses, not a hand-written+ // imitation of it: a fake free to throw its own error shape is a fake free to disagree+ // with production about which failure this is (it did, once).+ const data = await collectUnderCap(oneChunk(this.sdk.imageBytes), args.maxBytes, "The image");+ return { data, mimeType: "image/png" };+ }+ async fetchMessageFile(args: ImageFetch): Promise<Buffer> {+ this.fileFetches.push(args);+ if (this.sdk.failFileFetchWith !== null) throw this.sdk.failFileFetchWith;+ if (this.sdk.failFileFetch !== null) throw new Error(this.sdk.failFileFetch);+ // Through the REAL capped reader, for the reason fetchMessageImage gives.+ return collectUnderCap(oneChunk(this.sdk.fileBytes), args.maxBytes, "The file");+ }+ async sendImage(chatId: string, file: { fileName: string; data: Buffer }): Promise<void> {+ this.sdk.failMediaSendOnce();+ this.sends.push({+ kind: "image",+ target: chatId,+ fileName: file.fileName,+ bytes: file.data.length,+ });+ }+ async sendFile(chatId: string, file: { fileName: string; data: Buffer }): Promise<void> {+ this.sdk.failMediaSendOnce();+ this.sends.push({+ kind: "file",+ target: chatId,+ fileName: file.fileName,+ bytes: file.data.length,+ });+ }+}++export class FakeConnection {+ closed = false;+ constructor(+ readonly creds: FeishuCredentials,+ readonly handlers: FeishuEventHandlers,+ ) {}+ close(): void {+ this.closed = true;+ }+ fire(evt: FeishuInboundEvent): Promise<void> {+ return Promise.resolve(this.handlers.onMessage(evt));+ }+}++export class FakeFeishuSdk implements FeishuSdk {+ readonly clients: FakeClient[] = [];+ readonly connections: FakeConnection[] = [];+ /** Non-null makes checkCredentials throw with this message. */+ failCheck: string | null = null;+ /** Non-null makes the send with this 1-based number (counted across clients) throw. */+ failSendAt: number | null = null;+ /** Non-null parks every send on this promise, holding the bridge's send chain open. */+ heldSends: Promise<void> | null = null;+ private sendCount = 0;+ /** Every send passes here first: it counts, and throws for the one a test marked. */+ noteSend(): void {+ this.sendCount += 1;+ if (this.sendCount === this.failSendAt) throw new Error("Too Many Requests: retry after 5");+ }+ /** Awaited after each send: instant unless a test is holding sends open. */+ hold(): Promise<void> {+ return this.heldSends ?? Promise.resolve();+ }+ /** What `/open-apis/bot/v3/info` reports for this app; null = the identity is unavailable. */+ botOpenId: string | null = null;+ /** Makes that lookup never answer, so a test can prove connect() does not wait on it. */+ stallBotOpenId = false;+ /** Lookups the connector has started (one per connection, off the connect path). */+ botIdentityLookups = 0;+ /** Non-null makes every outbound sendText throw with this message. */+ failSend: string | null = null;+ /** Non-null makes every outbound sendText throw THIS — for the failure shapes that carry data. */+ failSendWith: Error | null = null;+ /**+ * Non-null makes every CARD send throw this, leaving the plain text sends working — the+ * shape of a channel that refuses a rendering and accepts the message behind it.+ */+ failCard: Error | null = null;+ /**+ * Non-null holds every createClient until it resolves, which is what makes the bridge's+ * one await between reading the binding row and its first send observable to a test.+ */+ createClientGate: Promise<void> | null = null;+ /** How many createClient calls the gate has held. */+ gated = 0;+ /** Non-null makes fetchMessageImage throw with this message (a dead image_key, a network fault). */+ failImageFetch: string | null = null;+ /** Non-null makes it throw THIS — for the failure shapes that carry data, not just text. */+ failImageFetchWith: Error | null = null;+ /** What an image download resolves to; oversize bytes exercise the cap. */+ imageBytes: Buffer = IMAGE_BYTES;+ /** Non-null makes fetchMessageFile throw with this message (a dead file_key, a network fault). */+ failFileFetch: string | null = null;+ /** Non-null makes it throw THIS — for the failure shapes that carry data, not just text. */+ failFileFetchWith: Error | null = null;+ /** What a file download resolves to; oversize bytes exercise the cap. */+ fileBytes: Buffer = FILE_BYTES;+ /** Fails this many upcoming outbound image/file sends (the channel refusing an upload). */+ failMediaSends = 0;+ /** Non-null makes EVERY media send throw this — for the failure shapes that carry data. */+ failMediaSendWith: Error | null = null;+ /** Consumes one scheduled media-send failure, throwing when there is one. */+ failMediaSendOnce(): void {+ if (this.failMediaSendWith !== null) throw this.failMediaSendWith;+ if (this.failMediaSends > 0) {+ this.failMediaSends -= 1;+ throw new Error("upload rejected");+ }+ }+ async createClient(creds: FeishuCredentials): Promise<FeishuApiClient> {+ if (this.createClientGate !== null) {+ this.gated++;+ await this.createClientGate;+ }+ const client = new FakeClient(creds, this);+ this.clients.push(client);+ return client;+ }+ async connect(creds: FeishuCredentials, handlers: FeishuEventHandlers): Promise<FakeConnection> {+ const conn = new FakeConnection(creds, handlers);+ this.connections.push(conn);+ handlers.onReady?.();+ return conn;+ }+ /** Everything sent through any client, in order (texts and media interleaved). */+ allSends(): Sent[] {+ return this.clients.flatMap((c) => c.sends);+ }+ /** Their timestamps, in the same order. */+ allSentAt(): number[] {+ return this.clients.flatMap((c) => c.sentAt);+ }+ /** Just the text messages — for the assertions that read `.text`. */+ allTexts(): SentText[] {+ return this.allSends().filter((s): s is SentText => s.kind === "send" || s.kind === "reply");+ }+ /** Only the messages that went out as an interactive card, across every client. */+ allCards(): SentText[] {+ return this.clients.flatMap((c) => c.cards);+ }+ /** Every image download asked of any client, in order. */+ allImageFetches(): ImageFetch[] {+ return this.clients.flatMap((c) => c.imageFetches);+ }+ /** Every file download asked of any client, in order. */+ allFileFetches(): ImageFetch[] {+ return this.clients.flatMap((c) => c.fileFetches);+ }+ lastConnection(): FakeConnection {+ const conn = this.connections.at(-1);+ if (!conn) throw new Error("no fake connection was opened");+ return conn;+ }+}diff --git a/packages/server/test/fixtures/forwarding.ts b/packages/server/test/fixtures/forwarding.tsnew file mode 100644index 00000000..58498777--- /dev/null+++ b/packages/server/test/fixtures/forwarding.ts@@ -0,0 +1,17 @@+/**+ * A stand-in that forwards to whatever `current()` returns at the moment it is used.+ *+ * What lets one app serve a whole describe while each case keeps a boundary fake of its own:+ * the app boots with the stand-in, and each case swaps the object behind it. Methods are+ * bound to the object they came from, so its private fields answer as they would directly.+ */+export function forwardingTo<T extends object>(current: () => T): T {+ return new Proxy({} as T, {+ get: (_stand, key) => {+ const target = current();+ const value: unknown = Reflect.get(target, key, target);+ return typeof value === "function" ? value.bind(target) : value;+ },+ has: (_stand, key) => Reflect.has(current(), key),+ });+}diff --git a/packages/server/test/messaging-markdown.test.ts b/packages/server/test/messaging-markdown.test.tsindex a424a5a1..883ea08a 100644--- a/packages/server/test/messaging-markdown.test.ts+++ b/packages/server/test/messaging-markdown.test.ts@@ -1,18 +1,31 @@/**- * The Markdown conversion the four messaging channels relay a reply through: the shared- * parse and chunking (markdown.ts), and each channel's own renderer.+ * The Markdown conversion the four messaging channels relay a reply through: the shared parse+ * and chunking (markdown.ts), and each channel's own renderer. Four renderers because the four+ * platforms accept four different subsets; how a construct a channel CANNOT show degrades is+ * the part a chat reader notices, and model output that merely looks like markup must arrive+ * as text everywhere. Delivery itself is proven against each channel's wire fake in the+ * channel suites; nothing here sends anything.*- * Four renderers rather than one because the four platforms accept four different- * subsets, and the tests are organized to say so: every construct the model actually writes- * is asserted per channel, including the ones a channel CANNOT show, because how a missing- * construct degrades is the part a reader of a chat notices. The escaping cases are grouped- * on their own — a reply is model output steered by whoever is in the chat, so text that- * looks like markup has to arrive as text on every channel.- *- * Delivery — that a rendered send actually goes out with the right `parse_mode` / `msg_type`,- * and that a refused one falls back to plain text — is proven against each channel's own- * wire fake in messaging.test.ts, messaging-telegram.test.ts, messaging-qq.test.ts,- * messaging-wechat.test.ts and messaging-wire.test.ts. Nothing here sends anything.+ * - Parsing reads GFM (tables, task lists) and never throws; only schemes a chat can open are+ * safe link targets.+ * - Telegram gets its inline tags, fenced blocks in pre/code with the language, headings as+ * bold lines, list markers as text, tables in pre, rules as text and images as links, the+ * model's own HTML escaped and a link target's quotes escaped in the href.+ * - Feishu keeps every construct its rich text renders, escapes literal text with entities in+ * one pass, leaves code literal, neutralizes a paragraph opening with a block marker, sends an+ * over-long table as a code block, and wraps the content in the schema 2.0 card envelope.+ * - QQ keeps its documented constructs and rule, sends code as escaped lines and a table as+ * its rows, and escapes with backslashes.+ * - WeChat keeps the most (code and its fence and language, tables, emphasis around Latin but+ * not CJK), escapes a table cell's markers, widens a fence past its content's backticks,+ * flattens over-deep headings, turns an inline image into a link, escapes outside code only.+ * - Every renderer keeps an unopenable link's label and drops only its clickability.+ * - A reply quoting an inbound file's attachment line keeps the marker literal, carries a+ * scratchpad path through a code span byte for byte, escapes its HTML characters, and+ * degrades a path that is genuinely emphasis without losing characters.+ * - Chunking returns a fitting reply whole, cuts between blocks, re-fences an over-long code+ * block, cuts a paragraph between inline runs, keeps blockquote and list prefixes, bounds an+ * unbreakable line as a last resort, and yields chunks every renderer accepts.*/import { describe, expect, it } from "vitest";import { attachedFileLine } from "@prismshadow/penguin-core";@@ -123,8 +136,7 @@ describe("telegramHtmlOf", () => {expect(telegramHtmlOf("<b>not mine</b>")).toBe("<b>not mine</b>");});- it("keeps an unopenable link's label and drops only its clickability", () => {- expect(telegramHtmlOf("[click](javascript:alert(1))")).toBe("click");+ it("escapes a link target's quotes inside the href", () => {expect(telegramHtmlOf('[q](https://x.com/?a="b")')).toBe('<a href="https://x.com/?a="b"">q</a>',);@@ -195,10 +207,6 @@ describe("feishuMarkdownOf", () => {body: { elements: [{ tag: "markdown", content: "**hi**" }] },});});-- it("keeps an unopenable link's label and drops only its clickability", () => {- expect(feishuMarkdownOf("[click](javascript:alert(1))")).toBe("click");- });});// ---------------------------------------------------------------------------@@ -242,10 +250,6 @@ describe("qqMarkdownOf", () => {// At the head of one they are escaped, so a paragraph is not re-read as a heading.expect(qqMarkdownOf("\\# not a heading")).toBe("\\# not a heading");});-- it("keeps an unopenable link's label and drops only its clickability", () => {- expect(qqMarkdownOf("[click](javascript:alert(1))")).toBe("click");- });});// ---------------------------------------------------------------------------@@ -335,10 +339,20 @@ describe("wechatMarkdownOf", () => {// would land in code the reader is meant to copy.expect(wechatMarkdownOf("```\nrm -rf *_[x]\n```")).toBe("```\nrm -rf *_[x]\n```");});+});- it("keeps an unopenable link's label and drops only its clickability", () => {- expect(wechatMarkdownOf("[click](javascript:alert(1))")).toBe("click");- });+describe("every renderer", () => {+ it.each([+ ["telegram", telegramHtmlOf],+ ["feishu", feishuMarkdownOf],+ ["qq", qqMarkdownOf],+ ["wechat", wechatMarkdownOf],+ ] as const)(+ "%s keeps an unopenable link's label and drops only its clickability",+ (_, render) => {+ expect(render("[click](javascript:alert(1))")).toBe("click");+ },+ );});// ---------------------------------------------------------------------------diff --git a/packages/server/test/messaging-qq-scan.test.ts b/packages/server/test/messaging-qq-scan.test.tsindex 3278c509..f0ebc2ee 100644--- a/packages/server/test/messaging-qq-scan.test.ts+++ b/packages/server/test/messaging-qq-scan.test.ts@@ -1,15 +1,27 @@/**- * QQ scan-to-connect tests: the three-call bind protocol, the AES-GCM framing that carries- * the App Secret out of it, the in-memory task table, and the routes.+ * QQ scan-to-connect: the three-call bind protocol, the AES-GCM framing that carries the App+ * Secret out of it, the in-memory task table, and the routes. Throughout, the AES key never+ * leaves the server: every route case checks the whole response body for it.*- * The framing is what these tests exist for. `bot_encrypt_secret` is base64 with a 12-byte- * IV in front and a 16-byte auth tag at the end, and nothing in the payload says so — a- * wrong offset yields an authentication failure rather than a wrong-looking string, so the- * round-trip here (encrypted by the test with the standard library, decrypted by the- * module) is the only thing that can prove the layout is the one Tencent actually sends.- *- * The second thing pinned throughout: the AES key never leaves the server. Every route- * assertion checks the whole response body for it.+ * - `bot_encrypt_secret` round-trips the platform's framing (a 12-byte IV in front, a 16-byte+ * tag at the end) and fails loudly on a wrong key, a tampered or a truncated payload — the+ * round-trip is the only thing that can prove the layout, since a wrong offset yields an+ * authentication failure rather than a wrong-looking string.+ * - The QR page URL encodes both of its values.+ * - The transport reads the `{retcode, msg, data}` envelope (a non-zero retcode throws),+ * normalizes the completed payload (the App ID arrives as a number), and maps the status+ * enum, reading an unknown value as still pending.+ * - The service keeps the key to itself and consumes a task on the poll that resolves it;+ * refuses another Session's task and an id it never issued; expires a task by its own clock+ * and by the platform's answer; hands one of two concurrent polls the result; puts a task+ * back when the request failed; bounds tasks per Session; sweeps abandoned tasks; forgets+ * the key on cancel.+ * - The routes start a scan with a task, a URL and an interval (never the key); a completed+ * poll saves the binding with the App ID as the account and no secret in the answer, and it+ * is editable like a typed one; a platform failure is a 502; a cancelled task, or one of+ * another Session, cannot be polled; every route is owner-only; a scan is refused while the+ * connection is enabled, and one completing onto a connection enabled meanwhile runs the+ * account guard.*/import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { createCipheriv, randomBytes } from "node:crypto";@@ -18,7 +30,6 @@ import type {QQScanPollResponse,QQScanStartResponse,} from "../src/api/types.js";-import type { SessionRow } from "../src/db/repos/sessions.js";import {QQ_SCAN_TASK_TTL_MS,QQScanService,@@ -28,6 +39,8 @@ import {qqScanQrUrl,} from "../src/runtime/messaging/qq-scan.js";import type { QQBindPollResult, QQScanTransport } from "../src/runtime/messaging/qq-scan.js";+import { stubFetch } from "./fixtures/fetch.js";+import { sessionRow } from "./fixtures/session.js";import { apiClient, createTestApp, provisionUser } from "./helpers.js";import type { TestApp } from "./helpers.js";@@ -98,21 +111,6 @@ class FakeScanTransport implements QQScanTransport {}}-function sessionRowOf(sessionId: string, projectId: string): SessionRow {- return {- sessionId,- projectId,- agentId: "default_agent",- provider: "custom",- modelId: "m1",- workspace: "/tmp/w",- approvalMode: "allow-all",- title: null,- createdAt: new Date().toISOString(),- lastActiveAt: new Date().toISOString(),- };-}-describe("decryptQQBotSecret", () => {it("round-trips the platform's framing: IV in front, tag at the end", () => {const key = newQQScanKey();@@ -155,38 +153,41 @@ describe("qqScanQrUrl", () => {});describe("createQQScanTransport", () => {- const originalFetch = globalThis.fetch;afterEach(() => {- globalThis.fetch = originalFetch;+ vi.unstubAllGlobals();});it("reads the {retcode, msg, data} envelope and turns a non-zero retcode into a throw", async () => {- const calls: Array<{ url: string; body: unknown }> = [];- globalThis.fetch = (async (url: string, init: { body: string }) => {- calls.push({ url, body: JSON.parse(init.body) as unknown });- if (url.endsWith("/lite/create_bind_task")) {- return new Response(JSON.stringify({ retcode: 0, data: { task_id: "T1" } }));- }- return new Response(JSON.stringify({ retcode: 42, msg: "task not found" }));- }) as unknown as typeof globalThis.fetch;+ const { calls } = stubFetch((call) =>+ call.url.endsWith("/lite/create_bind_task")+ ? new Response(JSON.stringify({ retcode: 0, data: { task_id: "T1" } }))+ : new Response(JSON.stringify({ retcode: 42, msg: "task not found" })),+ );const transport = createQQScanTransport();expect(await transport.createBindTask("KEY")).toBe("T1");expect(calls[0]!.url).toBe("https://q.qq.com/lite/create_bind_task");- expect(calls[0]!.body).toEqual({ key: "KEY" });+ expect(JSON.parse(calls[0]!.body)).toEqual({ key: "KEY" });await expect(transport.pollBindResult("T1")).rejects.toThrow(/task not found \(retcode 42\)/);- expect(calls[1]!.body).toEqual({ task_id: "T1" });+ expect(JSON.parse(calls[1]!.body)).toEqual({ task_id: "T1" });});it("normalizes the completed payload, which arrives as a bare object", async () => {- globalThis.fetch = (async () =>- new Response(- JSON.stringify({- retcode: 0,- data: { status: 2, bot_appid: 102000042, bot_encrypt_secret: "AAAA", user_openid: "u1" },- }),- )) as unknown as typeof globalThis.fetch;+ stubFetch(+ () =>+ new Response(+ JSON.stringify({+ retcode: 0,+ data: {+ status: 2,+ bot_appid: 102000042,+ bot_encrypt_secret: "AAAA",+ user_openid: "u1",+ },+ }),+ ),+ );const res = await createQQScanTransport().pollBindResult("T1");expect(res.status).toBe("completed");// The App ID arrives as a NUMBER on the wire and is stored as text everywhere else.@@ -201,10 +202,7 @@ describe("createQQScanTransport", () => {[3, "expired"],[99, "pending"],] as const) {- globalThis.fetch = (async () =>- new Response(- JSON.stringify({ retcode: 0, data: { status: wire } }),- )) as unknown as typeof globalThis.fetch;+ stubFetch(() => new Response(JSON.stringify({ retcode: 0, data: { status: wire } })));expect((await createQQScanTransport().pollBindResult("T")).status).toBe(expected);}});@@ -347,7 +345,7 @@ describe("qq scan routes", () => {t = await createTestApp({ qqScanTransport: transport });const { cookie } = await provisionUser(t.app, "birder");api = apiClient(t.app, cookie);- t.deps.sessionsRepo.insert(sessionRowOf(SID, PROJECT));+ t.deps.sessionsRepo.insert(sessionRow(SID, { projectId: PROJECT }));});afterEach(async () => {await t.cleanup();@@ -424,7 +422,7 @@ describe("qq scan routes", () => {// The task id is not the authorization, and it is not a bearer handle either: the same// owner polling their OWN second Session with it gets nothing.- t.deps.sessionsRepo.insert(sessionRowOf(SID2, PROJECT));+ t.deps.sessionsRepo.insert(sessionRow(SID2, { projectId: PROJECT }));const mine = (await (await api.post(SCAN(SID), {})).json()) as QQScanStartResponse;const crossed = await api.post(`${SCAN(SID2)}/poll`, { taskId: mine.taskId });expect(crossed.status).toBe(404);@@ -480,7 +478,7 @@ describe("qq scan routes", () => {const start = (await (await api.post(SCAN(SID), {})).json()) as QQScanStartResponse;// Another Session holds the very account this scan is about to land on...- t.deps.sessionsRepo.insert(sessionRowOf(SID2, PROJECT));+ t.deps.sessionsRepo.insert(sessionRow(SID2, { projectId: PROJECT }));t.deps.messagingRepo.upsert({sessionId: SID2,channel: "qq",diff --git a/packages/server/test/messaging-qq-transport.test.ts b/packages/server/test/messaging-qq-transport.test.tsindex baf8064c..67cea385 100644--- a/packages/server/test/messaging-qq-transport.test.ts+++ b/packages/server/test/messaging-qq-transport.test.ts@@ -1,17 +1,30 @@/**- * The QQ production adapter — the half of the channel that talks to Tencent.+ * The QQ production adapter — the half of the channel that talks to Tencent, under the fake+ * transport messaging-qq.test.ts drives the connector with: the access-token cache, the+ * OpenAPI POST with its 401 replay and its two error families, and the gateway session's+ * handshake, heartbeat and reconnect protocol.*- * messaging-qq.test.ts drives the connector and its routes over a fake transport, which- * leaves everything under that seam unexercised: the access-token cache, the OpenAPI POST- * with its 401 replay and its two error families, and the gateway session's whole- * handshake / heartbeat / reconnect protocol. Those are where a platform failure actually- * reaches this product, so they get their own file.+ * - One token is bought and shared by a burst of sends, re-bought inside its refresh margin,+ * never cached forever on a missing TTL; a refused exchange names the platform's reason and+ * never the secret.+ * - A passive reply posts to its scene's endpoint as text, or as msg_type 2 with `content`+ * emptied; a refusal is a QQApiError (a 4xx one a defect, a 5xx one recovering) and a+ * transfer failure a recovering channel error; a 401 is replayed once on a fresh token; the+ * one failure this product can provoke leads with the rule.+ * - The gateway identifies with the one subscribed intent; resumes after a drop that keeps+ * the session and re-identifies after one that does not; forgets the session on+ * INVALID_SESSION and reconnects on RECONNECT (the asked-for reconnect routine, the refused+ * resume not); stops for good on a delisted or banned bot; types every close it reports and+ * calls only the self-clearing ones recovering (a routine close does not silence the outage+ * after it); drops a socket that stops acknowledging heartbeats or never handshakes, both+ * routine; judges the token exchange and the gateway lookup the way it judges a send; opens+ * nothing once closed.*- * Nothing here opens a socket or a connection. `globalThis.fetch` is stubbed the way- * messaging-telegram.test.ts stubs it, and the gateway runs on a fake socket passed through- * `QQTransportOpts.createSocket` — a test hook rather than a module mock, because this- * suite shares one module registry across files and `vi.mock` would leak into every later- * one (see vitest.config.ts).+ * Nothing here opens a socket: the global fetch is the suite's fetch fake, restored after+ * every case, and the gateway runs on a fake socket passed through+ * `QQTransportOpts.createSocket` — hooks rather than module mocks, because this suite shares+ * one module registry across files and `vi.mock` would leak into every later one (see+ * vitest.config.ts).*/import { afterEach, describe, expect, it, vi } from "vitest";import type {@@ -29,10 +42,16 @@ import {} from "../src/runtime/messaging/qq-api.js";import { MessagingChannelError } from "../src/runtime/messaging/connector.js";import { messagingErrorKind } from "../src/runtime/messaging/error-kind.js";+import { jsonResponse, stubFetch } from "./fixtures/fetch.js";+import type { FetchCall } from "./fixtures/fetch.js";import { waitFor } from "./helpers.js";const CREDS: QQCredentials = { appId: "102000001", appSecret: "qq-app-secret-ABCD-1234" };+afterEach(() => {+ vi.unstubAllGlobals();+});+/** Gateway opcodes, spelled out here so a test asserts the wire number rather than a name. */const OP_DISPATCH = 0;const OP_HEARTBEAT = 1;@@ -45,62 +64,24 @@ const OP_HEARTBEAT_ACK = 11;const settle = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));-function jsonResponse(body: unknown, status = 200): Response {- return new Response(JSON.stringify(body), {- status,- headers: { "content-type": "application/json" },- });-}--/** One recorded request against the stubbed fetch. */-interface Call {- url: string;- method: string;- body: string;- authorization: string;-}-/**- * Installs a fetch stub for the run of `body`, and hands it the calls it recorded.- *- * `answer` returns the response for one call; returning null means "the default", which is- * a valid token and a gateway URL — the two calls almost every test needs before it reaches- * the thing it is actually about.+ * Stands the suite's fetch fake in for the global fetch. `answer` decides a call's response;+ * returning null gives the default — a valid token and a gateway URL, the two calls almost+ * every test needs before it reaches the thing it is actually about.*/-async function withFetch<T>(- answer: (call: Call, index: number) => Response | null,- body: (calls: Call[]) => Promise<T>,-): Promise<T> {- const calls: Call[] = [];- const original = globalThis.fetch;- globalThis.fetch = (async (input: unknown, init?: RequestInit) => {- const headers = new Headers(init?.headers);- const call: Call = {- url: String(input),- method: init?.method ?? "GET",- body: typeof init?.body === "string" ? init.body : "",- authorization: headers.get("authorization") ?? "",- };- calls.push(call);- const answered = answer(call, calls.length - 1);+function stubQQ(answer: (call: FetchCall, index: number) => Response | null = () => null) {+ return stubFetch((call, index) => {+ const answered = answer(call, index);if (answered !== null) return answered;if (call.url.endsWith("/app/getAppAccessToken")) {- return jsonResponse({ access_token: `token-${calls.length}`, expires_in: 7200 });+ return jsonResponse({ access_token: `token-${index + 1}`, expires_in: 7200 });}if (call.url.endsWith("/gateway")) return jsonResponse({ url: "wss://gateway.example/ws" });if (call.url.includes("/v2/")) return jsonResponse({}, 200);throw new Error(`unexpected fetch: ${call.url}`);- }) as typeof fetch;- try {- return await body(calls);- } finally {- globalThis.fetch = original;- }+ }).calls;}-/** The default answer: let withFetch's own token/gateway responses stand. */-const defaults = (): null => null;-// ---------------------------------------------------------------------------// A fake socket: every frame in and out is the test's, and no I/O happens.// ---------------------------------------------------------------------------@@ -220,87 +201,75 @@ describe("the QQ access-token cache", () => {afterEach(() => vi.useRealTimers());it("buys one token and reuses it, whatever a burst of sends asks for", async () => {- await withFetch(defaults, async (calls) => {- const bot = createQQTransport().createClient(CREDS);- // Concurrent, so the cache is asked before the first exchange has resolved: without- // the in-flight collapse each of these buys its own token, and the endpoint answers- // 100001 Too many requests.- await Promise.all([bot.checkCredentials(), bot.checkCredentials(), bot.checkCredentials()]);- await bot.checkCredentials();- const exchanges = calls.filter((c) => c.url.endsWith("/app/getAppAccessToken"));- expect(exchanges).toHaveLength(1);- expect(exchanges[0]!.method).toBe("POST");- // The exchange is the only call that carries the secret, and it carries it as the- // platform's own field names.- expect(JSON.parse(exchanges[0]!.body)).toEqual({- appId: CREDS.appId,- clientSecret: CREDS.appSecret,- });+ const calls = stubQQ();+ const bot = createQQTransport().createClient(CREDS);+ // Concurrent, so the cache is asked before the first exchange has resolved: without+ // the in-flight collapse each of these buys its own token, and the endpoint answers+ // 100001 Too many requests.+ await Promise.all([bot.checkCredentials(), bot.checkCredentials(), bot.checkCredentials()]);+ await bot.checkCredentials();+ const exchanges = calls.filter((c) => c.url.endsWith("/app/getAppAccessToken"));+ expect(exchanges).toHaveLength(1);+ expect(exchanges[0]!.method).toBe("POST");+ // The exchange is the only call that carries the secret, and it carries it as the+ // platform's own field names.+ expect(JSON.parse(exchanges[0]!.body)).toEqual({+ appId: CREDS.appId,+ clientSecret: CREDS.appSecret,});});it("re-buys once the token is inside its refresh margin", async () => {vi.useFakeTimers({ toFake: ["Date"] });- await withFetch(- (call) =>- call.url.endsWith("/app/getAppAccessToken")- ? // Quoted, which is what the platform's own response example returns even though- // its field table calls the field a number.- jsonResponse({ access_token: `t${Date.now()}`, expires_in: "120" })- : null,- async (calls) => {- const bot = createQQTransport().createClient(CREDS);- await bot.checkCredentials();- // Inside the cached life (120s less the documented 60s overlap).- vi.setSystemTime(Date.now() + 30_000);- await bot.checkCredentials();- expect(calls).toHaveLength(1);- // Past it. The old token stays valid for the overlap, so refreshing here can never- // strand a request already in flight.- vi.setSystemTime(Date.now() + 40_000);- await bot.checkCredentials();- expect(calls).toHaveLength(2);- },+ const calls = stubQQ((call) =>+ call.url.endsWith("/app/getAppAccessToken")+ ? // Quoted, which is what the platform's own response example returns even though+ // its field table calls the field a number.+ jsonResponse({ access_token: `t${Date.now()}`, expires_in: "120" })+ : null,);+ const bot = createQQTransport().createClient(CREDS);+ await bot.checkCredentials();+ // Inside the cached life (120s less the documented 60s overlap).+ vi.setSystemTime(Date.now() + 30_000);+ await bot.checkCredentials();+ expect(calls).toHaveLength(1);+ // Past it. The old token stays valid for the overlap, so refreshing here can never+ // strand a request already in flight.+ vi.setSystemTime(Date.now() + 40_000);+ await bot.checkCredentials();+ expect(calls).toHaveLength(2);});it("caps a missing or nonsensical TTL at the platform's own ceiling instead of caching forever", async () => {vi.useFakeTimers({ toFake: ["Date"] });- await withFetch(- (call) =>- call.url.endsWith("/app/getAppAccessToken")- ? jsonResponse({ access_token: "no-ttl" })- : null,- async (calls) => {- const bot = createQQTransport().createClient(CREDS);- await bot.checkCredentials();- vi.setSystemTime(Date.now() + 7100 * 1000);- await bot.checkCredentials();- expect(calls).toHaveLength(1);- vi.setSystemTime(Date.now() + 100 * 1000);- await bot.checkCredentials();- expect(calls).toHaveLength(2);- },+ const calls = stubQQ((call) =>+ call.url.endsWith("/app/getAppAccessToken") ? jsonResponse({ access_token: "no-ttl" }) : null,);+ const bot = createQQTransport().createClient(CREDS);+ await bot.checkCredentials();+ vi.setSystemTime(Date.now() + 7100 * 1000);+ await bot.checkCredentials();+ expect(calls).toHaveLength(1);+ vi.setSystemTime(Date.now() + 100 * 1000);+ await bot.checkCredentials();+ expect(calls).toHaveLength(2);});it("reports a refused exchange with the platform's reason and never with the secret", async () => {- await withFetch(- (call) =>- call.url.endsWith("/app/getAppAccessToken")- ? jsonResponse({ code: 100007, message: "appid invalid" }, 400)- : null,- async () => {- const bot = createQQTransport().createClient(CREDS);- const err = await bot.checkCredentials().then(- () => "",- (e: unknown) => (e instanceof Error ? e.message : String(e)),- );- expect(err).toContain("appid invalid");- expect(err).toContain("100007");- expect(err).not.toContain(CREDS.appSecret);- },+ stubQQ((call) =>+ call.url.endsWith("/app/getAppAccessToken")+ ? jsonResponse({ code: 100007, message: "appid invalid" }, 400)+ : null,+ );+ const bot = createQQTransport().createClient(CREDS);+ const err = await bot.checkCredentials().then(+ () => "",+ (e: unknown) => (e instanceof Error ? e.message : String(e)),);+ expect(err).toContain("appid invalid");+ expect(err).toContain("100007");+ expect(err).not.toContain(CREDS.appSecret);});});@@ -314,39 +283,37 @@ describe("the QQ OpenAPI send", () => {};it("posts a passive reply to the scene's own endpoint, as plain text", async () => {- await withFetch(defaults, async (calls) => {- const bot = createQQTransport().createClient(CREDS);- await bot.sendMessage(args);- await bot.sendMessage({ ...args, kind: "group", openid: "group_openid_bbb" });- const sends = calls.filter((c) => c.url.includes("/v2/"));- expect(sends.map((c) => c.url)).toEqual([- `${QQ_API_BASE}/v2/users/user_openid_aaa/messages`,- `${QQ_API_BASE}/v2/groups/group_openid_bbb/messages`,- ]);- expect(sends[0]!.authorization).toBe("QQBot token-1");- expect(JSON.parse(sends[0]!.body)).toEqual({- content: "hello",- msg_type: 0,- msg_id: "msg_1",- msg_seq: 2,- });+ const calls = stubQQ();+ const bot = createQQTransport().createClient(CREDS);+ await bot.sendMessage(args);+ await bot.sendMessage({ ...args, kind: "group", openid: "group_openid_bbb" });+ const sends = calls.filter((c) => c.url.includes("/v2/"));+ expect(sends.map((c) => c.url)).toEqual([+ `${QQ_API_BASE}/v2/users/user_openid_aaa/messages`,+ `${QQ_API_BASE}/v2/groups/group_openid_bbb/messages`,+ ]);+ expect(sends[0]!.headers.get("authorization")).toBe("QQBot token-1");+ expect(JSON.parse(sends[0]!.body)).toEqual({+ content: "hello",+ msg_type: 0,+ msg_id: "msg_1",+ msg_seq: 2,});});it("posts a markdown reply as msg_type 2, with `content` emptied as the platform requires", async () => {- await withFetch(defaults, async (calls) => {- const bot = createQQTransport().createClient(CREDS);- await bot.sendMessage({ ...args, markdown: "## Head\n\n**bold**" });- const sent = calls.filter((c) => c.url.includes("/v2/"))[0]!;- // "传了 markdown 后此字段必须为空" — a payload carrying both is rejected, so `content`- // goes out empty rather than merely ignored. The deprecated template fields are absent.- expect(JSON.parse(sent.body)).toEqual({- content: "",- msg_type: 2,- markdown: { content: "## Head\n\n**bold**" },- msg_id: "msg_1",- msg_seq: 2,- });+ const calls = stubQQ();+ const bot = createQQTransport().createClient(CREDS);+ await bot.sendMessage({ ...args, markdown: "## Head\n\n**bold**" });+ const sent = calls.filter((c) => c.url.includes("/v2/"))[0]!;+ // "传了 markdown 后此字段必须为空" — a payload carrying both is rejected, so `content`+ // goes out empty rather than merely ignored. The deprecated template fields are absent.+ expect(JSON.parse(sent.body)).toEqual({+ content: "",+ msg_type: 2,+ markdown: { content: "## Head\n\n**bold**" },+ msg_id: "msg_1",+ msg_seq: 2,});});@@ -354,200 +321,186 @@ describe("the QQ OpenAPI send", () => {// The distinction the markdown-to-text fallback turns on: the platform answered and// delivered nothing, so another form of the same message is safe to send — where a// request that never completed may already have been delivered.- await withFetch(- (call) => (call.url.includes("/v2/") ? jsonResponse({ err_code: 40054001 }, 400) : null),- async () => {- const bot = createQQTransport().createClient(CREDS);- const err = await bot.sendMessage(args).catch((e: unknown) => e);- expect(err).toBeInstanceOf(QQApiError);- expect((err as QQApiError).code).toBe(40054001);- // A 4xx refusal meets the same no next time: the error table keeps it a defect.- expect((err as QQApiError).recovers).toBe(false);- expect(messagingErrorKind(err, "messaging_send_failed")).toBe("unexpected");- },- );- await withFetch(- (call) => (call.url.includes("/v2/") ? jsonResponse({ err_code: 22009 }, 503) : null),- async () => {- const bot = createQQTransport().createClient(CREDS);- const err = await bot.sendMessage(args).catch((e: unknown) => e);- // The platform's own fault, whatever its code says: the next send goes through.- expect(err).toBeInstanceOf(QQApiError);- expect(messagingErrorKind(err, "messaging_send_failed")).toBe("expected");- },- );- await withFetch(- (call) => {- if (!call.url.includes("/v2/")) return null;- throw new TypeError("fetch failed");- },- async () => {- const bot = createQQTransport().createClient(CREDS);- const err = await bot.sendMessage(args).catch((e: unknown) => e);- expect(err).toBeInstanceOf(MessagingChannelError);- expect(err).not.toBeInstanceOf(QQApiError);- expect((err as MessagingChannelError).recovers).toBe(true);- expect(messagingErrorKind(err, "messaging_send_failed")).toBe("expected");- },+ const sendError = () =>+ createQQTransport()+ .createClient(CREDS)+ .sendMessage(args)+ .catch((e: unknown) => e);++ stubQQ((call) =>+ call.url.includes("/v2/") ? jsonResponse({ err_code: 40054001 }, 400) : null,);+ const refused = await sendError();+ expect(refused).toBeInstanceOf(QQApiError);+ expect((refused as QQApiError).code).toBe(40054001);+ // A 4xx refusal meets the same no next time: the error table keeps it a defect.+ expect((refused as QQApiError).recovers).toBe(false);+ expect(messagingErrorKind(refused, "messaging_send_failed")).toBe("unexpected");++ stubQQ((call) => (call.url.includes("/v2/") ? jsonResponse({ err_code: 22009 }, 503) : null));+ const faulted = await sendError();+ // The platform's own fault, whatever its code says: the next send goes through.+ expect(faulted).toBeInstanceOf(QQApiError);+ expect(messagingErrorKind(faulted, "messaging_send_failed")).toBe("expected");++ stubQQ((call) => {+ if (!call.url.includes("/v2/")) return null;+ throw new TypeError("fetch failed");+ });+ const lost = await sendError();+ expect(lost).toBeInstanceOf(MessagingChannelError);+ expect(lost).not.toBeInstanceOf(QQApiError);+ expect((lost as MessagingChannelError).recovers).toBe(true);+ expect(messagingErrorKind(lost, "messaging_send_failed")).toBe("expected");});it("replays a 401 once on a fresh token, and gives up rather than looping", async () => {// A secret rotated in the console, or a clock further off than the refresh margin// covers: the cached token died before its stated expiry.- await withFetch(- (call) => (call.url.includes("/v2/") ? jsonResponse({ code: 11244 }, 401) : null),- async (calls) => {- const bot = createQQTransport().createClient(CREDS);- await expect(bot.sendMessage(args)).rejects.toThrow(/Message send failed/);- expect(calls.map((c) => c.url.replace(QQ_API_BASE, ""))).toEqual([- "/app/getAppAccessToken",- "/v2/users/user_openid_aaa/messages",- // The invalidated cache buys a new token, and the send is tried once more...- "/app/getAppAccessToken",- "/v2/users/user_openid_aaa/messages",- ]);- },+ const calls = stubQQ((call) =>+ call.url.includes("/v2/") ? jsonResponse({ code: 11244 }, 401) : null,);+ const bot = createQQTransport().createClient(CREDS);+ await expect(bot.sendMessage(args)).rejects.toThrow(/Message send failed/);+ expect(calls.map((c) => c.url.replace(QQ_API_BASE, ""))).toEqual([+ "/app/getAppAccessToken",+ "/v2/users/user_openid_aaa/messages",+ // The invalidated cache buys a new token, and the send is tried once more...+ "/app/getAppAccessToken",+ "/v2/users/user_openid_aaa/messages",+ ]);});it("leads the one failure this product can provoke with the rule behind it", async () => {- await withFetch(- (call) =>- call.url.includes("/v2/")- ? // Both families in one body, which is where the precedence matters: the OpenAPI- // answers `err_code` and the token endpoint answers `code`.- jsonResponse({ err_code: 40034128, code: 500, message: "msg over limit" }, 400)- : null,- async () => {- const bot = createQQTransport().createClient(CREDS);- const err = await bot.sendMessage(args).then(- () => "",- (e: unknown) => (e instanceof Error ? e.message : String(e)),- );- expect(err).toContain("only a few replies");- expect(err).toContain("40034128");- expect(err).not.toContain("500");- },+ stubQQ((call) =>+ call.url.includes("/v2/")+ ? // Both families in one body, which is where the precedence matters: the OpenAPI+ // answers `err_code` and the token endpoint answers `code`.+ jsonResponse({ err_code: 40034128, code: 500, message: "msg over limit" }, 400)+ : null,);+ const bot = createQQTransport().createClient(CREDS);+ const err = await bot.sendMessage(args).then(+ () => "",+ (e: unknown) => (e instanceof Error ? e.message : String(e)),+ );+ expect(err).toContain("only a few replies");+ expect(err).toContain("40034128");+ expect(err).not.toContain("500");});});describe("the QQ gateway session", () => {it("identifies with the one subscribed intent and reports the handshake", async () => {- await withFetch(defaults, async (calls) => {- const h = harnessOf();- const conn = await h.open();- try {- const socket = h.sockets[0]!;- expect(socket.url).toBe("wss://gateway.example/ws");- socket.deliver({ op: OP_HELLO, d: { heartbeat_interval: 45_000 } });- expect(socket.frames(OP_IDENTIFY)[0]).toMatchObject({- op: OP_IDENTIFY,- d: { token: "QQBot token-1", intents: QQ_INTENT_GROUP_AND_C2C, shard: [0, 1] },- });- expect(h.readies).toBe(0); // HELLO is not a handshake; READY is- socket.deliver({ op: OP_DISPATCH, t: "READY", s: 1, d: { session_id: "gw-1" } });- expect(h.readies).toBe(1);-- socket.deliver({- op: OP_DISPATCH,- t: "C2C_MESSAGE_CREATE",- s: 2,- d: { id: "m1", content: " status?", author: { user_openid: "u1" } },- });- expect(h.inbound).toEqual([- { kind: "c2c", openid: "u1", messageId: "m1", content: "status?", senderOpenid: "u1" },- ]);- // `GET /gateway` is rate limited to 2 requests a minute; one lookup per session.- expect(calls.filter((c) => c.url.endsWith("/gateway"))).toHaveLength(1);- } finally {- conn.close();- }- });+ const calls = stubQQ();+ const h = harnessOf();+ const conn = await h.open();+ try {+ const socket = h.sockets[0]!;+ expect(socket.url).toBe("wss://gateway.example/ws");+ socket.deliver({ op: OP_HELLO, d: { heartbeat_interval: 45_000 } });+ expect(socket.frames(OP_IDENTIFY)[0]).toMatchObject({+ op: OP_IDENTIFY,+ d: { token: "QQBot token-1", intents: QQ_INTENT_GROUP_AND_C2C, shard: [0, 1] },+ });+ expect(h.readies).toBe(0); // HELLO is not a handshake; READY is+ socket.deliver({ op: OP_DISPATCH, t: "READY", s: 1, d: { session_id: "gw-1" } });+ expect(h.readies).toBe(1);++ socket.deliver({+ op: OP_DISPATCH,+ t: "C2C_MESSAGE_CREATE",+ s: 2,+ d: { id: "m1", content: " status?", author: { user_openid: "u1" } },+ });+ expect(h.inbound).toEqual([+ { kind: "c2c", openid: "u1", messageId: "m1", content: "status?", senderOpenid: "u1" },+ ]);+ // `GET /gateway` is rate limited to 2 requests a minute; one lookup per session.+ expect(calls.filter((c) => c.url.endsWith("/gateway"))).toHaveLength(1);+ } finally {+ conn.close();+ }});it("resumes after a drop that keeps the session, and re-identifies after one that does not", async () => {- await withFetch(defaults, async () => {- const h = harnessOf();- const conn = await h.open();- try {- handshake(h.sockets[0]!, "gw-1");- // 4009 is the one drop the platform keeps resumable.- h.sockets[0]!.drop(4009);- await waitFor(() => h.sockets.length === 2);- h.sockets[1]!.deliver({ op: OP_HELLO, d: { heartbeat_interval: 45_000 } });- expect(h.sockets[1]!.frames(OP_RESUME)[0]).toMatchObject({- d: { session_id: "gw-1", seq: 1 },- });- h.sockets[1]!.deliver({ op: OP_DISPATCH, t: "RESUMED", s: 2 });- expect(h.readies).toBe(2);-- // 4006 says the handle is dead: the next handshake must start over.- h.sockets[1]!.drop(4006);- await waitFor(() => h.sockets.length === 3);- h.sockets[2]!.deliver({ op: OP_HELLO, d: { heartbeat_interval: 45_000 } });- expect(h.sockets[2]!.frames(OP_RESUME)).toHaveLength(0);- expect(h.sockets[2]!.frames(OP_IDENTIFY)).toHaveLength(1);- // One report per OUTAGE, and there were two: a completed handshake ends the first- // one, so the drop after it is news rather than a repeat.- expect(h.errors).toHaveLength(2);- } finally {- conn.close();- }- });+ stubQQ();+ const h = harnessOf();+ const conn = await h.open();+ try {+ handshake(h.sockets[0]!, "gw-1");+ // 4009 is the one drop the platform keeps resumable.+ h.sockets[0]!.drop(4009);+ await waitFor(() => h.sockets.length === 2);+ h.sockets[1]!.deliver({ op: OP_HELLO, d: { heartbeat_interval: 45_000 } });+ expect(h.sockets[1]!.frames(OP_RESUME)[0]).toMatchObject({+ d: { session_id: "gw-1", seq: 1 },+ });+ h.sockets[1]!.deliver({ op: OP_DISPATCH, t: "RESUMED", s: 2 });+ expect(h.readies).toBe(2);++ // 4006 says the handle is dead: the next handshake must start over.+ h.sockets[1]!.drop(4006);+ await waitFor(() => h.sockets.length === 3);+ h.sockets[2]!.deliver({ op: OP_HELLO, d: { heartbeat_interval: 45_000 } });+ expect(h.sockets[2]!.frames(OP_RESUME)).toHaveLength(0);+ expect(h.sockets[2]!.frames(OP_IDENTIFY)).toHaveLength(1);+ // One report per OUTAGE, and there were two: a completed handshake ends the first+ // one, so the drop after it is news rather than a repeat.+ expect(h.errors).toHaveLength(2);+ } finally {+ conn.close();+ }});it("forgets the session on INVALID_SESSION and reconnects on RECONNECT", async () => {- await withFetch(defaults, async () => {- const h = harnessOf();- const conn = await h.open();- try {- handshake(h.sockets[0]!, "gw-1");- // Politely asked to reconnect: the session stays resumable.- h.sockets[0]!.deliver({ op: OP_RECONNECT });- expect(h.sockets[0]!.closes).toBe(1);- h.sockets[0]!.drop(1000);- await waitFor(() => h.sockets.length === 2);- h.sockets[1]!.deliver({ op: OP_HELLO, d: { heartbeat_interval: 45_000 } });- expect(h.sockets[1]!.frames(OP_RESUME)).toHaveLength(1);-- // The resume was refused: the handle goes.- h.sockets[1]!.deliver({ op: OP_INVALID_SESSION });- h.sockets[1]!.drop(1000);- await waitFor(() => h.sockets.length === 3);- h.sockets[2]!.deliver({ op: OP_HELLO, d: { heartbeat_interval: 45_000 } });- expect(h.sockets[2]!.frames(OP_IDENTIFY)).toHaveLength(1);-- // The two closes look alike on the wire, so their verdicts come from the session: the- // reconnect the platform asked for is routine, and the refused resume — which loses- // whatever arrived in the gap — is not, and is reported although the same outage has- // already reported the routine one.- expect(h.errors.map((err) => messagingErrorKind(err, "messaging_connect_failed"))).toEqual([- "expected",- "unexpected",- ]);- } finally {- conn.close();- }- });+ stubQQ();+ const h = harnessOf();+ const conn = await h.open();+ try {+ handshake(h.sockets[0]!, "gw-1");+ // Politely asked to reconnect: the session stays resumable.+ h.sockets[0]!.deliver({ op: OP_RECONNECT });+ expect(h.sockets[0]!.closes).toBe(1);+ h.sockets[0]!.drop(1000);+ await waitFor(() => h.sockets.length === 2);+ h.sockets[1]!.deliver({ op: OP_HELLO, d: { heartbeat_interval: 45_000 } });+ expect(h.sockets[1]!.frames(OP_RESUME)).toHaveLength(1);++ // The resume was refused: the handle goes.+ h.sockets[1]!.deliver({ op: OP_INVALID_SESSION });+ h.sockets[1]!.drop(1000);+ await waitFor(() => h.sockets.length === 3);+ h.sockets[2]!.deliver({ op: OP_HELLO, d: { heartbeat_interval: 45_000 } });+ expect(h.sockets[2]!.frames(OP_IDENTIFY)).toHaveLength(1);++ // The two closes look alike on the wire, so their verdicts come from the session: the+ // reconnect the platform asked for is routine, and the refused resume — which loses+ // whatever arrived in the gap — is not, and is reported although the same outage has+ // already reported the routine one.+ expect(h.errors.map((err) => messagingErrorKind(err, "messaging_connect_failed"))).toEqual([+ "expected",+ "unexpected",+ ]);+ } finally {+ conn.close();+ }});it("stops for good on a delisted or banned bot rather than retrying forever", async () => {- await withFetch(defaults, async () => {- const h = harnessOf();- const conn = await h.open();- try {- handshake(h.sockets[0]!, "gw-1");- h.sockets[0]!.drop(4914);- await settle(40); // several backoff rounds at 5ms, had it retried- expect(h.sockets).toHaveLength(1);- expect(h.errors).toHaveLength(1);- expect(String(h.errors[0])).toContain("4914");- } finally {- conn.close();- }- });+ stubQQ();+ const h = harnessOf();+ const conn = await h.open();+ try {+ handshake(h.sockets[0]!, "gw-1");+ h.sockets[0]!.drop(4914);+ await settle(40); // several backoff rounds at 5ms, had it retried+ expect(h.sockets).toHaveLength(1);+ expect(h.errors).toHaveLength(1);+ expect(String(h.errors[0])).toContain("4914");+ } finally {+ conn.close();+ }});it("types every close it reports, and calls only the self-clearing ones recovering", async () => {@@ -557,21 +510,20 @@ describe("the QQ gateway session", () => {// boolean somebody else typed in.const verdictOf = async (code: number): Promise<MessagingConnectionClosedError> => {let closed: MessagingConnectionClosedError | undefined;- await withFetch(defaults, async () => {- const h = harnessOf();- const conn = await h.open();- try {- handshake(h.sockets[0]!, "gw-1");- h.sockets[0]!.drop(code);- await waitFor(() => h.errors.length > 0);- const err = h.errors[0];- expect(err).toBeInstanceOf(MessagingConnectionClosedError);- closed = err as MessagingConnectionClosedError;- expect(closed.closeCode).toBe(code);- } finally {- conn.close();- }- });+ stubQQ();+ const h = harnessOf();+ const conn = await h.open();+ try {+ handshake(h.sockets[0]!, "gw-1");+ h.sockets[0]!.drop(code);+ await waitFor(() => h.errors.length > 0);+ const err = h.errors[0];+ expect(err).toBeInstanceOf(MessagingConnectionClosedError);+ closed = err as MessagingConnectionClosedError;+ expect(closed.closeCode).toBe(code);+ } finally {+ conn.close();+ }return closed!;};@@ -605,116 +557,112 @@ describe("the QQ gateway session", () => {// filed `expected` — so if it kept the slot, a socket the platform expires at 4009 followed// by an auth refusal forever would leave the dashboard reading zero defects for a binding// that is down until someone changes a credential.- await withFetch(defaults, async () => {- const h = harnessOf();- const conn = await h.open();- try {- handshake(h.sockets[0]!, "gw-1");- h.sockets[0]!.drop(4009);- await waitFor(() => h.errors.length === 1);- expect((h.errors[0] as MessagingConnectionClosedError).recovers).toBe(true);-- // The retry meets a refusal that no reconnect clears: it gets its own record.- await waitFor(() => h.sockets.length === 2);- h.sockets[1]!.drop(4004);- await waitFor(() => h.errors.length === 2);- expect((h.errors[1] as MessagingConnectionClosedError).recovers).toBe(false);-- // And there it stops: the outage has said what it needed to say.- await waitFor(() => h.sockets.length === 3);- h.sockets[2]!.drop(4004);- await settle(40);- expect(h.errors).toHaveLength(2);- } finally {- conn.close();- }- });+ stubQQ();+ const h = harnessOf();+ const conn = await h.open();+ try {+ handshake(h.sockets[0]!, "gw-1");+ h.sockets[0]!.drop(4009);+ await waitFor(() => h.errors.length === 1);+ expect((h.errors[0] as MessagingConnectionClosedError).recovers).toBe(true);++ // The retry meets a refusal that no reconnect clears: it gets its own record.+ await waitFor(() => h.sockets.length === 2);+ h.sockets[1]!.drop(4004);+ await waitFor(() => h.errors.length === 2);+ expect((h.errors[1] as MessagingConnectionClosedError).recovers).toBe(false);++ // And there it stops: the outage has said what it needed to say.+ await waitFor(() => h.sockets.length === 3);+ h.sockets[2]!.drop(4004);+ await settle(40);+ expect(h.errors).toHaveLength(2);+ } finally {+ conn.close();+ }});it("what the socket reports is what the recorder classifies, with no help in between", async () => {// The two halves are each tested against this class; this is the seam. `messagingErrorKind`// is handed the object the gateway raised, exactly as bridge.ts hands it over — so wrapping// or re-throwing the error anywhere on that path fails here.- await withFetch(defaults, async () => {- const h = harnessOf();- const conn = await h.open();- try {- handshake(h.sockets[0]!, "gw-1");- h.sockets[0]!.drop(4009);- await waitFor(() => h.errors.length === 1);- expect(messagingErrorKind(h.errors[0], "messaging_connect_failed")).toBe("expected");- } finally {- conn.close();- }- });+ stubQQ();+ const h = harnessOf();+ const conn = await h.open();+ try {+ handshake(h.sockets[0]!, "gw-1");+ h.sockets[0]!.drop(4009);+ await waitFor(() => h.errors.length === 1);+ expect(messagingErrorKind(h.errors[0], "messaging_connect_failed")).toBe("expected");+ } finally {+ conn.close();+ }});it("drops a socket that stops acknowledging heartbeats", async () => {- await withFetch(defaults, async () => {- const h = harnessOf();- const conn = await h.open();- try {- const socket = h.sockets[0]!;- handshake(socket, "gw-1", 20);- // Healthy first: a socket that answers keeps its heartbeat going.- await settle(70);- expect(socket.frames(OP_HEARTBEAT).length).toBeGreaterThanOrEqual(2);- expect(socket.closes).toBe(0);-- // Now the far end goes away without a FIN — a NAT or proxy drop. `readyState`- // stays OPEN, so nothing but this watchdog can notice.- socket.autoAck = false;- await waitFor(() => h.sockets.length === 2);- expect(socket.closes).toBe(1);- expect(h.errors).toHaveLength(1);- expect(String(h.errors[0])).toContain("heartbeat");- // A dead pipe the next socket replaces: routine, whatever the retries meet next.- expect(h.errors[0]).toBeInstanceOf(MessagingChannelError);- expect(messagingErrorKind(h.errors[0], "messaging_connect_failed")).toBe("expected");- } finally {- conn.close();- }- });+ stubQQ();+ const h = harnessOf();+ const conn = await h.open();+ try {+ const socket = h.sockets[0]!;+ handshake(socket, "gw-1", 20);+ // Healthy first: a socket that answers keeps its heartbeat going.+ await settle(70);+ expect(socket.frames(OP_HEARTBEAT).length).toBeGreaterThanOrEqual(2);+ expect(socket.closes).toBe(0);++ // Now the far end goes away without a FIN — a NAT or proxy drop. `readyState`+ // stays OPEN, so nothing but this watchdog can notice.+ socket.autoAck = false;+ await waitFor(() => h.sockets.length === 2);+ expect(socket.closes).toBe(1);+ expect(h.errors).toHaveLength(1);+ expect(String(h.errors[0])).toContain("heartbeat");+ // A dead pipe the next socket replaces: routine, whatever the retries meet next.+ expect(h.errors[0]).toBeInstanceOf(MessagingChannelError);+ expect(messagingErrorKind(h.errors[0], "messaging_connect_failed")).toBe("expected");+ } finally {+ conn.close();+ }});it("drops a socket that opened and then never handshook", async () => {- await withFetch(defaults, async () => {- const h = harnessOf({ handshakeTimeoutMs: 30 });- const conn = await h.open();- try {- // Not one frame: the shape of a proxy that accepted the upgrade and blackholed- // everything after it. No HELLO means no heartbeat either, so the deadline on the- // handshake is the only thing covering this.- await waitFor(() => h.sockets.length === 2);- expect(h.sockets[0]!.closes).toBe(1);- expect(h.errors).toHaveLength(1);- expect(String(h.errors[0])).toContain("handshake");- expect(messagingErrorKind(h.errors[0], "messaging_connect_failed")).toBe("expected");- } finally {- conn.close();- }- });+ stubQQ();+ const h = harnessOf({ handshakeTimeoutMs: 30 });+ const conn = await h.open();+ try {+ // Not one frame: the shape of a proxy that accepted the upgrade and blackholed+ // everything after it. No HELLO means no heartbeat either, so the deadline on the+ // handshake is the only thing covering this.+ await waitFor(() => h.sockets.length === 2);+ expect(h.sockets[0]!.closes).toBe(1);+ expect(h.errors).toHaveLength(1);+ expect(String(h.errors[0])).toContain("handshake");+ expect(messagingErrorKind(h.errors[0], "messaging_connect_failed")).toBe("expected");+ } finally {+ conn.close();+ }});it("judges the two calls in front of the socket the way it judges a send", async () => {// The token exchange and the gateway lookup are plain HTTPS: a request that never arrived// may go through next time, and a refusal is judged by its status.- const firstError = (answer: (call: Call) => Response | null): Promise<unknown> =>- withFetch(answer, async () => {- const errors: unknown[] = [];- const conn = await createQQTransport({ gatewayRetryMs: () => 5 }).openGateway(CREDS, {- onMessage: () => {},- onError: (err) => {- errors.push(err);- },- });- try {- await waitFor(() => errors.length > 0);- return errors[0];- } finally {- conn.close();- }+ const firstError = async (answer: (call: FetchCall) => Response | null): Promise<unknown> => {+ stubQQ(answer);+ const errors: unknown[] = [];+ const conn = await createQQTransport({ gatewayRetryMs: () => 5 }).openGateway(CREDS, {+ onMessage: () => {},+ onError: (err) => {+ errors.push(err);+ },});+ try {+ await waitFor(() => errors.length > 0);+ return errors[0];+ } finally {+ conn.close();+ }+ };const kindOf = (err: unknown) => messagingErrorKind(err, "messaging_connect_failed");expect(@@ -753,14 +701,13 @@ describe("the QQ gateway session", () => {});it("stops opening sockets once the connection is closed", async () => {- await withFetch(defaults, async () => {- const h = harnessOf({ handshakeTimeoutMs: 20 });- const conn = await h.open();- handshake(h.sockets[0]!, "gw-1");- conn.close();- expect(h.sockets[0]!.closes).toBe(1);- await settle(60);- expect(h.sockets).toHaveLength(1);- });+ stubQQ();+ const h = harnessOf({ handshakeTimeoutMs: 20 });+ const conn = await h.open();+ handshake(h.sockets[0]!, "gw-1");+ conn.close();+ expect(h.sockets[0]!.closes).toBe(1);+ await settle(60);+ expect(h.sockets).toHaveLength(1);});});diff --git a/packages/server/test/messaging-qq.test.ts b/packages/server/test/messaging-qq.test.tsindex 72ed83fe..cedbadea 100644--- a/packages/server/test/messaging-qq.test.ts+++ b/packages/server/test/messaging-qq.test.ts@@ -1,33 +1,48 @@/**- * QQ messaging tests — the third channel's mirror of messaging.test.ts, and the proof the- * connector seam survives a platform that will not let a bot speak freely.+ * QQ messaging — the third channel's mirror of messaging.test.ts over a fake transport, and+ * the proof the connector seam survives a platform that will not let a bot speak freely. No+ * test opens a socket.*- * Two halves. The ordinary one repeats what the other channels already pin, because the- * route wiring is per-channel even where the behaviour is not: secret masking and- * keep-on-blank, the App ID as the account identity and the enable-time 409 it collides- * on, the save/enable split, the channel-agnostic GET, the credential probe.+ * The ordinary half repeats what the other channels pin, because the route wiring is+ * per-channel even where the behaviour is not:+ * - A stored config narrows; a chat id round-trips its scene and openid; dispatches are read+ * from the two subscribed events (the @bot prefix taken at the platform's word, everything+ * else dropped).+ * - A PUT saves the pair only (secret masked, the App ID as the account, disabled); POST /state+ * owns the gateway and a re-save while enabled restarts it; saving never collides, enabling+ * does, and a save cannot carry an enabled connection onto another Session's bot; clearing+ * the secret needs the connection off; the probe is the token exchange; GET /messaging lists+ * qq beside the others.+ * - Inbound text starts an ordinary Task and is answered; a redelivered message is a no-op; a+ * message with no text gets the notice as a reply to it. Formatting renders what QQ has,+ * plain when renderMarkdown is off, falling back to plain at the cost of one slot when+ * refused — but a refusal not about the body is not retried.*- * The half that only exists here is the PASSIVE REPLY BUDGET. QQ accepts a fixed, small- * number of replies to one inbound message and has no push this product may use, so the- * connector coalesces a run's messages to fit. These tests are the ones that matter:- * exactly four sends for a run that completed six messages, the last carrying the- * remainder; `msg_seq` increasing without repeating; the approval notice taking the- * reserved slot rather than being lost behind it; one-message-per-line clamped to the- * budget instead of the channel-neutral 20; a reply's files, which QQ cannot take, filed as one- * error record without spending a slot; and a send with nothing to reply to failing loudly- * rather than pretending. No test opens a socket.+ * The half that only exists here is the PASSIVE REPLY BUDGET: QQ accepts a small fixed number+ * of replies to one inbound message and has no push this product may use.+ * - A run of six messages reaches QQ as four, the last carrying the remainder, on one anchor+ * with an increasing, never repeating msg_seq; a group gets its larger budget.+ * - The approval notice takes the reserved slot rather than being lost behind it;+ * one-message-per-line is clamped to the budget.+ * - A reply's files, which QQ cannot take, are one expected error record and spend no slot.+ * - A send with nothing to reply to fails loudly; the test message needs a received message and+ * rides its passive reply; the client refuses a file with a reason.+ * - The ledger: a redelivered msg_id is not fresh budget; closing the connection drops a+ * withheld tail; a failed flush keeps its text for the next message's budget; a chat quiet+ * past the reply window refuses rather than restarting its sequence.*/import fs from "node:fs/promises";import path from "node:path";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { approvalDecision, assistantText, toolCall } from "@prismshadow/penguin-core";import type { ApproveFn, OmniMessage, TextPayload } from "@prismshadow/penguin-core";+import { wire } from "@prismshadow/penguin-core/kernel";import type {MessagingBindingsResponse,QQBindingResponse,QQTestResponse,} from "../src/api/types.js";-import type { SessionRow } from "../src/db/repos/sessions.js";+import { ProjectsRepo } from "../src/db/repos/projects.js";import type { RuntimeSession } from "../src/runtime/session-manager.js";import {MESSAGING_APPROVAL_NOTICE,@@ -55,11 +70,11 @@ import {qqChatIdOf,qqConfigOf,} from "../src/runtime/messaging/qq-connector.js";+import { forwardingTo } from "./fixtures/forwarding.js";+import { fakeSession, sessionRow, uniqueSessionId } from "./fixtures/session.js";import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";import type { TestApp } from "./helpers.js";-const SID = "session-2026-08-27-10-00-00-q9000001";-const SID2 = "session-2026-08-27-10-00-01-q9000002";const BASE = (sid: string) => `/api/sessions/${sid}/messaging/qq`;const APP_ID = "102000001";const APP_SECRET = "qq-app-secret-ABCD-1234";@@ -167,46 +182,26 @@ function echoFakeSession(runs: TextPayload[][],reply = "Reply text",): RuntimeSession {- return {- sessionId,- toolPermission: () => "rw",- generateTitle: async () => ({ title: null, usage: null }),- compactability: () => "ok" as const,- steer: () => false,- skipReconnectWait: () => false,+ return fakeSession(sessionId, {async *run(input: OmniMessage[]) {runs.push(input.map((m) => m.payload as TextPayload));yield assistantText(reply);},- async *compact() {},- };+ });}/** Fake Session completing several assistant messages in ONE run — the budget's whole point. */function multiMessageFakeSession(sessionId: string, texts: readonly string[]): RuntimeSession {- return {- sessionId,- toolPermission: () => "rw",- generateTitle: async () => ({ title: null, usage: null }),- compactability: () => "ok" as const,- steer: () => false,- skipReconnectWait: () => false,+ return fakeSession(sessionId, {async *run() {for (const text of texts) yield assistantText(text);},- async *compact() {},- };+ });}/** Fake Session that completes `texts` and THEN parks on an approval (drives approval_request). */function parkingAfterMessagesSession(sessionId: string, texts: readonly string[]): RuntimeSession {- return {- sessionId,- toolPermission: () => "rw",- generateTitle: async () => ({ title: null, usage: null }),- compactability: () => "ok" as const,- steer: () => false,- skipReconnectWait: () => false,+ return fakeSession(sessionId, {async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {for (const text of texts) yield assistantText(text);const tc = toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-qq" });@@ -214,23 +209,7 @@ function parkingAfterMessagesSession(sessionId: string, texts: readonly string[]const decision = await opts.approve(tc);yield approvalDecision(decision, "tc-qq");},- async *compact() {},- };-}--function sessionRowOf(sessionId: string, projectId: string): SessionRow {- return {- sessionId,- projectId,- agentId: "default_agent",- provider: "custom",- modelId: "m1",- workspace: "/tmp/w",- approvalMode: "allow-all",- title: null,- createdAt: new Date().toISOString(),- lastActiveAt: new Date().toISOString(),- };+ });}// ---------------------------------------------------------------------------@@ -358,8 +337,17 @@ describe("qq binding routes and the passive reply budget", () => {let t: TestApp;let api: ReturnType<typeof apiClient>;let fake: FakeQQTransport;- let projectId: string;let runs: TextPayload[][];+ /**+ * The case's Project and its two Sessions, fresh per case: the app is the describe's, a+ * binding, a gateway and a status belong to their Session, and the error log dedupes and+ * reads per Project. The Project is birder's row alone — every Session here is a fake, so+ * nothing opens a default Agent's tree.+ */+ let projectId: string;+ let SID: string;+ let SID2: string;+ let cases = 0;/** Save the credentials, then flip the toggle on and wait for the gateway handshake. */const bindEnabled = async (sid: string, appId = APP_ID, put: Record<string, unknown> = {}) => {@@ -368,19 +356,34 @@ describe("qq binding routes and the passive reply budget", () => {await waitFor(() => t.deps.messaging.statusOf(sid, "qq").state === "connected");};- beforeEach(async () => {- fake = new FakeQQTransport();- t = await createTestApp({ qqTransport: fake, qqTailFlushMs: TAIL_MS });+ beforeAll(async () => {+ t = await createTestApp({ qqTransport: forwardingTo(() => fake), qqTailFlushMs: TAIL_MS });const { cookie } = await provisionUser(t.app, "birder");api = apiClient(t.app, cookie);- projectId = "birder-default_project";+ });+ afterAll(async () => {+ await t.cleanup();+ });+ beforeEach(() => {+ fake = new FakeQQTransport();runs = [];- const row = sessionRowOf(SID, projectId);+ cases += 1;+ projectId = `birder-case-${cases}`;+ wire(ProjectsRepo, { db: t.deps.db }).insert({+ projectId,+ ownerUserId: "birder",+ createdAt: new Date().toISOString(),+ });+ SID = uniqueSessionId();+ SID2 = uniqueSessionId();+ const row = sessionRow(SID, { projectId });t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row, echoFakeSession(SID, runs));});- afterEach(async () => {- await t.cleanup();+ afterEach(() => {+ // What the case bound goes with it, gateway and all, and so does the error log it wrote.+ for (const row of t.deps.messagingRepo.listAll()) t.deps.messaging.unbindSession(row.sessionId);+ t.deps.db.prepare("DELETE FROM error_records").run();});// —— Routes ——————————————————————————————————————————————————————————————@@ -430,7 +433,7 @@ describe("qq binding routes and the passive reply budget", () => {});it("the account is the App ID: saving never collides, enabling does", async () => {- t.deps.sessionsRepo.insert(sessionRowOf(SID2, projectId));+ t.deps.sessionsRepo.insert(sessionRow(SID2, { projectId }));await bindEnabled(SID);expect((await api.put(BASE(SID2), { appId: APP_ID, appSecret: "other-secret-9999" })).status,@@ -453,7 +456,7 @@ describe("qq binding routes and the passive reply budget", () => {// an App ID somebody else has enabled would stand two gateways on one bot's single// event stream without ever passing the gate above.const other = "102000002";- t.deps.sessionsRepo.insert(sessionRowOf(SID2, projectId));+ t.deps.sessionsRepo.insert(sessionRow(SID2, { projectId }));await bindEnabled(SID, other);await bindEnabled(SID2, APP_ID);@@ -562,7 +565,7 @@ describe("qq binding routes and the passive reply budget", () => {// —— renderMarkdown: the per-binding formatting option ————————————————————————it("renders the constructs QQ has, and degrades the two it does not", async () => {- const row = sessionRowOf(SID2, projectId);+ const row = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row,@@ -583,7 +586,7 @@ describe("qq binding routes and the passive reply budget", () => {it("renderMarkdown off reproduces the plain msg_type 0 send, byte for byte", async () => {const raw = "## Result\n\nRan **2** tests.";- const row = sessionRowOf(SID2, projectId);+ const row = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row, multiMessageFakeSession(SID2, [raw]));await bindEnabled(SID2, APP_ID, { renderMarkdown: false });@@ -598,7 +601,7 @@ describe("qq binding routes and the passive reply budget", () => {it("a markdown send the platform REFUSES falls back to plain text, at the cost of one slot", async () => {const raw = "**bold** and more";- const row = sessionRowOf(SID2, projectId);+ const row = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row, multiMessageFakeSession(SID2, [raw]));await bindEnabled(SID2);@@ -617,7 +620,7 @@ describe("qq binding routes and the passive reply budget", () => {});it("a refusal that was not about the body is not retried, so the reserved slot is kept", async () => {- const row = sessionRowOf(SID2, projectId);+ const row = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row, multiMessageFakeSession(SID2, ["**bold**"]));await bindEnabled(SID2);@@ -637,7 +640,7 @@ describe("qq binding routes and the passive reply budget", () => {// —— The budget ——————————————————————————————————————————————————————————it("a run of six messages reaches QQ as four, the last carrying the remainder", async () => {- const row = sessionRowOf(SID2, projectId);+ const row = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row, multiMessageFakeSession(SID2, ["m1", "m2", "m3", "m4", "m5", "m6"]));await bindEnabled(SID2);@@ -656,7 +659,7 @@ describe("qq binding routes and the passive reply budget", () => {});it("a group chat gets the platform's larger budget", async () => {- const row = sessionRowOf(SID2, projectId);+ const row = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row, multiMessageFakeSession(SID2, ["g1", "g2", "g3", "g4", "g5", "g6"]));await bindEnabled(SID2);@@ -678,7 +681,7 @@ describe("qq binding routes and the passive reply budget", () => {it("the approval notice takes the reserved slot rather than being lost behind it", async () => {// Three messages spend every immediate slot; the notice then has only the reserved one// left — and it must not wait for the run, which is parked until a human acts.- const row = sessionRowOf(SID2, projectId);+ const row = sessionRow(SID2, { projectId });row.approvalMode = "always-ask";t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row, parkingAfterMessagesSession(SID2, ["a1", "a2", "a3"]));@@ -705,7 +708,7 @@ describe("qq binding routes and the passive reply budget", () => {it("one-message-per-line is clamped to the budget, not to the channel-neutral 20", async () => {const lines = Array.from({ length: 10 }, (_, i) => `line ${i + 1}`);- const row = sessionRowOf(SID2, projectId);+ const row = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row, multiMessageFakeSession(SID2, [lines.join("\n")]));await api.put(BASE(SID2), { appId: APP_ID, appSecret: APP_SECRET, linePerMessage: true });@@ -730,7 +733,7 @@ describe("qq binding routes and the passive reply budget", () => {it("a file the reply mentions is filed as an expected error record and spends no reply slot", async () => {const ws = await fs.mkdtemp(path.join(t.root, "ws-"));- const row = sessionRowOf(SID2, projectId);+ const row = sessionRow(SID2, { projectId });row.workspace = ws;t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row, multiMessageFakeSession(SID2, ["The notes are in xx.md."]));@@ -766,7 +769,7 @@ describe("qq binding routes and the passive reply budget", () => {it("three files in one reply are ONE expected record naming all three, and QQ hears only the reply", async () => {const ws = await fs.mkdtemp(path.join(t.root, "ws-"));- const row = sessionRowOf(SID2, projectId);+ const row = sessionRow(SID2, { projectId });row.workspace = ws;t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row, multiMessageFakeSession(SID2, ["Wrote a.md, b.md and c.md."]));@@ -899,15 +902,16 @@ describe("the QQ client's media half", () => {describe("the passive-reply ledger's lifetime", () => {const CONFIG = { appId: APP_ID, appSecret: APP_SECRET };const CHAT = qqChatIdOf("c2c", USER_OPENID);- const settle = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));- /**- * The ledger map is private and, for the eviction below, has no behavioural surface at- * all: nothing past the window can be replied to whether it is held or not, so how many- * are held is the only question there is to ask.- */- const ledgerCount = (c: QQConnector): number =>- (c as unknown as { ledgers: Map<string, unknown> }).ledgers.size;+ // The tail's flush is a timer: the clock is the test's, so "nothing more arrives" is+ // proved by advancing past it rather than by waiting it out.+ beforeEach(() => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ });+ afterEach(() => {+ vi.useRealTimers();+ });+ const pastTheTail = () => vi.advanceTimersByTimeAsync(TAIL_MS * 3);/** A connector on a fake transport with its gateway open and its client built. */async function connected(opts: QQConnectorOpts = {}) {@@ -946,7 +950,7 @@ describe("the passive-reply ledger's lifetime", () => {await spendImmediate(client);await client.sendText(CHAT, "withheld"); // no immediate slot left: waits for the reserved oneconnection.close();- await settle(TAIL_MS * 3);+ await pastTheTail();// The binding is off. A message arriving now lands in a chat the Session no longer// answers, and there is no route by which the user could have expected it.expect(fake.allSends().map((s) => s.content)).toEqual(["a", "b", "c"]);@@ -955,7 +959,7 @@ describe("the passive-reply ledger's lifetime", () => {const again = await connector.connect(CONFIG, { onMessage: () => {} });await fake.lastGateway().fire(c2cText("hello again", "msg_reenabled"));await client.sendText(CHAT, "fresh");- await settle(TAIL_MS * 3);+ await pastTheTail();expect(fake.allSends().map((s) => s.content)).toEqual(["a", "b", "c", "fresh"]);expect(fake.allSends().at(-1)).toMatchObject({ msgId: "msg_reenabled", msgSeq: 1 });again.close();@@ -968,12 +972,13 @@ describe("the passive-reply ledger's lifetime", () => {await client.sendText(CHAT, "the end");// The one send carrying a long answer's coalesced end, lost to a transient 5xx.fake.failSend = "503 Service Unavailable";- await settle(TAIL_MS * 3);+ await pastTheTail();expect(fake.allSends().map((s) => s.content)).toEqual(["a", "b", "c"]);fake.failSend = null;await gateway.fire(c2cText("still there?", "msg_next"));- await waitFor(() => fake.allSends().length === 4);+ await pastTheTail();+ expect(fake.allSends()).toHaveLength(4);expect(fake.allSends().at(-1)).toMatchObject({content: "the end",msgId: "msg_next",@@ -981,15 +986,13 @@ describe("the passive-reply ledger's lifetime", () => {});});- it("forgets a chat left quiet past the reply window", async () => {+ it("forgets a chat left quiet past the reply window: it refuses rather than restarting", async () => {let clock = Date.now();- const { fake, client, connector, gateway } = await connected({ now: () => clock });+ const { fake, client, gateway } = await connected({ now: () => clock });await gateway.fire(c2cText("go", "msg_old"));await client.sendText(CHAT, "answered");- expect(ledgerCount(connector)).toBe(1);- // Past the window this chat can never be replied to again, so its accounting is dead- // weight — one entry per chat the bot is ever messaged in, each able to hold a tail.+ // Past the window this chat can never be replied to again.clock += QQ_PASSIVE_WINDOW_MS + 1;await gateway.fire({kind: "group",@@ -998,7 +1001,6 @@ describe("the passive-reply ledger's lifetime", () => {content: "hi",senderOpenid: "member_1",});- expect(ledgerCount(connector)).toBe(1);// The live chat still answers, and the expired one refuses rather than restarting a// sequence the platform still remembers.await client.sendText(qqChatIdOf("group", GROUP_OPENID), "answered too");diff --git a/packages/server/test/messaging-telegram.test.ts b/packages/server/test/messaging-telegram.test.tsindex 5f7b38d5..78209c10 100644--- a/packages/server/test/messaging-telegram.test.ts+++ b/packages/server/test/messaging-telegram.test.ts@@ -1,24 +1,53 @@/**- * Telegram messaging tests — the mirror of messaging.test.ts for the second channel, and- * the proof the connector seam holds: the /api/sessions/:id/messaging/telegram routes- * (token masking + keep-on-blank, the bot id as the account identity and the enable-time- * 409 it collides on, the save/enable split, the getMe- * probe surfacing the bot username), the channel-agnostic GET the channel-aware editor- * reads, and the connector's long-poll loop through a fake Bot API transport — offset- * advancement, the connect-time backlog drain, inbound routing as plain user input,- * an inbound photo (largest variant, caption as the message text, a failed download- * degrading to a notice), an inbound `document` (the one media field the file seam takes —- * scratchpad attachment, caption as the message text, and Telegram's own 20MB bot download- * ceiling reported as a size refusal rather than an unexplained failure),- * per-message mirroring with one reply thread per run in groups,- * mentioned files leaving as a photo or a document, 4096-safe chunking,- * non-text notices, poll-failure status flips, and the conflict path a second poller- * produces (the 409 backoff, the connect-time webhook clear, and the actionable text the- * transport maps a 409 to). No test opens real network.+ * Telegram messaging — the mirror of messaging.test.ts for the second channel, over a fake Bot+ * API transport (the Feishu side, where a case needs one, is the suite's Feishu fake). No test+ * opens a network connection.+ *+ * Routes:+ * - The bot id is read off the token (a malformed token refused). A PUT saves the token only+ * (masked, the bot id as the account, disabled, no poll; a blank token keeps the stored one,+ * the clear flag drops it after a disable); the delivery flags ride the same PUT, defaulting+ * off. POST /state owns the connection (getMe, then the poll); a new token while enabled+ * restarts the poll; a rotated secret saves freely and collides with another Session's+ * enabled bot only on enable.+ * - GET /messaging lists every saved channel side by side; enabling a second channel of one+ * Session is a 409 another_channel_enabled.+ * - POST /test probes getMe, reporting the username and @BotFather's Group Privacy; failures+ * are ok:false. /test-message needs a known chat.+ *+ * The connector and the bridge:+ * - Inbound text starts an ordinary user Task and advances the offset; the reply mirrors each+ * completed message on its own, in groups threaded onto the inbound message (the run's first+ * only), in a real supergroup too; non-message updates are skipped.+ * - This bot's @mention is stripped from a group message (case-insensitively, by text_mention+ * id, by UTF-16 units), others' kept, a mention that is not the addressing prefix kept, a+ * mention-only message starting nothing.+ * - Forum topics: the reply follows the remembered topic, the newest one the user writes in,+ * and a held reply answers where its run was asked; notices go there too; a deleted topic+ * degrades to a plain send; General, private chats, non-forum supergroups, reply chains in+ * General and pre-topic chat ids mint no topic.+ * - A flood wait is not retried; a send failing every way surfaces after bounded attempts.+ * - An inbound photo becomes an image_url part at its largest size, its caption (this bot's+ * mention stripped) as the text; a failed download degrades to a notice. A document lands in+ * the scratchpad as a path line (caption first), past Telegram's own ceiling is a size+ * refusal, and a nameless one gets a placeholder; video, audio and voice get the+ * not-supported notice.+ * - Mentioned files leave as a photo and a document after the text; a long reply is chunked+ * under the shared cap; formatting renders what Telegram has (degrading the rest, escaping+ * the model's HTML), plain when renderMarkdown is off, falls back to plain on a refusal,+ * never retries a send that may have landed, and chunks without splitting a fence or entity.+ * - Connecting drains the dark-period backlog; poll failures flip the status to error once and+ * recovery re-probes; start() connects an enabled binding; a message delivered under two+ * update ids starts one Task; racing syncs leave one poller.+ * - Under a persistent 409 the poll reports once and backs off, recovers when the conflict ends,+ * probes for a webhook once per connection and names it, and a closed connection issues+ * nothing; a failure that recovers on its own does not silence the refusal behind it.+ * - A 409 is reported as the action to take (another poller, a leftover webhook); other Bot+ * API descriptions pass through; the bot token is never echoed.*/import fs from "node:fs/promises";import path from "node:path";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";import {approvalDecision,assistantText,@@ -29,13 +58,14 @@ import {toolCall,} from "@prismshadow/penguin-core";import type { ApproveFn, OmniMessage } from "@prismshadow/penguin-core";+import { wire } from "@prismshadow/penguin-core/kernel";import type {FeishuBindingResponse,MessagingBindingsResponse,TelegramBindingResponse,TelegramTestResponse,} from "../src/api/types.js";-import type { SessionRow } from "../src/db/repos/sessions.js";+import { ProjectsRepo } from "../src/db/repos/projects.js";import type { RuntimeSession } from "../src/runtime/session-manager.js";import { INLINE_IMAGE_MAX_BYTES } from "../src/services/attachment-limits.js";import {@@ -64,17 +94,13 @@ import {createTelegramTransport,} from "../src/runtime/messaging/telegram-api.js";import { TelegramConnector, telegramBotIdOf } from "../src/runtime/messaging/telegram-connector.js";-import type {- FeishuApiClient,- FeishuCredentials,- FeishuEventHandlers,- FeishuSdk,-} from "../src/runtime/messaging/feishu-sdk.js";+import { FakeFeishuSdk } from "./fixtures/feishu.js";+import { fakeFetch, jsonResponse } from "./fixtures/fetch.js";+import { forwardingTo } from "./fixtures/forwarding.js";+import { fakeSession, sessionRow, uniqueSessionId } from "./fixtures/session.js";import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";import type { TestApp } from "./helpers.js";-const SID = "session-2026-08-26-10-00-00-t9000001";-const SID2 = "session-2026-08-26-10-00-01-t9000002";const BASE = (sid: string) => `/api/sessions/${sid}/messaging/telegram`;const TOKEN = "7000000001:test-secret-AAAA-1111";@@ -365,39 +391,6 @@ class FakeTelegramTransport {}}-/**- * Minimal fake Feishu SDK for the cross-channel tests (enabling the feishu side must not- * import the real Lark SDK or open network): connects instantly, records nothing.- */-class FakeFeishuSdk implements FeishuSdk {- async createClient(_creds: FeishuCredentials): Promise<FeishuApiClient> {- return {- async checkCredentials() {- return null;- },- async sendText() {},- async replyText() {},- async sendCard() {},- async replyCard() {},- async botOpenId() {- return null;- },- async fetchMessageImage(): Promise<never> {- throw new Error("the feishu side of these tests never carries an image");- },- async fetchMessageFile(): Promise<never> {- throw new Error("the feishu side of these tests never carries a file");- },- async sendImage() {},- async sendFile() {},- };- }- async connect(_creds: FeishuCredentials, handlers: FeishuEventHandlers) {- handlers.onReady?.();- return { close: () => {} };- }-}-/** A private-chat text message from a fixed user. */function privateText(text: string, messageId = 1): TelegramUpdate["message"] {return {@@ -467,19 +460,12 @@ function echoFakeSession(runs: InputPayload[][],reply = "Reply text",): RuntimeSession {- return {- sessionId,- toolPermission: () => "rw",- generateTitle: async () => ({ title: null, usage: null }),- compactability: () => "ok" as const,- steer: () => false,- skipReconnectWait: () => false,+ return fakeSession(sessionId, {async *run(input: OmniMessage[]) {runs.push(input.map((m) => m.payload as InputPayload));yield assistantText(reply);},- async *compact() {},- };+ });}/**@@ -492,32 +478,19 @@ function multiMessageFakeSession(texts: readonly string[],gate?: Promise<void>,): RuntimeSession {- return {- sessionId,- toolPermission: () => "rw",- generateTitle: async () => ({ title: null, usage: null }),- compactability: () => "ok" as const,- steer: () => false,- skipReconnectWait: () => false,+ return fakeSession(sessionId, {async *run() {for (let i = 0; i < texts.length; i += 1) {if (gate !== undefined && i === texts.length - 1) await gate;yield assistantText(texts[i]!);}},- async *compact() {},- };+ });}/** Fake Session that parks on one approval per run (drives an approval_request event). */function parkingFakeSession(sessionId: string): RuntimeSession {- return {- sessionId,- toolPermission: () => "rw",- generateTitle: async () => ({ title: null, usage: null }),- compactability: () => "ok" as const,- steer: () => false,- skipReconnectWait: () => false,+ return fakeSession(sessionId, {async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {const tc = toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-forum" });yield tc;@@ -525,23 +498,7 @@ function parkingFakeSession(sessionId: string): RuntimeSession {yield approvalDecision(decision, "tc-forum");yield assistantText("after approval");},- async *compact() {},- };-}--function sessionRowOf(sessionId: string, projectId: string): SessionRow {- return {- sessionId,- projectId,- agentId: "default_agent",- provider: "custom",- modelId: "m1",- workspace: "/tmp/w",- approvalMode: "allow-all",- title: null,- createdAt: new Date().toISOString(),- lastActiveAt: new Date().toISOString(),- };+ });}describe("telegramBotIdOf", () => {@@ -557,10 +514,19 @@ describe("telegram binding routes and connector loop", () => {let t: TestApp;let api: ReturnType<typeof apiClient>;let fake: FakeTelegramTransport;- let projectId: string;let runs: InputPayload[][];/** The server log, so a delivery that succeeded only in a degraded form is observable. */- let logLines: string[];+ let logLines: string[] = [];+ /**+ * The case's Project and its two Sessions, fresh per case: the app is the describe's, a+ * binding, a poll and a status belong to their Session, and the error log dedupes and reads+ * per Project. The Project is birder's row alone — every Session here is a fake, so nothing+ * opens a default Agent's tree.+ */+ let projectId: string;+ let SID: string;+ let SID2: string;+ let cases = 0;/** Save the token, then flip the toggle on and wait for the poll loop's handshake. */const bindEnabled = async (sid: string, botToken = TOKEN) => {@@ -569,25 +535,40 @@ describe("telegram binding routes and connector loop", () => {await waitFor(() => t.deps.messaging.statusOf(sid, "telegram").state === "connected");};- beforeEach(async () => {- fake = new FakeTelegramTransport();- logLines = [];+ beforeAll(async () => {t = await createTestApp({- telegramTransport: fake,+ telegramTransport: forwardingTo(() => fake),telegramRetryDelayMs: () => 1,feishuSdk: new FakeFeishuSdk(),log: (line) => logLines.push(line),});const { cookie } = await provisionUser(t.app, "birder");api = apiClient(t.app, cookie);- projectId = "birder-default_project";+ });+ afterAll(async () => {+ await t.cleanup();+ });+ beforeEach(() => {+ fake = new FakeTelegramTransport();+ logLines = [];runs = [];- const row = sessionRowOf(SID, projectId);+ cases += 1;+ projectId = `birder-case-${cases}`;+ wire(ProjectsRepo, { db: t.deps.db }).insert({+ projectId,+ ownerUserId: "birder",+ createdAt: new Date().toISOString(),+ });+ SID = uniqueSessionId();+ SID2 = uniqueSessionId();+ const row = sessionRow(SID, { projectId });t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row, echoFakeSession(SID, runs));});- afterEach(async () => {- await t.cleanup();+ afterEach(() => {+ // What the case bound goes with it, poll loop and all, and so does the error log it wrote.+ for (const row of t.deps.messagingRepo.listAll()) t.deps.messaging.unbindSession(row.sessionId);+ t.deps.db.prepare("DELETE FROM error_records").run();});it("PUT saves the token only (masked, bot id extracted, disabled, no poll); blank keeps the stored token", async () => {@@ -660,7 +641,7 @@ describe("telegram binding routes and connector loop", () => {});it("a token swap cannot re-point an ENABLED binding at a bot another Session has enabled", async () => {- t.deps.sessionsRepo.insert(sessionRowOf(SID2, projectId));+ t.deps.sessionsRepo.insert(sessionRow(SID2, { projectId }));// Two Sessions, each polling its own bot.await bindEnabled(SID);await bindEnabled(SID2, "7000000002:test-secret-BBBB-2222");@@ -718,7 +699,7 @@ describe("telegram binding routes and connector loop", () => {});it("the account is the bot id: a rotated secret saves freely and collides only on enable", async () => {- t.deps.sessionsRepo.insert(sessionRowOf(SID2, projectId));+ t.deps.sessionsRepo.insert(sessionRow(SID2, { projectId }));await bindEnabled(SID);// Different secret half, same id half: the identity is the id, not the whole token. It// saves without a murmur — saving is never exclusive across Sessions...@@ -1137,7 +1118,7 @@ describe("telegram binding routes and connector loop", () => {it("remembers the topic, and every later message of the run reaches it", async () => {// Three completed messages in ONE run: the first threads onto the inbound message, the// two after it are plain sends — which is precisely where the topic used to be lost.- const row = sessionRowOf(SID2, projectId);+ const row = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row, multiMessageFakeSession(SID2, ["first", "second", "third"]));await bindEnabled(SID2);@@ -1175,7 +1156,7 @@ describe("telegram binding routes and connector loop", () => {// reply anchor. Addressed at delivery time, the WHOLE answer to the first question would// land in their topic, quoted onto their message — the every-message relay can misplace// the tail of a reply that way, never the entire thing.- const row = sessionRowOf(SID2, projectId);+ const row = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row);let release!: () => void;const gate = new Promise<void>((resolve) => {@@ -1223,7 +1204,7 @@ describe("telegram binding routes and connector loop", () => {});it("sends the approval notice and the test message into the remembered topic", async () => {- const row = sessionRowOf(SID2, projectId);+ const row = sessionRow(SID2, { projectId });// The approval only becomes an event when something is actually asked.row.approvalMode = "always-ask";t.deps.sessionsRepo.insert(row);@@ -1252,7 +1233,7 @@ describe("telegram binding routes and connector loop", () => {it("a topic that has been deleted degrades to a plain send instead of losing the reply", async () => {// Three completed messages in one run: the topic is gone for every one of them, which is// what the trace has to survive without turning into a line per send.- const row = sessionRowOf(SID2, projectId);+ const row = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row, multiMessageFakeSession(SID2, ["first", "second", "third"]));await bindEnabled(SID2);@@ -1608,7 +1589,7 @@ describe("telegram binding routes and connector loop", () => {const ws = await fs.mkdtemp(path.join(t.root, "ws-"));await fs.writeFile(path.join(ws, "chart.png"), PHOTO_BYTES);await fs.writeFile(path.join(ws, "notes.md"), "hello");- const row2 = sessionRowOf(SID2, projectId);+ const row2 = sessionRow(SID2, { projectId });row2.workspace = ws;t.deps.sessionsRepo.insert(row2);t.deps.manager.adopt(@@ -1632,7 +1613,7 @@ describe("telegram binding routes and connector loop", () => {});it("relays each completed assistant message separately, in order, as it completes", async () => {- const row2 = sessionRowOf(SID2, projectId);+ const row2 = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row2);let release = () => {};const gate = new Promise<void>((r) => {@@ -1654,7 +1635,7 @@ describe("telegram binding routes and connector loop", () => {});it("in a group only the run's first message carries the reply ref", async () => {- const row2 = sessionRowOf(SID2, projectId);+ const row2 = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row2);t.deps.manager.adopt(row2, multiMessageFakeSession(SID2, ["first", "second"]));await bindEnabled(SID2, "7000000004:test-secret-FFFF-6666");@@ -1673,7 +1654,7 @@ describe("telegram binding routes and connector loop", () => {});it("chunks a long reply under the shared 4000-char cap (inside Telegram's 4096 limit)", async () => {- const row2 = sessionRowOf(SID2, projectId);+ const row2 = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row2);t.deps.manager.adopt(row2, echoFakeSession(SID2, runs, "x".repeat(9000)));await bindEnabled(SID2, "7000000002:test-secret-DDDD-4444");@@ -1689,7 +1670,7 @@ describe("telegram binding routes and connector loop", () => {/** SID2 replying with one fixed text, bound and connected, ready to be messaged. */const bindReplying = async (text: string, token: string, put: Record<string, unknown> = {}) => {- const row2 = sessionRowOf(SID2, projectId);+ const row2 = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row2);t.deps.manager.adopt(row2, echoFakeSession(SID2, runs, text));expect((await api.put(BASE(SID2), { botToken: token, ...put })).status).toBe(200);@@ -2204,13 +2185,11 @@ describe("telegram transport error mapping", () => {// Through the transport's own fetch seam, not the global: the production transport// calls undici's fetch on purpose (see telegram-api's TelegramFetch), so replacing// `globalThis.fetch` would leave it talking to the real Bot API.- const stub = (async () =>- new Response(JSON.stringify(body), {- status: 409,- headers: { "content-type": "application/json" },- })) as unknown as TelegramTransportOpts["fetch"];+ const refusing = fakeFetch(() => jsonResponse(body, 409));try {- const bot = createTelegramTransport({ fetch: stub }).createClient({ botToken: TOKEN });+ const bot = createTelegramTransport({+ fetch: refusing.fetch as unknown as TelegramTransportOpts["fetch"],+ }).createClient({ botToken: TOKEN });await run(bot);return "";} catch (err) {diff --git a/packages/server/test/messaging-wechat-scan.test.ts b/packages/server/test/messaging-wechat-scan.test.tsindex 5b8d9336..d919c7d7 100644--- a/packages/server/test/messaging-wechat-scan.test.ts+++ b/packages/server/test/messaging-wechat-scan.test.ts@@ -1,18 +1,31 @@/**- * WeChat scan-to-connect — the only way this channel is ever bound, so these tests cover- * more than QQ's equivalent: there is no typed fallback behind them.+ * WeChat scan-to-connect — the only way this channel is ever bound, so these cases cover more+ * than QQ's equivalent: there is no typed fallback behind them. Three layers, each faked at a+ * different depth on purpose: the protocol runs the real transport against the suite's fetch+ * fake (the request shape and status vocabulary are what a seam fake would stop testing); the+ * service and the routes run over a fake transport, the service being a state machine no wire+ * can express. The one invariant spanning all three: the platform's poll handle, which is what+ * collects a bot token, never reaches the browser.*- * Three layers, each fake at a different depth on purpose. The protocol layer drives the- * real transport against a stubbed `globalThis.fetch`, because the request shape and the- * status vocabulary are exactly what a seam fake would stop testing. The service layer uses- * a fake transport, because what it owns is a state machine — claims, the pairing code, the- * IDC redirect, the TTL — that no wire can express. The route layer uses the same fake, and- * asserts the one invariant that spans all three: the platform's poll handle, which is what- * collects a bot token, never appears in anything the browser is given.+ * - The protocol asks for a code under the bot type offering no local tokens; maps every+ * status the platform reports onto one the browser can render (an unknown one reads as+ * pending); puts the pairing code on the status query; reads a confirmed scan's credentials+ * and assigned host (the entry host when none is named); refuses a confirmation without+ * credentials; reads a long poll that closed silently as pending.+ * - The service hands out a handle of its own; answers an overlapping poll `pending`; holds a+ * pairing code for the next poll and stops resending it once accepted; refuses a code for+ * another Session's task; follows an IDC redirect silently; spends the task on a completed+ * scan and on every other end the platform declares, but keeps it pollable when the request+ * failed; keeps Sessions' tasks apart, evicting only the caller's own oldest at its ceiling;+ * sweeps abandoned tasks and forgets a Session's tasks wholesale.+ * - The routes hand the browser a task, a URL and an interval, never the handle; a completed+ * poll saves the binding with the bot id as the account and no token in the answer; a+ * pairing code is reported and taken (404 for a task that is gone); a scan is refused while+ * the connection is live; a platform failure is a 502; an abandoned scan can be cancelled;+ * every route is owner-only.*/import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { WeChatScanPollResponse, WeChatScanStartResponse } from "../src/api/types.js";-import type { SessionRow } from "../src/db/repos/sessions.js";import { WECHAT_API_BASE } from "../src/runtime/messaging/wechat-api.js";import type {WeChatScanPollResult,@@ -28,6 +41,8 @@ import type {WeChatCredentials,WeChatTransport,} from "../src/runtime/messaging/wechat-api.js";+import { jsonResponse, stubFetch } from "./fixtures/fetch.js";+import { sessionRow } from "./fixtures/session.js";import { apiClient, createTestApp, provisionUser } from "./helpers.js";import type { TestApp } from "./helpers.js";@@ -42,69 +57,30 @@ const SCANNER = "ilink_user_aaa";/** The platform's poll handle. It turns into a bot token, so no response may carry it. */const QRCODE = "qrcode-handle-SECRET";-function sessionRowOf(sessionId: string, projectId: string): SessionRow {- return {- sessionId,- projectId,- agentId: "default_agent",- provider: "custom",- modelId: "m1",- workspace: "/tmp/w",- approvalMode: "allow-all",- title: null,- createdAt: new Date().toISOString(),- lastActiveAt: new Date().toISOString(),- };-}-// ---------------------------------------------------------------------------// The protocol, against a stubbed fetch// ----------------------------------------------------------------------------function jsonResponse(body: unknown, status = 200): Response {- return new Response(JSON.stringify(body), {- status,- headers: { "content-type": "application/json" },- });-}--async function withFetch<T>(- answer: (url: string, init: RequestInit | undefined) => Response,- body: (urls: string[]) => Promise<T>,-): Promise<T> {- const urls: string[] = [];- const original = globalThis.fetch;- globalThis.fetch = (async (input: unknown, init?: RequestInit) => {- urls.push(String(input));- return answer(String(input), init);- }) as typeof fetch;- try {- return await body(urls);- } finally {- globalThis.fetch = original;- }-}+afterEach(() => {+ vi.unstubAllGlobals();+});describe("the WeChat scan protocol", () => {it("asks for a code under the bot type and offers no local tokens", async () => {let sentBody = "";- await withFetch(- (_url, init) => {- sentBody = String(init?.body ?? "");- return jsonResponse({ qrcode: QRCODE, qrcode_img_content: "https://weixin.qq.com/q/abc" });- },- async (urls) => {- const res = await createWeChatScanTransport().createQrCode();- expect(urls[0]).toBe(`${WECHAT_API_BASE}/ilink/bot/get_bot_qrcode?bot_type=3`);- // Offering the tokens this server already holds would hand one binding's credential- // to another binding's flow.- expect(JSON.parse(sentBody)).toEqual({ local_token_list: [] });- // The handle and the URL are different things: the URL goes into the QR, the handle- // collects the token.- expect(res.qrcode).toBe(QRCODE);- expect(res.qrUrl).toBe("https://weixin.qq.com/q/abc");- },- );+ const { calls } = stubFetch((call) => {+ sentBody = call.body;+ return jsonResponse({ qrcode: QRCODE, qrcode_img_content: "https://weixin.qq.com/q/abc" });+ });+ const res = await createWeChatScanTransport().createQrCode();+ expect(calls[0]!.url).toBe(`${WECHAT_API_BASE}/ilink/bot/get_bot_qrcode?bot_type=3`);+ // Offering the tokens this server already holds would hand one binding's credential+ // to another binding's flow.+ expect(JSON.parse(sentBody)).toEqual({ local_token_list: [] });+ // The handle and the URL are different things: the URL goes into the QR, the handle+ // collects the token.+ expect(res.qrcode).toBe(QRCODE);+ expect(res.qrUrl).toBe("https://weixin.qq.com/q/abc");});it("maps every status the platform reports onto one the browser can render", async () => {@@ -120,101 +96,77 @@ describe("the WeChat scan protocol", () => {["something_new_from_tencent", "pending"],];for (const [wire, expected] of cases) {- await withFetch(- () => jsonResponse({ status: wire }),- async () => {- const res = await createWeChatScanTransport().pollQrStatus({- baseUrl: WECHAT_API_BASE,- qrcode: QRCODE,- });- expect(res.status).toBe(expected);- },- );+ stubFetch(() => jsonResponse({ status: wire }));+ const res = await createWeChatScanTransport().pollQrStatus({+ baseUrl: WECHAT_API_BASE,+ qrcode: QRCODE,+ });+ expect(res.status).toBe(expected);}});it("puts the pairing code on the status query, which is where the platform takes it", async () => {- await withFetch(- () => jsonResponse({ status: "scaned" }),- async (urls) => {- await createWeChatScanTransport().pollQrStatus({- baseUrl: WECHAT_API_BASE,- qrcode: QRCODE,- verifyCode: "8421",- });- expect(urls[0]).toContain("verify_code=8421");- expect(urls[0]).toContain(`qrcode=${encodeURIComponent(QRCODE)}`);- },- );+ const { calls } = stubFetch(() => jsonResponse({ status: "scaned" }));+ await createWeChatScanTransport().pollQrStatus({+ baseUrl: WECHAT_API_BASE,+ qrcode: QRCODE,+ verifyCode: "8421",+ });+ expect(calls[0]!.url).toContain("verify_code=8421");+ expect(calls[0]!.url).toContain(`qrcode=${encodeURIComponent(QRCODE)}`);});it("reads a confirmed scan's credentials, and the API host it assigned", async () => {- await withFetch(- () =>- jsonResponse({- status: "confirmed",- bot_token: BOT_TOKEN,- ilink_bot_id: BOT_ID,- ilink_user_id: SCANNER,- baseurl: "https://idc-7.ilinkai.weixin.qq.com",- }),- async () => {- const res = await createWeChatScanTransport().pollQrStatus({- baseUrl: WECHAT_API_BASE,- qrcode: QRCODE,- });- expect(res.bot).toEqual({- botId: BOT_ID,- botToken: BOT_TOKEN,- baseUrl: "https://idc-7.ilinkai.weixin.qq.com",- userId: SCANNER,- });- },+ stubFetch(() =>+ jsonResponse({+ status: "confirmed",+ bot_token: BOT_TOKEN,+ ilink_bot_id: BOT_ID,+ ilink_user_id: SCANNER,+ baseurl: "https://idc-7.ilinkai.weixin.qq.com",+ }),);+ const res = await createWeChatScanTransport().pollQrStatus({+ baseUrl: WECHAT_API_BASE,+ qrcode: QRCODE,+ });+ expect(res.bot).toEqual({+ botId: BOT_ID,+ botToken: BOT_TOKEN,+ baseUrl: "https://idc-7.ilinkai.weixin.qq.com",+ userId: SCANNER,+ });});it("falls back to the entry host when a confirmed scan names none", async () => {- await withFetch(- () => jsonResponse({ status: "confirmed", bot_token: BOT_TOKEN, ilink_bot_id: BOT_ID }),- async () => {- const res = await createWeChatScanTransport().pollQrStatus({- baseUrl: WECHAT_API_BASE,- qrcode: QRCODE,- });- expect(res.bot?.baseUrl).toBe(WECHAT_API_BASE);- },+ stubFetch(() =>+ jsonResponse({ status: "confirmed", bot_token: BOT_TOKEN, ilink_bot_id: BOT_ID }),);+ const res = await createWeChatScanTransport().pollQrStatus({+ baseUrl: WECHAT_API_BASE,+ qrcode: QRCODE,+ });+ expect(res.bot?.baseUrl).toBe(WECHAT_API_BASE);});it("refuses a confirmation that carried no credentials rather than storing a blank one", async () => {- await withFetch(- () => jsonResponse({ status: "confirmed", ilink_bot_id: BOT_ID }),- async () => {- await expect(- createWeChatScanTransport().pollQrStatus({ baseUrl: WECHAT_API_BASE, qrcode: QRCODE }),- ).rejects.toThrow(/no credentials/);- },- );+ stubFetch(() => jsonResponse({ status: "confirmed", ilink_bot_id: BOT_ID }));+ await expect(+ createWeChatScanTransport().pollQrStatus({ baseUrl: WECHAT_API_BASE, qrcode: QRCODE }),+ ).rejects.toThrow(/no credentials/);});it("reads a long poll that closed with nothing to say as pending, not as a failure", async () => {// A window that expires and a client-side timeout are the same thing here: nothing// changed, ask again. Only that keeps a transient close from taking the code down.- const original = globalThis.fetch;- globalThis.fetch = (async () => {- const err = new Error("aborted");- err.name = "TimeoutError";- throw err;- }) as typeof fetch;- try {- const res = await createWeChatScanTransport().pollQrStatus({- baseUrl: WECHAT_API_BASE,- qrcode: QRCODE,- });- expect(res).toEqual({ status: "pending" });- } finally {- globalThis.fetch = original;- }+ stubFetch(() => {+ throw Object.assign(new Error("aborted"), { name: "TimeoutError" });+ });+ const res = await createWeChatScanTransport().pollQrStatus({+ baseUrl: WECHAT_API_BASE,+ qrcode: QRCODE,+ });+ expect(res).toEqual({ status: "pending" });});});@@ -450,7 +402,7 @@ describe("wechat scan routes", () => {});const { cookie } = await provisionUser(t.app, "birder");api = apiClient(t.app, cookie);- t.deps.sessionsRepo.insert(sessionRowOf(SID, PROJECT));+ t.deps.sessionsRepo.insert(sessionRow(SID, { projectId: PROJECT }));});afterEach(async () => {await t.cleanup();diff --git a/packages/server/test/messaging-wechat-transport.test.ts b/packages/server/test/messaging-wechat-transport.test.tsindex 6fdd4f5d..c72d15bc 100644--- a/packages/server/test/messaging-wechat-transport.test.ts+++ b/packages/server/test/messaging-wechat-transport.test.ts@@ -1,25 +1,41 @@/**- * The WeChat production adapter — the half of the channel that talks to Tencent.+ * The WeChat production adapter — the half of the channel that talks to Tencent, under the+ * fake transport messaging-wechat.test.ts drives the connector with: the request envelope,+ * the long poll's cursor, the wire message reduced to the connector's event, and the CDN+ * media path (a pre-signed upload of AES-128-ECB ciphertext one way, a decrypt the other).*- * messaging-wechat.test.ts drives the connector and its routes over a fake transport, which- * leaves everything under that seam unexercised: the request envelope and its headers, the- * long poll's cursor, the reduction of the wire's message shape to the connector's event, and- * the whole CDN media path — a pre-signed upload of AES-128-ECB ciphertext in one direction- * and a decrypt in the other. Those are where a platform failure actually reaches this- * product, so they get their own file (the split messaging-qq-transport.test.ts makes).+ * - Every call is authenticated and identified the same way; a platform failure code or an+ * HTTP failure's body is carried through, never with the credential in it.+ * - The credential probe passes on a good token whose ticket call has no conversation yet,+ * fails on a refused or stale credential and on a request that never arrived, and never+ * uses the update poll (which would eat a message).+ * - The long poll sends its cursor and reports the next one (keeping the old one when none+ * comes back); a quiet window is an empty answer, while a transport fault and the caller's+ * own abort are not.+ * - Inbound normalization drops this bot's own messages, reads a voice transcription as text,+ * quotes what a reply answers, normalizes images, files and videos, names an unnamed file+ * plainly and skips media with no URL.+ * - Outbound sends carry one item per request and the conversation token when known; an+ * image or file is uploaded as ciphertext under a fresh key the handle declares, with the+ * plaintext length, a caption goes out as its own message, and a missing upload URL fails+ * readably.+ * - Every failure carries its verdict: a refusal behind an accepted credential, the session+ * timeout (which still fails the probe), a request that never arrived and a 408, 429 or 5xx+ * recover; a refused credential, a wrong host and an unreadable answer do not.+ * - Downloads decrypt under either key encoding, pass unencrypted bytes through, refuse a+ * transfer past the cap as a size problem, keep the signed URL out of the failure, and+ * report an undecryptable payload as such.*- * Nothing here opens a socket. `globalThis.fetch` is stubbed the way that suite stubs it —- * a test hook rather than a module mock, because this suite shares one module registry- * across files and `vi.mock` would leak into every later one (see vitest.config.ts).+ * Nothing here opens a socket: the global fetch is the suite's fetch fake, restored after+ * every case — a stub rather than a module mock, because this suite shares one module+ * registry across files and `vi.mock` would leak into every later one (see vitest.config.ts).*/-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";import { messagingErrorKind } from "../src/runtime/messaging/error-kind.js";import { MessagingMediaTooLargeError } from "../src/runtime/messaging/media.js";import type { WeChatCredentials } from "../src/runtime/messaging/wechat-api.js";import {- DRAIN_TIMEOUT_MS,- LONG_POLL_TIMEOUT_MS,WECHAT_API_BASE,WECHAT_STALE_TOKEN_CODE,WECHAT_VIDEO_FILE_NAME,@@ -28,6 +44,8 @@ import {normalizeWeChatMessage,parseWeChatAesKey,} from "../src/runtime/messaging/wechat-api.js";+import { jsonResponse, stubFetch } from "./fixtures/fetch.js";+import type { FetchCall } from "./fixtures/fetch.js";const CREDS: WeChatCredentials = {botId: "bot_9001",@@ -38,59 +56,21 @@ const CREDS: WeChatCredentials = {const USER = "ilink_user_aaa";-/** One recorded request against the stubbed fetch. */-interface Call {- url: string;- method: string;- body: string;- headers: Headers;-}--function jsonResponse(body: unknown, status = 200): Response {- return new Response(JSON.stringify(body), {- status,- headers: { "content-type": "application/json" },- });-}+afterEach(() => {+ vi.unstubAllGlobals();+});/**- * Installs a fetch stub for the run of `body`, and hands it the calls it recorded.- *- * `answer` returns the response for one call; returning null means "the default", which is- * an empty success — enough for the calls a test makes on its way to the one it is about.+ * Stands the suite's fetch fake in for the global fetch: `answer` decides a call's response,+ * and returning null gives the default — an empty success, enough for the calls a test makes+ * on its way to the one it is about.*/-async function withFetch<T>(- answer: (call: Call, index: number) => Response | null,- body: (calls: Call[]) => Promise<T>,-): Promise<T> {- const calls: Call[] = [];- const original = globalThis.fetch;- globalThis.fetch = (async (input: unknown, init?: RequestInit) => {- const call: Call = {- url: String(input),- method: init?.method ?? "GET",- body: typeof init?.body === "string" ? init.body : "",- headers: new Headers(init?.headers),- };- // The CDN upload sends bytes rather than a string; recorded separately below.- if (init?.body instanceof Uint8Array) uploads.push(Buffer.from(init.body));- calls.push(call);- const answered = answer(call, calls.length - 1);- if (answered !== null) return answered;- return jsonResponse({ ret: 0 });- }) as typeof fetch;- try {- return await body(calls);- } finally {- globalThis.fetch = original;- }+function stubWeChat(+ answer: (call: FetchCall, index: number) => Response | null = () => null,+): FetchCall[] {+ return stubFetch((call, index) => answer(call, index) ?? jsonResponse({ ret: 0 })).calls;}-/** Bytes POSTed to a CDN upload URL during the current `withFetch`. */-let uploads: Buffer[] = [];--const defaults = (): null => null;-/** The abort signal a poll takes; every test that is not about cancellation passes a live one. */const live = (): AbortSignal => new AbortController().signal;@@ -100,62 +80,52 @@ function client() {describe("the WeChat request envelope", () => {it("authenticates every call the same way and identifies the client", async () => {- await withFetch(defaults, async (calls) => {- await client().checkCredentials();- const call = calls[0]!;- expect(call.url).toBe(`${WECHAT_API_BASE}/ilink/bot/getconfig`);- expect(call.method).toBe("POST");- expect(call.headers.get("authorization")).toBe(`Bearer ${CREDS.botToken}`);- // The protocol's own auth-scheme name, not a bearer convention this server invented.- expect(call.headers.get("authorizationtype")).toBe("ilink_bot_token");- expect(call.headers.get("ilink-app-id")).toBe("bot");- // A fresh random uint32, base64 of its decimal digits — present and decodable.- const uin = call.headers.get("x-wechat-uin");- expect(uin).not.toBeNull();- expect(Buffer.from(uin!, "base64").toString("utf8")).toMatch(/^\d+$/);- // The probe is `getconfig`, which reads: polling would advance the cursor the poll- // loop is about to read, and a probe that eats a message is not a probe.- expect(JSON.parse(call.body)).toMatchObject({ ilink_user_id: USER });- expect(JSON.parse(call.body).base_info.bot_agent).toContain("PenguinHarness");- });+ const calls = stubWeChat();+ await client().checkCredentials();+ const call = calls[0]!;+ expect(call.url).toBe(`${WECHAT_API_BASE}/ilink/bot/getconfig`);+ expect(call.method).toBe("POST");+ expect(call.headers.get("authorization")).toBe(`Bearer ${CREDS.botToken}`);+ // The protocol's own auth-scheme name, not a bearer convention this server invented.+ expect(call.headers.get("authorizationtype")).toBe("ilink_bot_token");+ expect(call.headers.get("ilink-app-id")).toBe("bot");+ // A fresh random uint32, base64 of its decimal digits — present and decodable.+ const uin = call.headers.get("x-wechat-uin");+ expect(uin).not.toBeNull();+ expect(Buffer.from(uin!, "base64").toString("utf8")).toMatch(/^\d+$/);+ // The probe is `getconfig`, which reads: polling would advance the cursor the poll+ // loop is about to read, and a probe that eats a message is not a probe.+ expect(JSON.parse(call.body)).toMatchObject({ ilink_user_id: USER });+ expect(JSON.parse(call.body).base_info.bot_agent).toContain("PenguinHarness");});it("raises the platform's own failure code, and never the credential with it", async () => {- await withFetch(- () => jsonResponse({ ret: -14, errmsg: "session timeout" }),- async () => {- const err = await client()- .checkCredentials()- .catch((e: unknown) => e);- expect(err).toBeInstanceOf(WeChatApiError);- expect((err as WeChatApiError).ret).toBe(-14);- expect((err as Error).message).toContain("session timeout");- expect((err as Error).message).not.toContain(CREDS.botToken);- },- );+ stubWeChat(() => jsonResponse({ ret: -14, errmsg: "session timeout" }));+ const err = await client()+ .checkCredentials()+ .catch((e: unknown) => e);+ expect(err).toBeInstanceOf(WeChatApiError);+ expect((err as WeChatApiError).ret).toBe(-14);+ expect((err as Error).message).toContain("session timeout");+ expect((err as Error).message).not.toContain(CREDS.botToken);});it("carries an HTTP failure's body through, which is what tells a revoked token from a wrong host", async () => {- await withFetch(- () => new Response("invalid bot token", { status: 401 }),- async () => {- const err = await client()- .checkCredentials()- .catch((e: unknown) => e);- expect((err as Error).message).toContain("401");- expect((err as Error).message).toContain("invalid bot token");- },- );+ stubWeChat(() => new Response("invalid bot token", { status: 401 }));+ const err = await client()+ .checkCredentials()+ .catch((e: unknown) => e);+ expect((err as Error).message).toContain("401");+ expect((err as Error).message).toContain("invalid bot token");});it("probes even without a scanned user identity: the auth layer is what it reads", async () => {// The user id belongs to the call BEHIND the credential, and that call's outcome is not// what this probe reports (see the credential-probe suite below).- await withFetch(defaults, async (calls) => {- const bare = createWeChatTransport().createClient({ ...CREDS, userId: "" });- await expect(bare.checkCredentials()).resolves.toBeUndefined();- expect(calls).toHaveLength(1);- });+ const calls = stubWeChat();+ const bare = createWeChatTransport().createClient({ ...CREDS, userId: "" });+ await expect(bare.checkCredentials()).resolves.toBeUndefined();+ expect(calls).toHaveLength(1);});});@@ -164,66 +134,48 @@ describe("the credential probe", () => {// The reported bug. `getconfig` mints a typing ticket for a CONVERSATION, so a bot nobody// has messaged yet answers this even though its token is fine and its sends work. Reading// that as a bad credential sent the user to re-scan a token that was never the problem.- await withFetch(- () => jsonResponse({ ret: 1, errmsg: "GetTypingTicket rpc failed" }),- async () => {- await expect(client().checkCredentials()).resolves.toBeUndefined();- },- );+ stubWeChat(() => jsonResponse({ ret: 1, errmsg: "GetTypingTicket rpc failed" }));+ await expect(client().checkCredentials()).resolves.toBeUndefined();});it("fails when the credential itself is refused", async () => {for (const status of [401, 403]) {- await withFetch(- () => new Response("invalid bot token", { status }),- async () => {- const err = await client()- .checkCredentials()- .catch((e: unknown) => e);- expect(err).toBeInstanceOf(WeChatApiError);- expect((err as WeChatApiError).authenticated).toBe(false);- expect((err as Error).message).toContain(String(status));- },- );+ stubWeChat(() => new Response("invalid bot token", { status }));+ const err = await client()+ .checkCredentials()+ .catch((e: unknown) => e);+ expect(err).toBeInstanceOf(WeChatApiError);+ expect((err as WeChatApiError).authenticated).toBe(false);+ expect((err as Error).message).toContain(String(status));}});it("fails on a stale token, which arrives as a business code rather than a status", async () => {// The one non-zero envelope code that IS about the credential: everything else means the// request got past it.- await withFetch(- () => jsonResponse({ errcode: WECHAT_STALE_TOKEN_CODE, errmsg: "session timeout" }),- async () => {- const err = await client()- .checkCredentials()- .catch((e: unknown) => e);- expect(err).toBeInstanceOf(WeChatApiError);- expect((err as WeChatApiError).authenticated).toBe(false);- },- );+ stubWeChat(() => jsonResponse({ errcode: WECHAT_STALE_TOKEN_CODE, errmsg: "session timeout" }));+ const err = await client()+ .checkCredentials()+ .catch((e: unknown) => e);+ expect(err).toBeInstanceOf(WeChatApiError);+ expect((err as WeChatApiError).authenticated).toBe(false);});it("fails when the request never arrived, which proves nothing either way", async () => {- const original = globalThis.fetch;- globalThis.fetch = (async () => {+ stubFetch(() => {throw new Error("getaddrinfo ENOTFOUND");- }) as typeof fetch;- try {- await expect(client().checkCredentials()).rejects.toThrow(/ENOTFOUND/);- } finally {- globalThis.fetch = original;- }+ });+ await expect(client().checkCredentials()).rejects.toThrow(/ENOTFOUND/);});it("never probes with the update poll, which would eat a message", async () => {// `getupdates` would prove the credential too, and advance the cursor the connector is// about to read — so the messages it returned would be dropped and never delivered.- await withFetch(defaults, async (calls) => {- await client().checkCredentials();- expect(calls).toHaveLength(1);- expect(calls[0]!.url).toContain("/getconfig");- expect(calls.some((c) => c.url.includes("getupdates"))).toBe(false);- });+ const calls = stubWeChat();+ await client().checkCredentials();+ expect(calls).toHaveLength(1);+ expect(calls[0]!.url).toContain("/getconfig");+ expect(calls.some((c) => c.url.includes("getupdates"))).toBe(false);});});@@ -237,100 +189,64 @@ describe("the long poll", () => {});it("sends the cursor it was given and reports the one it got back", async () => {- await withFetch(- (call) =>- call.url.endsWith("/getupdates")- ? jsonResponse({ msgs: [textMessage(7, "hello")], get_updates_buf: "cursor-2" })- : null,- async (calls) => {- const res = await client().getUpdates({ cursor: "cursor-1", signal: live() });- expect(JSON.parse(calls[0]!.body).get_updates_buf).toBe("cursor-1");- expect(res.cursor).toBe("cursor-2");- expect(res.messages).toEqual([- {- userId: USER,- messageId: "7",- text: "hello",- contextToken: "ctx-1",- images: [],- files: [],- },- ]);- },+ const calls = stubWeChat((call) =>+ call.url.endsWith("/getupdates")+ ? jsonResponse({ msgs: [textMessage(7, "hello")], get_updates_buf: "cursor-2" })+ : null,);+ const res = await client().getUpdates({ cursor: "cursor-1", signal: live() });+ expect(JSON.parse(calls[0]!.body).get_updates_buf).toBe("cursor-1");+ expect(res.cursor).toBe("cursor-2");+ expect(res.messages).toEqual([+ {+ userId: USER,+ messageId: "7",+ text: "hello",+ contextToken: "ctx-1",+ images: [],+ files: [],+ },+ ]);});it("resolves a quiet window as empty rather than as an outage", async () => {// A long poll with nothing to report holds its request until the window closes. Treating// that as a failure would put the connection into `error` every quiet minute — and the// cursor is unchanged, so the next call simply asks again from where this one started.- const original = globalThis.fetch;// The window closing, as fetch reports it — no real timer is waited on here.- globalThis.fetch = (async () => {- const err = new Error("The operation was aborted due to timeout");- err.name = "TimeoutError";- throw err;- }) as typeof fetch;- try {- const res = await client().getUpdates({ cursor: "cursor-7", signal: live() });- expect(res).toEqual({ messages: [], cursor: "cursor-7", timedOut: true });- } finally {- globalThis.fetch = original;- }+ stubFetch(() => {+ throw Object.assign(new Error("The operation was aborted due to timeout"), {+ name: "TimeoutError",+ });+ });+ const res = await client().getUpdates({ cursor: "cursor-7", signal: live() });+ expect(res).toEqual({ messages: [], cursor: "cursor-7", timedOut: true });});it("still reports a transport fault, which is not a quiet window", async () => {- const original = globalThis.fetch;- globalThis.fetch = (async () => {+ stubFetch(() => {throw new Error("getaddrinfo ENOTFOUND");- }) as typeof fetch;- try {- await expect(client().getUpdates({ cursor: "c", signal: live() })).rejects.toThrow(- /ENOTFOUND/,- );- } finally {- globalThis.fetch = original;- }+ });+ await expect(client().getUpdates({ cursor: "c", signal: live() })).rejects.toThrow(/ENOTFOUND/);});it("rethrows when the CALLER closed the connection, which is not a quiet window", async () => {// A disable aborts the same way a deadline does, and must reach the poll loop as the end// of the connection rather than as one more empty answer.const controller = new AbortController();- const original = globalThis.fetch;- globalThis.fetch = (async (_input: unknown, init?: RequestInit) => {+ stubFetch(() => {controller.abort();- const err = new Error("aborted");- err.name = "AbortError";- void init;- throw err;- }) as typeof fetch;- try {- await expect(- client().getUpdates({ cursor: "c", signal: controller.signal }),- ).rejects.toThrow();- } finally {- globalThis.fetch = original;- }- });-- it("gives the drain a shorter deadline than a long poll, so it cannot swallow a live message", async () => {- // A drain asks for what the platform is already HOLDING. Parked for the long-poll window- // it would instead return the first message a user sends after enabling — which the- // connector then discards as backlog.- expect(DRAIN_TIMEOUT_MS).toBeLessThan(LONG_POLL_TIMEOUT_MS);+ throw Object.assign(new Error("aborted"), { name: "AbortError" });+ });+ await expect(client().getUpdates({ cursor: "c", signal: controller.signal })).rejects.toThrow();});it("keeps the old cursor when the response carries none, rather than starting over", async () => {// An empty `get_updates_buf` means "from the beginning" on the next call, which would// replay everything this poll just consumed.- await withFetch(- () => jsonResponse({ msgs: [] }),- async () => {- const res = await client().getUpdates({ cursor: "cursor-9", signal: live() });- expect(res.cursor).toBe("cursor-9");- },- );+ stubWeChat(() => jsonResponse({ msgs: [] }));+ const res = await client().getUpdates({ cursor: "cursor-9", signal: live() });+ expect(res.cursor).toBe("cursor-9");});});@@ -456,150 +372,125 @@ describe("inbound normalization", () => {describe("outbound sends", () => {it("sends one item per request and echoes the conversation token", async () => {- await withFetch(defaults, async (calls) => {- await client().sendText({ userId: USER, text: "hi", contextToken: "ctx-7" });- const body = JSON.parse(calls[0]!.body);- expect(calls[0]!.url).toBe(`${WECHAT_API_BASE}/ilink/bot/sendmessage`);- expect(body.msg.to_user_id).toBe(USER);- expect(body.msg.context_token).toBe("ctx-7");- expect(body.msg.message_type).toBe(2);- expect(body.msg.message_state).toBe(2);- // Exactly one item: the platform does not take a two-item list.- expect(body.msg.item_list).toEqual([{ type: 1, text_item: { text: "hi" } }]);- });+ const calls = stubWeChat();+ await client().sendText({ userId: USER, text: "hi", contextToken: "ctx-7" });+ const body = JSON.parse(calls[0]!.body);+ expect(calls[0]!.url).toBe(`${WECHAT_API_BASE}/ilink/bot/sendmessage`);+ expect(body.msg.to_user_id).toBe(USER);+ expect(body.msg.context_token).toBe("ctx-7");+ expect(body.msg.message_type).toBe(2);+ expect(body.msg.message_state).toBe(2);+ // Exactly one item: the platform does not take a two-item list.+ expect(body.msg.item_list).toEqual([{ type: 1, text_item: { text: "hi" } }]);});it("omits the token entirely when none is known, rather than sending a blank one", async () => {- await withFetch(defaults, async (calls) => {- await client().sendText({ userId: USER, text: "hi" });- expect("context_token" in JSON.parse(calls[0]!.body).msg).toBe(false);- });+ const calls = stubWeChat();+ await client().sendText({ userId: USER, text: "hi" });+ expect("context_token" in JSON.parse(calls[0]!.body).msg).toBe(false);});it("uploads an image as ciphertext under a fresh key, then references the CDN's handle", async () => {- uploads = [];const plaintext = Buffer.from("PNG-ish bytes, long enough to need padding");- await withFetch(- (call) => {- if (call.url.endsWith("/getuploadurl")) {- return jsonResponse({ ret: 0, upload_full_url: "https://cdn.example/upload?sig=abc" });- }- if (call.url.startsWith("https://cdn.example/upload")) {- return new Response(null, {- status: 200,- headers: { "x-encrypted-param": "dl-param-1" },- });- }- return null;- },- async (calls) => {- await client().sendImage({- userId: USER,- text: "",- file: { fileName: "chart.png", data: plaintext },+ const calls = stubWeChat((call) => {+ if (call.url.endsWith("/getuploadurl")) {+ return jsonResponse({ ret: 0, upload_full_url: "https://cdn.example/upload?sig=abc" });+ }+ if (call.url.startsWith("https://cdn.example/upload")) {+ return new Response(null, {+ status: 200,+ headers: { "x-encrypted-param": "dl-param-1" },});- const handle = JSON.parse(calls[0]!.body);- expect(handle.media_type).toBe(1);- expect(handle.to_user_id).toBe(USER);- expect(handle.rawsize).toBe(plaintext.length);- expect(handle.rawfilemd5).toBe(createHash("md5").update(plaintext).digest("hex"));- // PKCS#7 pads to the next full block, always adding at least one byte.- expect(handle.filesize).toBe(Math.ceil((plaintext.length + 1) / 16) * 16);- // Nothing here has a thumbnail to make, and the platform only demands sizes for one- // that is being uploaded.- expect(handle.no_need_thumb).toBe(true);-- // The bytes on the wire are ciphertext, and the key the handle declared opens them:- // this is the pairing that fails silently if either half drifts.- const key = Buffer.from(handle.aeskey as string, "hex");- expect(key).toHaveLength(16);- const decipher = createDecipheriv("aes-128-ecb", key, null);- const round = Buffer.concat([decipher.update(uploads[0]!), decipher.final()]);- expect(round.equals(plaintext)).toBe(true);- expect(uploads[0]!.equals(plaintext)).toBe(false);-- const item = JSON.parse(calls[2]!.body).msg.item_list[0];- expect(item.type).toBe(2);- expect(item.image_item.media.encrypt_query_param).toBe("dl-param-1");- expect(Buffer.from(item.image_item.media.aes_key as string, "base64").equals(key)).toBe(- true,- );- },- );+ }+ return null;+ });+ await client().sendImage({+ userId: USER,+ text: "",+ file: { fileName: "chart.png", data: plaintext },+ });+ const handle = JSON.parse(calls[0]!.body);+ expect(handle.media_type).toBe(1);+ expect(handle.to_user_id).toBe(USER);+ expect(handle.rawsize).toBe(plaintext.length);+ expect(handle.rawfilemd5).toBe(createHash("md5").update(plaintext).digest("hex"));+ // PKCS#7 pads to the next full block, always adding at least one byte.+ expect(handle.filesize).toBe(Math.ceil((plaintext.length + 1) / 16) * 16);+ // Nothing here has a thumbnail to make, and the platform only demands sizes for one+ // that is being uploaded.+ expect(handle.no_need_thumb).toBe(true);++ // The bytes on the wire are ciphertext, and the key the handle declared opens them:+ // this is the pairing that fails silently if either half drifts.+ const key = Buffer.from(handle.aeskey as string, "hex");+ expect(key).toHaveLength(16);+ const decipher = createDecipheriv("aes-128-ecb", key, null);+ const round = Buffer.concat([decipher.update(calls[1]!.bytes), decipher.final()]);+ expect(round.equals(plaintext)).toBe(true);+ expect(Buffer.from(calls[1]!.bytes).equals(plaintext)).toBe(false);++ const item = JSON.parse(calls[2]!.body).msg.item_list[0];+ expect(item.type).toBe(2);+ expect(item.image_item.media.encrypt_query_param).toBe("dl-param-1");+ expect(Buffer.from(item.image_item.media.aes_key as string, "base64").equals(key)).toBe(true);});it("sends a file under the FILE media type, with its name and its PLAINTEXT length", async () => {- uploads = [];const bytes = Buffer.from("%PDF-1.7 ...");- await withFetch(- (call) => {- if (call.url.endsWith("/getuploadurl")) {- return jsonResponse({ upload_full_url: "https://cdn.example/upload" });- }- if (call.url.startsWith("https://cdn.example/upload")) {- return new Response(null, { status: 200, headers: { "x-encrypted-param": "dl-2" } });- }- return null;- },- async (calls) => {- await client().sendFile({- userId: USER,- text: "",- file: { fileName: "report.pdf", data: bytes },- });- expect(JSON.parse(calls[0]!.body).media_type).toBe(3);- const item = JSON.parse(calls[2]!.body).msg.item_list[0];- expect(item.type).toBe(4);- expect(item.file_item.file_name).toBe("report.pdf");- // The receiving client shows this number, and the ciphertext is a padding block- // longer than what the reader actually gets.- expect(item.file_item.len).toBe(String(bytes.length));- },- );+ const calls = stubWeChat((call) => {+ if (call.url.endsWith("/getuploadurl")) {+ return jsonResponse({ upload_full_url: "https://cdn.example/upload" });+ }+ if (call.url.startsWith("https://cdn.example/upload")) {+ return new Response(null, { status: 200, headers: { "x-encrypted-param": "dl-2" } });+ }+ return null;+ });+ await client().sendFile({+ userId: USER,+ text: "",+ file: { fileName: "report.pdf", data: bytes },+ });+ expect(JSON.parse(calls[0]!.body).media_type).toBe(3);+ const item = JSON.parse(calls[2]!.body).msg.item_list[0];+ expect(item.type).toBe(4);+ expect(item.file_item.file_name).toBe("report.pdf");+ // The receiving client shows this number, and the ciphertext is a padding block+ // longer than what the reader actually gets.+ expect(item.file_item.len).toBe(String(bytes.length));});it("sends a caption as its own message ahead of the picture", async () => {- uploads = [];- await withFetch(- (call) => {- if (call.url.endsWith("/getuploadurl")) {- return jsonResponse({ upload_full_url: "https://cdn.example/upload" });- }- if (call.url.startsWith("https://cdn.example/upload")) {- return new Response(null, { status: 200, headers: { "x-encrypted-param": "dl-3" } });- }- return null;- },- async (calls) => {- await client().sendImage({- userId: USER,- text: "here is the chart",- file: { fileName: "c.png", data: Buffer.from("x") },- });- // upload handle, CDN, caption, picture — the caption is a message of its own because- // one request carries one item.- expect(calls).toHaveLength(4);- expect(JSON.parse(calls[2]!.body).msg.item_list[0].text_item.text).toBe(- "here is the chart",- );- expect(JSON.parse(calls[3]!.body).msg.item_list[0].type).toBe(2);- },- );+ const calls = stubWeChat((call) => {+ if (call.url.endsWith("/getuploadurl")) {+ return jsonResponse({ upload_full_url: "https://cdn.example/upload" });+ }+ if (call.url.startsWith("https://cdn.example/upload")) {+ return new Response(null, { status: 200, headers: { "x-encrypted-param": "dl-3" } });+ }+ return null;+ });+ await client().sendImage({+ userId: USER,+ text: "here is the chart",+ file: { fileName: "c.png", data: Buffer.from("x") },+ });+ // upload handle, CDN, caption, picture — the caption is a message of its own because+ // one request carries one item.+ expect(calls).toHaveLength(4);+ expect(JSON.parse(calls[2]!.body).msg.item_list[0].text_item.text).toBe("here is the chart");+ expect(JSON.parse(calls[3]!.body).msg.item_list[0].type).toBe(2);});it("fails readably when the platform returns no upload URL, rather than guessing a CDN host", async () => {- await withFetch(- (call) => (call.url.endsWith("/getuploadurl") ? jsonResponse({ ret: 0 }) : null),- async () => {- await expect(- client().sendFile({- userId: USER,- text: "",- file: { fileName: "a.bin", data: Buffer.from("x") },- }),- ).rejects.toThrow(/upload URL was not returned/);- },- );+ stubWeChat((call) => (call.url.endsWith("/getuploadurl") ? jsonResponse({ ret: 0 }) : null));+ await expect(+ client().sendFile({+ userId: USER,+ text: "",+ file: { fileName: "a.bin", data: Buffer.from("x") },+ }),+ ).rejects.toThrow(/upload URL was not returned/);});});@@ -608,16 +499,14 @@ describe("the verdict a failure carries", () => {// `recovers` at those two capture points and nothing else. Asserted where the adapter decides// it rather than on a hand-built error, which would only prove the classifier reads a boolean.const failureOf = async (- answer: (call: Call) => Response | null,+ answer: (call: FetchCall) => Response | null,run: () => Promise<unknown>,): Promise<WeChatApiError> => {- let caught: unknown;- await withFetch(answer, async () => {- caught = await run().then(- () => null,- (e: unknown) => e,- );- });+ stubWeChat(answer);+ const caught = await run().then(+ () => null,+ (e: unknown) => e,+ );expect(caught).toBeInstanceOf(WeChatApiError);return caught as WeChatApiError;};@@ -683,86 +572,60 @@ describe("inbound media transfers", () => {}it("decrypts a download whose key arrived as raw base64", async () => {- await withFetch(- () => new Response(encrypted(), { status: 200 }),- async () => {- const bytes = await client().fetchMedia(- { url: "https://cdn/i?sig=secret", aesKey: KEY.toString("base64") },- 1_000_000,- "The image",- );- expect(bytes.equals(PLAIN)).toBe(true);- },+ stubWeChat(() => new Response(encrypted(), { status: 200 }));+ const bytes = await client().fetchMedia(+ { url: "https://cdn/i?sig=secret", aesKey: KEY.toString("base64") },+ 1_000_000,+ "The image",);+ expect(bytes.equals(PLAIN)).toBe(true);});it("decrypts one whose key arrived as base64 of its hex digits, which files and videos send", async () => {- await withFetch(- () => new Response(encrypted(), { status: 200 }),- async () => {- const bytes = await client().fetchMedia(- {- url: "https://cdn/f",- aesKey: Buffer.from(KEY.toString("hex"), "utf8").toString("base64"),- },- 1_000_000,- "The file",- );- expect(bytes.equals(PLAIN)).toBe(true);+ stubWeChat(() => new Response(encrypted(), { status: 200 }));+ const bytes = await client().fetchMedia(+ {+ url: "https://cdn/f",+ aesKey: Buffer.from(KEY.toString("hex"), "utf8").toString("base64"),},+ 1_000_000,+ "The file",);+ expect(bytes.equals(PLAIN)).toBe(true);});it("passes an unencrypted download through untouched", async () => {- await withFetch(- () => new Response(PLAIN, { status: 200 }),- async () => {- const bytes = await client().fetchMedia({ url: "https://cdn/i" }, 1_000_000, "The image");- expect(bytes.equals(PLAIN)).toBe(true);- },- );+ stubWeChat(() => new Response(PLAIN, { status: 200 }));+ const bytes = await client().fetchMedia({ url: "https://cdn/i" }, 1_000_000, "The image");+ expect(bytes.equals(PLAIN)).toBe(true);});it("refuses a transfer past the cap as a size problem, not a failure", async () => {- await withFetch(- () => new Response(Buffer.alloc(4096), { status: 200 }),- async () => {- const err = await client()- .fetchMedia({ url: "https://cdn/i" }, 1024, "The image")- .catch((e: unknown) => e);- expect(err).toBeInstanceOf(MessagingMediaTooLargeError);- },- );+ stubWeChat(() => new Response(Buffer.alloc(4096), { status: 200 }));+ const err = await client()+ .fetchMedia({ url: "https://cdn/i" }, 1024, "The image")+ .catch((e: unknown) => e);+ expect(err).toBeInstanceOf(MessagingMediaTooLargeError);});it("never puts the signed CDN URL into a failure the chat will read", async () => {// The URL embeds the parameter that authorizes the read.- await withFetch(- () => new Response("nope", { status: 403 }),- async () => {- const err = await client()- .fetchMedia({ url: "https://cdn/i?sig=SECRET-PARAM" }, 1_000_000, "The image")- .catch((e: unknown) => e);- expect((err as Error).message).toContain("The image");- expect((err as Error).message).not.toContain("SECRET-PARAM");- },- );+ stubWeChat(() => new Response("nope", { status: 403 }));+ const err = await client()+ .fetchMedia({ url: "https://cdn/i?sig=SECRET-PARAM" }, 1_000_000, "The image")+ .catch((e: unknown) => e);+ expect((err as Error).message).toContain("The image");+ expect((err as Error).message).not.toContain("SECRET-PARAM");});it("reports a payload that will not decrypt as arrived-but-unreadable", async () => {- await withFetch(+ stubWeChat(() => new Response(Buffer.from("not a multiple of the block size at all"), { status: 200 }),- async () => {- const err = await client()- .fetchMedia(- { url: "https://cdn/i", aesKey: KEY.toString("base64") },- 1_000_000,- "The image",- )- .catch((e: unknown) => e);- expect((err as Error).message).toBe("The image arrived but could not be decrypted");- },);+ const err = await client()+ .fetchMedia({ url: "https://cdn/i", aesKey: KEY.toString("base64") }, 1_000_000, "The image")+ .catch((e: unknown) => e);+ expect((err as Error).message).toBe("The image arrived but could not be decrypted");});});diff --git a/packages/server/test/messaging-wechat.test.ts b/packages/server/test/messaging-wechat.test.tsindex 4f2ee927..3d4581c2 100644--- a/packages/server/test/messaging-wechat.test.ts+++ b/packages/server/test/messaging-wechat.test.ts@@ -1,22 +1,34 @@/**- * WeChat messaging tests — the fourth channel's mirror of messaging.test.ts, over a fake- * transport (the wire itself is messaging-wechat-transport.test.ts's).+ * WeChat messaging — the fourth channel's mirror of messaging.test.ts, over a fake transport+ * (the wire itself is messaging-wechat-transport.test.ts's). No test opens a socket.*- * Two halves. The ordinary one repeats what the other channels already pin, because the- * route wiring is per-channel even where the behaviour is not: token masking, the bot id as- * the account identity and the enable-time 409 it collides on, the save/enable split, the- * channel-agnostic GET, the credential probe.+ * This channel has NO typed credential (it is bound by a scan), so its PUT carries+ * preferences alone, its test endpoint takes no body, and its inbound side is a long poll+ * whose FIRST answer is a drain, so a binding switched on after a week dark does not replay+ * that week as a task flood. Pictures and files travel both ways.*- * The half that only exists here follows from this channel having NO typed credential. Its- * PUT carries preferences alone and refuses to create a binding; its test endpoint takes no- * body; and its inbound side is a long poll whose FIRST answer is a drain, so a binding- * switched on after a week dark does not replay that week as a task flood. Media is the- * other difference worth its own tests: pictures and files travel in both directions here,- * which no other channel in this product manages.- *- * No test opens a socket.+ * - A stored config is narrowed (one missing a credential refused; no host means the entry+ * host); a reply anchor reads back to its chat; the poll backs off further after each+ * failure, up to a ceiling.+ * - The connector's seam carries text, images and files, downloading nothing until the bridge+ * asks.+ * - The GET masks the token and names the bot id as the account; the PUT saves preferences+ * only and never creates a binding; the clear flag drops the token, refused while connected;+ * saving never collides, enabling does; the probe reads the stored binding; the channel+ * joins the channel-agnostic read.+ * - The connection is ready before any poll answers; the drain runs until the platform+ * answers and never again on that connection, without spending itself on a silent window;+ * the first poll's backlog is dropped, keeping its cursor; a refused token stops the loop+ * with its own reason; a poll failure is one outage report, recovering on its own, and a+ * failure that recovers on its own does not silence the refusal behind it.+ * - An inbound message reaches the Agent and the reply goes back with the conversation token+ * (forgotten when the connection closes); the test message goes to the remembered chat; an+ * empty message gets the not-supported notice; a picture reaches the model as an image typed+ * from its bytes, a file as a path under the sender's name, an oversize one as a size+ * refusal; outbound, a picture goes as a picture and any other file as an attachment, and+ * Markdown renders only when the binding asks.*/-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";import { assistantText } from "@prismshadow/penguin-core";import type { OmniMessage } from "@prismshadow/penguin-core";import type {@@ -24,7 +36,6 @@ import type {WeChatBindingResponse,WeChatTestResponse,} from "../src/api/types.js";-import type { SessionRow } from "../src/db/repos/sessions.js";import type { RuntimeSession } from "../src/runtime/session-manager.js";import {MESSAGING_TEST_MESSAGE,@@ -49,11 +60,11 @@ import {wechatConfigOf,wechatRetryDelayMs,} from "../src/runtime/messaging/wechat-connector.js";+import { forwardingTo } from "./fixtures/forwarding.js";+import { fakeSession, sessionRow, uniqueSessionId } from "./fixtures/session.js";import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";import type { TestApp } from "./helpers.js";-const SID = "session-2026-08-28-11-00-00-w9100001";-const SID2 = "session-2026-08-28-11-00-01-w9100002";const BASE = (sid: string) => `/api/sessions/${sid}/messaging/wechat`;const PROJECT = "birder-default_project";@@ -229,34 +240,12 @@ function echoFakeSession(runs: InputPayload[][],reply = "Reply text",): RuntimeSession {- return {- sessionId,- toolPermission: () => "rw",- generateTitle: async () => ({ title: null, usage: null }),- compactability: () => "ok" as const,- steer: () => false,- skipReconnectWait: () => false,+ return fakeSession(sessionId, {async *run(input: OmniMessage[]) {runs.push(input.map((m) => m.payload as InputPayload));yield assistantText(reply);},- async *compact() {},- };-}--function sessionRowOf(sessionId: string, projectId: string): SessionRow {- return {- sessionId,- projectId,- agentId: "default_agent",- provider: "custom",- modelId: "m1",- workspace: "/tmp/w",- approvalMode: "allow-all",- title: null,- createdAt: new Date().toISOString(),- lastActiveAt: new Date().toISOString(),- };+ });}// ---------------------------------------------------------------------------@@ -282,9 +271,10 @@ describe("wechat config and reply refs", () => {});it("backs off further after each failure, up to a ceiling", () => {- expect(wechatRetryDelayMs(1)).toBe(2_000);- expect(wechatRetryDelayMs(2)).toBe(4_000);- expect(wechatRetryDelayMs(20)).toBe(60_000);+ expect(wechatRetryDelayMs(2)).toBeGreaterThan(wechatRetryDelayMs(1));+ expect(wechatRetryDelayMs(3)).toBeGreaterThan(wechatRetryDelayMs(2));+ // Past some number of failures the wait stops growing.+ expect(wechatRetryDelayMs(30)).toBe(wechatRetryDelayMs(20));});});@@ -331,6 +321,12 @@ describe("wechat binding routes and the long poll", () => {let api: ReturnType<typeof apiClient>;let fake: FakeWeChatTransport;let runs: InputPayload[][];+ /**+ * The case's two Sessions, fresh per case: the app is the describe's, and a binding, a poll+ * and a status belong to their Session.+ */+ let SID: string;+ let SID2: string;/** Store a scanned config as the scan route would, then flip the toggle on. */const bindEnabled = async (sid: string, config: Record<string, unknown> = SCANNED_CONFIG) => {@@ -344,20 +340,31 @@ describe("wechat binding routes and the long poll", () => {await waitFor(() => t.deps.messaging.statusOf(sid, "wechat").state === "connected");};- beforeEach(async () => {- fake = new FakeWeChatTransport();- runs = [];+ beforeAll(async () => {// A small non-zero backoff rather than zero: the loop retries in a tight cycle during// the outage test, and a zero delay would spin without yielding.- t = await createTestApp({ wechatTransport: fake, wechatRetryDelayMs: () => 5 });+ t = await createTestApp({+ wechatTransport: forwardingTo(() => fake),+ wechatRetryDelayMs: () => 5,+ });const { cookie } = await provisionUser(t.app, "birder");api = apiClient(t.app, cookie);- const row = sessionRowOf(SID, PROJECT);+ });+ afterAll(async () => {+ await t.cleanup();+ });+ beforeEach(() => {+ fake = new FakeWeChatTransport();+ runs = [];+ SID = uniqueSessionId();+ SID2 = uniqueSessionId();+ const row = sessionRow(SID, { projectId: PROJECT });t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row, echoFakeSession(SID, runs));});- afterEach(async () => {- await t.cleanup();+ afterEach(() => {+ // What the case bound goes with it, long poll and all.+ for (const row of t.deps.messagingRepo.listAll()) t.deps.messaging.unbindSession(row.sessionId);});// —— Routes ——————————————————————————————————————————————————————————————@@ -426,8 +433,8 @@ describe("wechat binding routes and the long poll", () => {});it("the bot id is the account: saving never collides, enabling does", async () => {- t.deps.sessionsRepo.insert(sessionRowOf(SID2, PROJECT));- t.deps.manager.adopt(sessionRowOf(SID2, PROJECT), echoFakeSession(SID2, []));+ t.deps.sessionsRepo.insert(sessionRow(SID2, { projectId: PROJECT }));+ t.deps.manager.adopt(sessionRow(SID2, { projectId: PROJECT }), echoFakeSession(SID2, []));await bindEnabled(SID);// The same bot saved on a second Session is fine; only the connection is exclusive.t.deps.messagingRepo.upsert({diff --git a/packages/server/test/messaging-wire.test.ts b/packages/server/test/messaging-wire.test.tsindex 8c402b5d..05816947 100644--- a/packages/server/test/messaging-wire.test.ts+++ b/packages/server/test/messaging-wire.test.ts@@ -1,36 +1,42 @@/**- * Protocol tests for the two messaging adapters, at the boundary each one actually calls:- * the Lark SDK's HTTP instance, and `fetch`.+ * Protocol tests for the two messaging adapters, at the boundary each one actually calls: the+ * Lark SDK's HTTP instance, and `fetch`. The suites next door substitute our own seams+ * (FeishuSdk, TelegramTransport), which proves the bridge drives the seam and nothing about+ * whether the adapter behind it speaks the real protocol; both shipped messaging bugs lived in+ * that gap. So the fake here is pushed one layer down, to the transport itself.*- * These exist because the suites next door could not have caught the two bugs that reached- * a user. Those suites substitute a hand-written implementation of *our own* seam- * (FeishuSdk, TelegramTransport), which proves the bridge drives the seam correctly and- * proves nothing whatever about whether the adapter behind it speaks the real protocol —- * every wire detail is stubbed out along with the wire. Both shipped bugs lived in that- * gap: an image download whose refusal reason was silently discarded, and an upload path no- * test had ever run against a real response shape.+ * Feishu, against the SDK's HTTP boundary (`createLarkSdk({ httpInstance })`, a stand-in for+ * axios that reproduces the SDK's response interceptor, so URL building, params, payloads and+ * unwrapping all run for real):+ * - A message image or file downloads from the resource endpoint, typed off its bytes (by the+ * header when they are not an image, PNG only as a last resort); past the cap it is a size+ * error.+ * - A refusal reports the API's own reason even when the error body is a stream, reads the+ * stream's own code and msg, and carries the scopes and the grant link out of it; a body+ * that is not a Feishu envelope falls back to the generic text.+ * - Every call has a deadline; a refused call is a FeishuApiError, a stalled one a plain Error.+ * - A card goes out as msg_type interactive (schema 2.0), through the send and the reply+ * endpoints alike.+ * - A picture is uploaded and its key sent as an image message; other files upload under the+ * category the client previews them by; an upload without a key names the file.*- * So the fake here is pushed down one layer, to the transport itself:- *- * - **Feishu**: `createLarkSdk({ httpInstance })` hands the real SDK a stand-in for axios,- * so the SDK's own URL building, `:path` filling, param serialization, payload formatting- * and response unwrapping all run for real. The stub must reproduce what the SDK's own- * response interceptor does to an axios response — return `resp.data` (the parsed body),- * or `{data, headers}` when the call asked for `$return_headers` — because that is the- * contract the SDK's generated methods are written against. Errors are thrown in axios's- * shape, `{response: {status, data}}`, and for a `responseType: "stream"` request the- * error body is a stream too, which is the whole of bug 1.- * - **Telegram**: the Bot API is plain HTTPS, so the stub is `globalThis.fetch`, and the- * assertions are on the URLs, the multipart field names and the error text.- *- * No test opens a socket.+ * Telegram, against `fetch` (the suite's fetch fake, handed to the transport's own seam):+ * - A photo downloads in two hops, getFile then the file endpoint, and no error ever carries+ * the bot token the download URL embeds; a file the API already reports over the cap is a+ * size error.+ * - parse_mode is on the wire only when the send asked for it.+ * - A failure carries the verdict the error table files it by: a poll or a send that never+ * completed, a flood wait, Telegram's own outage and a proxy's error page recover; a revoked+ * token, a chat that blocked the bot and a chat that is gone do not.+ * - A picture posts as multipart sendPhoto and other files as sendDocument, for real against a+ * loopback socket too; a refused upload surfaces the API's description.*/import { createServer } from "node:http";import type { AddressInfo } from "node:net";import { Readable } from "node:stream";import { Agent, getGlobalDispatcher, setGlobalDispatcher } from "undici";import type { Dispatcher } from "undici";-import { afterEach, describe, expect, it } from "vitest";+import { describe, expect, it } from "vitest";import { FeishuApiError, createLarkSdk } from "../src/runtime/messaging/feishu-sdk.js";import { feishuCardOf } from "../src/runtime/messaging/feishu-card.js";import { messagingErrorKind } from "../src/runtime/messaging/error-kind.js";@@ -46,6 +52,7 @@ import {MessagingMediaTooLargeError,MessagingPermissionError,} from "../src/runtime/messaging/media.js";+import { fakeFetch } from "./fixtures/fetch.js";const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x01, 0x02, 0x03]);const CREDS = { appId: "cli_wire", appSecret: "secret", baseDomain: "https://open.feishu.cn" };@@ -463,23 +470,15 @@ describe("telegram adapter against the fetch boundary", () => {const PHOTO = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0x11, 0x22]);const DOC = Buffer.from("hello from the workspace");- /** A recorded stub, handed to the transport through its own seam rather than to the global. */- interface FetchStub {- urls: string[];- bodies: unknown[];- transport: TelegramTransport;- }-- /** Records every request and answers by URL. */- function stubFetch(answer: (url: string) => Response | Promise<Response>): FetchStub {- const urls: string[] = [];- const bodies: unknown[] = [];- const fetchImpl = ((url: string | URL, init?: RequestInit) => {- urls.push(String(url));- bodies.push(init?.body);- return Promise.resolve(answer(String(url)));- }) as unknown as TelegramTransportOpts["fetch"];- return { urls, bodies, transport: createTelegramTransport({ fetch: fetchImpl }) };+ /** A transport over the suite's fetch fake, handed in through its own seam rather than the global. */+ function telegramOver(answer: (url: string) => Response | Promise<Response>) {+ const fake = fakeFetch((call) => answer(call.url));+ return {+ calls: fake.calls,+ transport: createTelegramTransport({+ fetch: fake.fetch as unknown as TelegramTransportOpts["fetch"],+ }),+ };}const okJson = (result: unknown): Response =>@@ -488,7 +487,7 @@ describe("telegram adapter against the fetch boundary", () => {});it("downloads a photo in two hops: getFile, then the FILE endpoint", async () => {- const stub = stubFetch((url) =>+ const stub = telegramOver((url) =>url.includes("/getFile")? okJson({ file_path: "photos/file_7.jpg", file_size: PHOTO.length }): new Response(PHOTO, { headers: { "content-type": "image/jpeg" } }),@@ -499,13 +498,13 @@ describe("telegram adapter against the fetch boundary", () => {expect(got.filePath).toBe("photos/file_7.jpg");// The second hop is /file/bot<token>/<path> — a different endpoint from the methods,// and the detail most easily got wrong.- expect(stub.urls[0]).toBe(`https://api.telegram.org/bot${TOKEN}/getFile`);- expect(stub.urls[1]).toBe(`https://api.telegram.org/file/bot${TOKEN}/photos/file_7.jpg`);+ expect(stub.calls[0]!.url).toBe(`https://api.telegram.org/bot${TOKEN}/getFile`);+ expect(stub.calls[1]!.url).toBe(`https://api.telegram.org/file/bot${TOKEN}/photos/file_7.jpg`);});it("never puts the bot token in an error, though the download URL embeds it", async () => {// Transport failure first.- const stub = stubFetch(() => {+ const stub = telegramOver(() => {throw Object.assign(new Error("fetch failed"), { cause: new Error("ECONNREFUSED") });});const bot = stub.transport.createClient({ botToken: TOKEN });@@ -516,7 +515,7 @@ describe("telegram adapter against the fetch boundary", () => {/SECRET-TOKEN-VALUE/,);// Then an HTTP failure on the file endpoint itself, whose URL carries the token.- const stub2 = stubFetch((url) =>+ const stub2 = telegramOver((url) =>url.includes("/getFile")? okJson({ file_path: "photos/f.jpg" }): new Response("nope", { status: 404 }),@@ -531,19 +530,19 @@ describe("telegram adapter against the fetch boundary", () => {});it("puts parse_mode on the wire only when the send asked for it", async () => {- const stub = stubFetch(() => okJson({ message_id: 1 }));+ const stub = telegramOver(() => okJson({ message_id: 1 }));const bot = stub.transport.createClient({ botToken: TOKEN });await bot.sendMessage({ chatId: "42", text: "<b>hi</b>", parseMode: "HTML" });// A fixed notice carries no markup and must go out verbatim, which means no field at all// rather than a field naming plain text.await bot.sendMessage({ chatId: "42", text: "plain notice" });- const bodies = stub.bodies.map((b) => JSON.parse(String(b)) as Record<string, unknown>);+ const bodies = stub.calls.map((c) => JSON.parse(c.body) as Record<string, unknown>);expect(bodies[0]).toEqual({ chat_id: 42, text: "<b>hi</b>", parse_mode: "HTML" });expect(bodies[1]).toEqual({ chat_id: 42, text: "plain notice" });});it("refuses a file the API already says is over the cap, as a size error", async () => {- const stub = stubFetch(() =>+ const stub = telegramOver(() =>okJson({ file_path: "photos/f.jpg", file_size: 30 * 1024 * 1024 }),);const bot = stub.transport.createClient({ botToken: TOKEN });@@ -553,8 +552,7 @@ describe("telegram adapter against the fetch boundary", () => {});it("posts a picture as multipart sendPhoto, and other files as sendDocument", async () => {- const stub = stubFetch(() => okJson({}));- const { urls, bodies } = stub;+ const stub = telegramOver(() => okJson({}));const bot = stub.transport.createClient({ botToken: TOKEN });await bot.sendPhoto({ chatId: "42424242", fileName: "chart.png", data: PHOTO });await bot.sendDocument({@@ -563,15 +561,16 @@ describe("telegram adapter against the fetch boundary", () => {data: Buffer.from("hi"),});- expect(urls[0]!.endsWith("/sendPhoto")).toBe(true);- expect(urls[1]!.endsWith("/sendDocument")).toBe(true);- const photo = bodies[0] as FormData;+ const [photoCall, docCall] = stub.calls;+ expect(photoCall!.url.endsWith("/sendPhoto")).toBe(true);+ expect(docCall!.url.endsWith("/sendDocument")).toBe(true);+ const photo = photoCall!.init?.body as FormData;// The field name is the API's, not ours, and the file must arrive with its name on it.expect(photo.get("chat_id")).toBe("42424242");const file = photo.get("photo") as File;expect(file.name).toBe("chart.png");expect(file.size).toBe(PHOTO.length);- const doc = bodies[1] as FormData;+ const doc = docCall!.init?.body as FormData;expect(doc.get("chat_id")).toBe("-1002233445566");expect((doc.get("document") as File).name).toBe("notes.md");});@@ -655,7 +654,7 @@ describe("telegram adapter against the fetch boundary", () => {headers: { "content-type": "application/json" },});const sendFailure = (answer: (url: string) => Response): Promise<unknown> =>- stubFetch(answer)+ telegramOver(answer).transport.createClient({ botToken: TOKEN }).sendMessage({ chatId: "1", text: "hi" }).then(@@ -674,7 +673,7 @@ describe("telegram adapter against the fetch boundary", () => {// The reported row: a poll that never completed is no refusal of Telegram's, and the// loop's next poll is the whole of the fix.- const poll = await stubFetch(tlsReset)+ const poll = await telegramOver(tlsReset).transport.createClient({ botToken: TOKEN }).getUpdates({ timeoutSec: 0, signal: new AbortController().signal }).then(@@ -704,7 +703,7 @@ describe("telegram adapter against the fetch boundary", () => {});it("surfaces a Bot API refusal of an upload with its description", async () => {- const stub = stubFetch(+ const stub = telegramOver(() =>new Response(JSON.stringify({ ok: false, description: "PHOTO_INVALID_DIMENSIONS", error_code: 400 }),diff --git a/packages/server/test/messaging.test.ts b/packages/server/test/messaging.test.tsindex 4a2da478..23472bd0 100644--- a/packages/server/test/messaging.test.ts+++ b/packages/server/test/messaging.test.ts@@ -1,34 +1,68 @@/**- * Messaging-binding tests, Feishu side (the Telegram connector's mirror suite is- * messaging-telegram.test.ts): the bind-by-enable model (saving is never exclusive,- * enabling is), the- * /api/sessions/:id/messaging/feishu routes (masking, secret keep-on-blank, the- * save/enable split — PUT persists credentials only, POST /state owns the connection —- * 409s, authz split, cascade on session delete), and the bridge's routing through a fake- * Feishu SDK — inbound text becomes an ordinary user task- * exactly as if typed in the composer (no marker, no special sender; queueIfBusy), an- * inbound image becomes the composer's `image_url` part (and a download that fails or- * exceeds the inline-image cap degrades to a notice instead of a half-message), an inbound- * FILE becomes the composer's other attachment shape — written into the Session scratchpad- * and named on the message text as an `[attached file: …]` line, under the server's own- * attachment caps, with a size refusal, a permission refusal and a transfer failure each- * answered by its own notice — anything else gets the bilingual not-supported reply,- * each completed assistant message- * mirrors on- * its own to the last known chat as soon as it completes (the run's first one threaded onto- * the inbound message in groups), the files the reply MENTIONED follow it (existing ones- * only, pictures as pictures, capped by count and by size, escapes refused by the Workspace- * file service, and whatever does not go out filed as an error record under the Project- * rather than announced in the chat), an approval_request sends the one-line notice behind- * whatever is already going out, a binding with `linePerMessage` set delivers a reply one- * message per non-blank line — paced, and with a refused message costing only itself — while- * an unset one is byte-for-byte the original single message, and a binding with- * `finalReplyOnly` set relays a run's last completed message alone, at the run's end, files- * included. No test opens real network.+ * Messaging bindings, Feishu side, and the bridge every channel shares (the Telegram, QQ and+ * WeChat suites mirror the per-channel wiring). The Feishu SDK is the suite's Feishu fake and+ * the Session a scripted one; no test opens a network connection.+ *+ * Helpers:+ * - A reply is chunked at newline boundaries under the channel's cap; split one message per+ * non-blank line (indentation and code blocks kept, CRLF read), the tail past the message cap+ * combined rather than dropped, the cap spent on outbound messages, chunks included.+ * - Media is typed by extension (SVG stays a file) and by its bytes over any header; a download+ * stops at the byte that crosses its cap, and a transfer dying mid-stream fails.+ * - Files that did not go out are filed one record per cause, naming every file once, scopes and+ * console links once, and staying under the recorder's cap by giving up names first.+ * - A reply's file mentions are found however they are phrased, never outside the Workspace,+ * in either spelling of a Windows path, deduplicated.+ *+ * Routes:+ * - GET reports unbound and disconnected before a save; a PUT saves credentials only (masked,+ * disabled; a blank secret keeps the stored one, the clear flag drops it); POST /state owns+ * the connection, and a save while enabled restarts it with the new credentials.+ * - Enabling is the binding: two Sessions may save one app, only one may enable it, a save+ * cannot re-point an enabled binding at an app enabled elsewhere, and a gone Session releases+ * its app.+ * - Non-members get 404; members read but cannot write. POST /test probes draft values falling+ * back to stored ones; /test-message needs a known chat. DELETE unbinds, and deleting the+ * Session cascades the binding away.+ *+ * The bridge:+ * - Inbound text starts an ordinary user Task, exactly as typed in the composer; the reply+ * mirrors back — in a group threaded onto the inbound message (the run's first message+ * only), web-initiated turns too, every completed assistant message on its own as it+ * completes, every chunk to the chat named when the delivery began.+ * - linePerMessage splits a reply one message per line (chunking over-long lines, combining+ * past the cap, a refused message costing only itself, paced, the approval notice waiting+ * behind the lines, notices never split, threading once); finalReplyOnly relays the run's last+ * message alone at its end (files following it); renderMarkdown sends a card, falls back to a+ * plain bubble on a refusal and never retries a card that may have landed; each option is+ * saved, defaulted and kept by an omitted field.+ * - A streamed compaction summary never reaches the chat; anything neither text, image nor+ * file gets the bilingual notice and starts nothing.+ * - An inbound image becomes an image_url part; a refused download names the channel's reason,+ * an oversize one the limit, a missing permission the scope and where to grant it; imagery+ * is bounded per binding. An inbound file lands in the scratchpad as a path line under the+ * same rules; a redelivered image or file is dropped before any download; a nameless file+ * gets a placeholder name. Several files in one message attach in order, compose with text+ * and an image, return with a withdrawn follow-up, and are refused whole past the total.+ * - An approval request sends the waiting notice. The files a reply mentions follow it+ * (pictures as pictures, a file the run wrote, never an escape or a missing file), capped by+ * count and size, and whatever does not go out is filed under the Project — never announced+ * in the chat.+ * - Mentions resolve to names with this bot's own dropped (longest placeholder first, a real+ * message never emptied, a mention-only message starting nothing); connecting never waits on+ * the bot-identity lookup.+ * - The status reports the last arrival (reset on re-enable and on a credential save, stamped+ * for messages it cannot act on), the last connection failure (ignoring a superseded+ * attempt's), a reply that never went out, and a Task that could not start.+ * - A redelivered message starts one Task (a genuine repeat still runs twice); the watermark is+ * bounded, survives a server and a connector restart, is not moved by a message without an+ * id or one whose Task never started, and is dropped with the chat on a re-save to another+ * bot; a redelivery leaves the arrival stamp alone.+ * - The session list marks a Session bound on any channel.*/import fs from "node:fs/promises";import path from "node:path";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";import {assistantText,approvalDecision,@@ -40,8 +74,9 @@ import {toolCall,} from "@prismshadow/penguin-core";import type { ApproveFn, OmniMessage } from "@prismshadow/penguin-core";+import { wire } from "@prismshadow/penguin-core/kernel";import type { FeishuBindingResponse, FeishuTestResponse } from "../src/api/types.js";-import type { SessionRow } from "../src/db/repos/sessions.js";+import { ProjectsRepo } from "../src/db/repos/projects.js";import type { RuntimeSession } from "../src/runtime/session-manager.js";import { INLINE_IMAGE_MAX_BYTES, toAttachmentLimits } from "../src/services/attachment-limits.js";import { MESSAGE_MAX } from "../src/runtime/error-recorder.js";@@ -77,7 +112,6 @@ import type {} from "../src/runtime/messaging/connector.js";import { messagingErrorKind } from "../src/runtime/messaging/error-kind.js";import { FeishuConnector } from "../src/runtime/messaging/feishu-connector.js";-import type { FeishuCard } from "../src/runtime/messaging/feishu-card.js";import { FeishuApiError } from "../src/runtime/messaging/feishu-sdk.js";import {MessagingPermissionError,@@ -88,304 +122,15 @@ import {sniffImageMime,} from "../src/runtime/messaging/media.js";import { replyFileMentions } from "../src/runtime/messaging/reply-files.js";-import type {- FeishuApiClient,- FeishuCredentials,- FeishuEventHandlers,- FeishuImageData,- FeishuInboundEvent,- FeishuSdk,-} from "../src/runtime/messaging/feishu-sdk.js";+import { FILE_BYTES, FakeFeishuSdk, IMAGE_BYTES, oneChunk } from "./fixtures/feishu.js";+import type { SentMedia } from "./fixtures/feishu.js";+import { forwardingTo } from "./fixtures/forwarding.js";+import { fakeSession, sessionRow, uniqueSessionId } from "./fixtures/session.js";import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";import type { TestApp, TestAppOptions } from "./helpers.js";-const SID = "session-2026-08-25-10-00-00-fe15aa01";-const SID2 = "session-2026-08-25-10-00-01-fe15aa02";const BASE = (sid: string) => `/api/sessions/${sid}/messaging/feishu`;-// ----------------------------------------------------------------------------// Fake SDK: records every client call and hands inbound events back to the connector.-// -----------------------------------------------------------------------------interface SentText {- kind: "send" | "reply";- target: string;- text: string;-}--/**- * One picture or attachment that reached the channel. Byte count rather than the bytes:- * what the assertions care about is which file went where, in what order, and that the- * caps let it through.- */-interface SentMedia {- kind: "image" | "file";- target: string;- fileName: string;- bytes: number;-}--/** Everything one client sent, in order — the ordering of text against media is the point. */-type Sent = SentText | SentMedia;--/** One resource download the bridge asked for, cap included (the fake stands in for the SDK adapter). */-interface ImageFetch {- messageId: string;- fileKey: string;- maxBytes: number;-}--/** The rich-text content out of a card, which is the whole of what a card carries here. */-function cardContent(card: FeishuCard): string {- const element = card.body.elements[0];- if (card.schema !== "2.0" || element?.tag !== "markdown") {- throw new Error(`unexpected card envelope: ${JSON.stringify(card)}`);- }- return element.content;-}--/** The bytes as a stream, so the fakes read them through the real capped reader. */-async function* oneChunk(bytes: Buffer): AsyncGenerator<Uint8Array> {- yield bytes;-}--/** A PNG's magic bytes plus a little payload: enough for a data URL to be asserted verbatim. */-const IMAGE_BYTES = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x01, 0x02, 0x03]);--/** An inbound file's contents — text, so a failed write shows up as the wrong bytes on disk. */-const FILE_BYTES = Buffer.from("quarterly revenue: 42\n", "utf8");--class FakeClient implements FeishuApiClient {- readonly sends: Sent[] = [];- /**- * The card sends specifically, as the rich-text content they carried.- *- * A card is ALSO recorded in `sends` as an ordinary text send, so the routing, ordering- * and threading assertions read the same whichever transport carried the message — those- * are what they are about. This list is what separates the two, and it is what a test- * asserting the plain path checks is empty.- */- readonly cards: SentText[] = [];- /** When each send was recorded, parallel to `sends`: what the pacing test measures. */- readonly sentAt: number[] = [];- readonly imageFetches: ImageFetch[] = [];- readonly fileFetches: ImageFetch[] = [];- checks = 0;- constructor(- readonly creds: FeishuCredentials,- private readonly sdk: FakeSdk,- ) {}- async checkCredentials(): Promise<null> {- this.checks++;- if (this.sdk.failCheck !== null) throw new Error(this.sdk.failCheck);- return null;- }- async sendText(chatId: string, text: string): Promise<void> {- if (this.sdk.failSendWith !== null) throw this.sdk.failSendWith;- if (this.sdk.failSend !== null) throw new Error(this.sdk.failSend);- this.sdk.noteSend();- this.record({ kind: "send", target: chatId, text });- await this.sdk.hold();- }- async replyText(messageId: string, text: string): Promise<void> {- this.sdk.noteSend();- this.record({ kind: "reply", target: messageId, text });- await this.sdk.hold();- }- async sendCard(chatId: string, card: FeishuCard): Promise<void> {- // The typed failures fire on a card exactly as they do on a text bubble: Feishu refuses a- // missing scope on EVERY send, whatever the msg_type, so a fake that let a card through- // would make the card path quietly immune to the failure the text path is asserted on.- if (this.sdk.failSendWith !== null) throw this.sdk.failSendWith;- if (this.sdk.failCard !== null) throw this.sdk.failCard;- if (this.sdk.failSend !== null) throw new Error(this.sdk.failSend);- this.sdk.noteSend();- this.recordCard({ kind: "send", target: chatId, text: cardContent(card) });- await this.sdk.hold();- }- async replyCard(messageId: string, card: FeishuCard): Promise<void> {- if (this.sdk.failSendWith !== null) throw this.sdk.failSendWith;- if (this.sdk.failCard !== null) throw this.sdk.failCard;- this.sdk.noteSend();- this.recordCard({ kind: "reply", target: messageId, text: cardContent(card) });- await this.sdk.hold();- }- private recordCard(sent: SentText): void {- this.cards.push(sent);- this.record(sent);- }- private record(sent: SentText): void {- this.sends.push(sent);- this.sentAt.push(Date.now());- }- async botOpenId(): Promise<string | null> {- this.sdk.botIdentityLookups++;- // A stalled endpoint: the TCP connection is accepted and the answer never comes.- if (this.sdk.stallBotOpenId) return new Promise<never>(() => {});- return this.sdk.botOpenId;- }- async fetchMessageImage(args: ImageFetch): Promise<FeishuImageData> {- this.imageFetches.push(args);- if (this.sdk.failImageFetchWith !== null) throw this.sdk.failImageFetchWith;- if (this.sdk.failImageFetch !== null) throw new Error(this.sdk.failImageFetch);- // The cap is enforced through the REAL machinery the adapter uses, not a hand-written- // imitation of it: a fake free to throw its own error shape is a fake free to disagree- // with production about which failure this is (it did, once).- const data = await collectUnderCap(oneChunk(this.sdk.imageBytes), args.maxBytes, "The image");- return { data, mimeType: "image/png" };- }- async fetchMessageFile(args: ImageFetch): Promise<Buffer> {- this.fileFetches.push(args);- if (this.sdk.failFileFetchWith !== null) throw this.sdk.failFileFetchWith;- if (this.sdk.failFileFetch !== null) throw new Error(this.sdk.failFileFetch);- // Through the REAL capped reader, for the reason fetchMessageImage gives.- return collectUnderCap(oneChunk(this.sdk.fileBytes), args.maxBytes, "The file");- }- async sendImage(chatId: string, file: { fileName: string; data: Buffer }): Promise<void> {- this.sdk.failMediaSendOnce();- this.sends.push({- kind: "image",- target: chatId,- fileName: file.fileName,- bytes: file.data.length,- });- }- async sendFile(chatId: string, file: { fileName: string; data: Buffer }): Promise<void> {- this.sdk.failMediaSendOnce();- this.sends.push({- kind: "file",- target: chatId,- fileName: file.fileName,- bytes: file.data.length,- });- }-}--class FakeConnection {- closed = false;- constructor(- readonly creds: FeishuCredentials,- readonly handlers: FeishuEventHandlers,- ) {}- close(): void {- this.closed = true;- }- fire(evt: FeishuInboundEvent): Promise<void> {- return Promise.resolve(this.handlers.onMessage(evt));- }-}--class FakeSdk implements FeishuSdk {- readonly clients: FakeClient[] = [];- readonly connections: FakeConnection[] = [];- /** Non-null makes checkCredentials throw with this message. */- failCheck: string | null = null;- /** Non-null makes the send with this 1-based number (counted across clients) throw. */- failSendAt: number | null = null;- /** Non-null parks every send on this promise, holding the bridge's send chain open. */- heldSends: Promise<void> | null = null;- private sendCount = 0;- /** Every send passes here first: it counts, and throws for the one a test marked. */- noteSend(): void {- this.sendCount += 1;- if (this.sendCount === this.failSendAt) throw new Error("Too Many Requests: retry after 5");- }- /** Awaited after each send: instant unless a test is holding sends open. */- hold(): Promise<void> {- return this.heldSends ?? Promise.resolve();- }- /** What `/open-apis/bot/v3/info` reports for this app; null = the identity is unavailable. */- botOpenId: string | null = null;- /** Makes that lookup never answer, so a test can prove connect() does not wait on it. */- stallBotOpenId = false;- /** Lookups the connector has started (one per connection, off the connect path). */- botIdentityLookups = 0;- /** Non-null makes every outbound sendText throw with this message. */- failSend: string | null = null;- /** Non-null makes every outbound sendText throw THIS — for the failure shapes that carry data. */- failSendWith: Error | null = null;- /**- * Non-null makes every CARD send throw this, leaving the plain text sends working — the- * shape of a channel that refuses a rendering and accepts the message behind it.- */- failCard: Error | null = null;- /**- * Non-null holds every createClient until it resolves, which is what makes the bridge's- * one await between reading the binding row and its first send observable to a test.- */- createClientGate: Promise<void> | null = null;- /** How many createClient calls the gate has held. */- gated = 0;- /** Non-null makes fetchMessageImage throw with this message (a dead image_key, a network fault). */- failImageFetch: string | null = null;- /** Non-null makes it throw THIS — for the failure shapes that carry data, not just text. */- failImageFetchWith: Error | null = null;- /** What an image download resolves to; oversize bytes exercise the cap. */- imageBytes: Buffer = IMAGE_BYTES;- /** Non-null makes fetchMessageFile throw with this message (a dead file_key, a network fault). */- failFileFetch: string | null = null;- /** Non-null makes it throw THIS — for the failure shapes that carry data, not just text. */- failFileFetchWith: Error | null = null;- /** What a file download resolves to; oversize bytes exercise the cap. */- fileBytes: Buffer = FILE_BYTES;- /** Fails this many upcoming outbound image/file sends (the channel refusing an upload). */- failMediaSends = 0;- /** Non-null makes EVERY media send throw this — for the failure shapes that carry data. */- failMediaSendWith: Error | null = null;- /** Consumes one scheduled media-send failure, throwing when there is one. */- failMediaSendOnce(): void {- if (this.failMediaSendWith !== null) throw this.failMediaSendWith;- if (this.failMediaSends > 0) {- this.failMediaSends -= 1;- throw new Error("upload rejected");- }- }- async createClient(creds: FeishuCredentials): Promise<FeishuApiClient> {- if (this.createClientGate !== null) {- this.gated++;- await this.createClientGate;- }- const client = new FakeClient(creds, this);- this.clients.push(client);- return client;- }- async connect(creds: FeishuCredentials, handlers: FeishuEventHandlers): Promise<FakeConnection> {- const conn = new FakeConnection(creds, handlers);- this.connections.push(conn);- handlers.onReady?.();- return conn;- }- /** Everything sent through any client, in order (texts and media interleaved). */- allSends(): Sent[] {- return this.clients.flatMap((c) => c.sends);- }- /** Their timestamps, in the same order. */- allSentAt(): number[] {- return this.clients.flatMap((c) => c.sentAt);- }- /** Just the text messages — for the assertions that read `.text`. */- allTexts(): SentText[] {- return this.allSends().filter((s): s is SentText => s.kind === "send" || s.kind === "reply");- }- /** Only the messages that went out as an interactive card, across every client. */- allCards(): SentText[] {- return this.clients.flatMap((c) => c.cards);- }- /** Every image download asked of any client, in order. */- allImageFetches(): ImageFetch[] {- return this.clients.flatMap((c) => c.imageFetches);- }- /** Every file download asked of any client, in order. */- allFileFetches(): ImageFetch[] {- return this.clients.flatMap((c) => c.fileFetches);- }- lastConnection(): FakeConnection {- const conn = this.connections.at(-1);- if (!conn) throw new Error("no fake connection was opened");- return conn;- }-}-/*** One input part as the fake Sessions record it. Deliberately a loose shape rather than* core's payload union: a run's input mixes composer text with `image_url` parts, and the@@ -404,30 +149,17 @@ function echoFakeSession(runs: InputPayload[][],reply = "Reply text",): RuntimeSession {- return {- sessionId,- toolPermission: () => "rw",- generateTitle: async () => ({ title: null, usage: null }),- compactability: () => "ok" as const,- steer: () => false,- skipReconnectWait: () => false,+ return fakeSession(sessionId, {async *run(input: OmniMessage[]) {runs.push(input.map((m) => m.payload as InputPayload));yield assistantText(reply);},- async *compact() {},- };+ });}/** Fake Session that parks on one approval per run (drives an approval_request event). */function parkingFakeSession(sessionId: string): RuntimeSession {- return {- sessionId,- toolPermission: () => "rw",- generateTitle: async () => ({ title: null, usage: null }),- compactability: () => "ok" as const,- steer: () => false,- skipReconnectWait: () => false,+ return fakeSession(sessionId, {async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {const tc = toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-feishu" });yield tc;@@ -435,8 +167,7 @@ function parkingFakeSession(sessionId: string): RuntimeSession {yield approvalDecision(decision, "tc-feishu");yield assistantText("after approval");},- async *compact() {},- };+ });}/**@@ -449,21 +180,14 @@ function multiMessageFakeSession(texts: readonly string[],gate?: Promise<void>,): RuntimeSession {- return {- sessionId,- toolPermission: () => "rw",- generateTitle: async () => ({ title: null, usage: null }),- compactability: () => "ok" as const,- steer: () => false,- skipReconnectWait: () => false,+ return fakeSession(sessionId, {async *run() {for (let i = 0; i < texts.length; i += 1) {if (gate !== undefined && i === texts.length - 1) await gate;yield assistantText(texts[i]!);}},- async *compact() {},- };+ });}/**@@ -471,56 +195,27 @@ function multiMessageFakeSession(* window in which a notice could overtake the reply's still-unsent messages.*/function replyThenApprovalFakeSession(sessionId: string, text: string): RuntimeSession {- return {- sessionId,- toolPermission: () => "rw",- generateTitle: async () => ({ title: null, usage: null }),- compactability: () => "ok" as const,- steer: () => false,- skipReconnectWait: () => false,+ return fakeSession(sessionId, {async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {yield assistantText(text);const tc = toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-lines" });yield tc;yield approvalDecision(await opts.approve(tc), "tc-lines");},- async *compact() {},- };+ });}/** Fake Session that streams a compaction summary mid-run, then the actual answer. */function compactingFakeSession(sessionId: string): RuntimeSession {const bounds = { reason: "context", mode: "summarize" } as const;- return {- sessionId,- toolPermission: () => "rw",- generateTitle: async () => ({ title: null, usage: null }),- compactability: () => "ok" as const,- steer: () => false,- skipReconnectWait: () => false,+ return fakeSession(sessionId, {async *run() {yield compactionBegin({ ...bounds, context: 90, turns: 12 });yield assistantText("SUMMARY that is not a reply");yield compactionEnd({ ...bounds, status: "completed" });yield assistantText("the actual answer");},- async *compact() {},- };-}--function sessionRowOf(sessionId: string, projectId: string): SessionRow {- return {- sessionId,- projectId,- agentId: "default_agent",- provider: "custom",- modelId: "m1",- workspace: "/tmp/w",- approvalMode: "allow-all",- title: null,- createdAt: new Date().toISOString(),- lastActiveAt: new Date().toISOString(),- };+ });}const PUT_BODY = {@@ -578,11 +273,6 @@ describe("splitReplyLines", () => {expect(splitReplyLines(lines.slice(0, 5).join("\n"), 5)).toEqual(lines.slice(0, 5));});- it("defaults to the documented per-reply message cap", () => {- const lines = Array.from({ length: MESSAGING_MAX_LINE_MESSAGES + 5 }, (_, i) => `l${i}`);- expect(splitReplyLines(lines.join("\n"))).toHaveLength(MESSAGING_MAX_LINE_MESSAGES);- });-it("spends the cap on outbound MESSAGES, chunking included", () => {// An ordinary long answer: every line sits well under the size cap, but the combined// tail does not, so counting bodies would promise 20 messages and send 25 — past the@@ -904,9 +594,22 @@ describe("replyFileMentions", () => {describe("messaging binding routes and bridge", () => {let t: TestApp;let api: ReturnType<typeof apiClient>;- let fake: FakeSdk;- let projectId: string;+ let fake: FakeFeishuSdk;let runs: InputPayload[][];+ /**+ * The case's Project and its two Sessions, fresh per case: the app is the describe's, a+ * binding, a run and a status belong to their Session, and the error log dedupes and reads+ * per Project. The Project is birder's row alone — every Session here is a fake, so nothing+ * opens a default Agent's tree.+ */+ let projectId: string;+ let SID: string;+ let SID2: string;+ let cases = 0;+ /** The describe's app, with birder signed in; a case that needs other tuning boots its own. */+ let shared: TestApp;+ let sharedApi: ReturnType<typeof apiClient>;+ let own: TestApp | null = null;/** Save credentials, then flip the toggle on — the two-step flow the flow tests need. */const bindEnabled = async (sid: string, body: Record<string, unknown> = PUT_BODY) => {@@ -932,22 +635,51 @@ describe("messaging binding routes and bridge", () => {errors: t.deps.errors,});- /** The suite's app, rebuildable: the pacing test needs one whose per-line wait is not zero. */- const boot = async (opts: TestAppOptions = {}) => {- fake = new FakeSdk();- t = await createTestApp({ feishuSdk: fake, ...opts });- const { cookie } = await provisionUser(t.app, "birder");- api = apiClient(t.app, cookie);- projectId = "birder-default_project";+ /** Points the case at `app`: its own Project and Session ids, SID adopted as an echoing Session. */+ const enter = (app: TestApp, client: ReturnType<typeof apiClient>) => {+ t = app;+ api = client;runs = [];- const row = sessionRowOf(SID, projectId);+ cases += 1;+ projectId = `birder-case-${cases}`;+ wire(ProjectsRepo, { db: app.deps.db }).insert({+ projectId,+ ownerUserId: "birder",+ createdAt: new Date().toISOString(),+ });+ SID = uniqueSessionId();+ SID2 = uniqueSessionId();+ const row = sessionRow(SID, { projectId });t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row, echoFakeSession(SID, runs));};- beforeEach(() => boot());+ /** An app of the case's own, for tuning the shared one does not have (a per-line pace, an image budget). */+ const boot = async (opts: TestAppOptions) => {+ fake = new FakeFeishuSdk();+ own = await createTestApp({ feishuSdk: fake, ...opts });+ enter(own, apiClient(own.app, (await provisionUser(own.app, "birder")).cookie));+ };++ beforeAll(async () => {+ shared = await createTestApp({ feishuSdk: forwardingTo(() => fake) });+ sharedApi = apiClient(shared.app, (await provisionUser(shared.app, "birder")).cookie);+ });+ afterAll(async () => {+ await shared.cleanup();+ });+ beforeEach(() => {+ fake = new FakeFeishuSdk();+ enter(shared, sharedApi);+ });afterEach(async () => {- await t.cleanup();+ await own?.cleanup();+ own = null;+ // What the case bound goes with it, connection and all, and so does the error log it wrote.+ for (const row of shared.deps.messagingRepo.listAll()) {+ shared.deps.messaging.unbindSession(row.sessionId);+ }+ shared.deps.db.prepare("DELETE FROM error_records").run();});it("GET reports unbound + disconnected before any PUT", async () => {@@ -1064,7 +796,7 @@ describe("messaging binding routes and bridge", () => {});it("enabling is the binding: two Sessions may save one app, only one may have it enabled", async () => {- t.deps.sessionsRepo.insert(sessionRowOf(SID2, projectId));+ t.deps.sessionsRepo.insert(sessionRow(SID2, { projectId }));// Saving the same app on a second Session is not a conflict at all — each keeps its own// stored config, and neither of them is connected by a save.expect((await api.put(BASE(SID), PUT_BODY)).status).toBe(200);@@ -1105,7 +837,7 @@ describe("messaging binding routes and bridge", () => {});it("a save cannot re-point an ENABLED binding at an app another Session has enabled", async () => {- t.deps.sessionsRepo.insert(sessionRowOf(SID2, projectId));+ t.deps.sessionsRepo.insert(sessionRow(SID2, { projectId }));// Two Sessions, each connected to its own app. Exclusivity holds so far.await bindEnabled(SID);await bindEnabled(SID2, { appId: "cli_app_second", appSecret: PUT_BODY.appSecret });@@ -1138,7 +870,7 @@ describe("messaging binding routes and bridge", () => {});it("an enabled binding whose Session is gone releases its app to the next enable", async () => {- t.deps.sessionsRepo.insert(sessionRowOf(SID2, projectId));+ t.deps.sessionsRepo.insert(sessionRow(SID2, { projectId }));await bindEnabled(SID);// Deleting a Project or an Agent removes its Sessions without sweeping their bindings,// so the row stays behind holding the app. Until boot reconciles it, the refusal it@@ -1158,11 +890,14 @@ describe("messaging binding routes and bridge", () => {it("authz: non-members get 404; a member reads but cannot write or toggle (owner-only)", async () => {await api.put(BASE(SID), PUT_BODY);- const outsider = apiClient(t.app, (await provisionUser(t.app, "outsider")).cookie);+ // Accounts of this attempt's own: the app outlives the case, and a retry would find+ // fixed names taken.+ const suffix = SID.slice(-8);+ const outsider = apiClient(t.app, (await provisionUser(t.app, `outsider_${suffix}`)).cookie);expect((await outsider.get(BASE(SID))).status).toBe(404);- const mate = await provisionUser(t.app, "mate");- await api.post(`/api/projects/${projectId}/members`, { userId: "mate" });+ const mate = await provisionUser(t.app, `mate_${suffix}`);+ await api.post(`/api/projects/${projectId}/members`, { userId: `mate_${suffix}` });const member = apiClient(t.app, mate.cookie);expect((await member.get(BASE(SID))).status).toBe(200);expect((await member.put(BASE(SID), PUT_BODY)).status).toBe(403);@@ -1287,7 +1022,7 @@ describe("messaging binding routes and bridge", () => {});it("relays every completed assistant message on its own, as it completes, never joined", async () => {- const row2 = sessionRowOf(SID2, projectId);+ const row2 = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row2);let release = () => {};const gate = new Promise<void>((r) => {@@ -1323,7 +1058,7 @@ describe("messaging binding routes and bridge", () => {});it("in a group only the run's first message threads onto the inbound one", async () => {- const row2 = sessionRowOf(SID2, projectId);+ const row2 = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row2);t.deps.manager.adopt(row2, multiMessageFakeSession(SID2, ["first", "second", "third"]));await bindEnabled(SID2, { ...PUT_BODY, appId: "cli_grouped" });@@ -1348,7 +1083,7 @@ describe("messaging binding routes and bridge", () => {// A reply long enough to chunk, so the first chunk (which threads onto the inbound// message) and the rest (plain sends to the stored chat) can disagree at all.const long = `${"a".repeat(3000)}\n${"b".repeat(3000)}`;- const row2 = sessionRowOf(SID2, projectId);+ const row2 = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row2);t.deps.manager.adopt(row2, echoFakeSession(SID2, [], long));await bindEnabled(SID2, { ...PUT_BODY, appId: "cli_snapshot" });@@ -1405,7 +1140,7 @@ describe("messaging binding routes and bridge", () => {* between the two options has its own case below.*/const bindReplying = async (text: string, put: Record<string, unknown>) => {- const row2 = sessionRowOf(SID2, projectId);+ const row2 = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row2);t.deps.manager.adopt(row2, multiMessageFakeSession(SID2, [text]));await bindEnabled(SID2, { ...PUT_BODY, renderMarkdown: false, ...put });@@ -1491,7 +1226,6 @@ describe("messaging binding routes and bridge", () => {it("paces the messages of a per-line reply instead of firing them back to back", async () => {// The pace is a real wait, so this one test runs on an app with a short one; the rest of// the suite collapses it to zero.- await t.cleanup();await boot({ messagingLineDelayMs: 40 });await bindReplying(SPOKEN, { appId: "cli_lines_paced", linePerMessage: true });await messageBot("oc_paced");@@ -1503,7 +1237,7 @@ describe("messaging binding routes and bridge", () => {});it("the approval notice waits behind the reply rather than landing between its lines", async () => {- const row2 = sessionRowOf(SID2, projectId);+ const row2 = sessionRow(SID2, { projectId });row2.approvalMode = "always-ask";t.deps.sessionsRepo.insert(row2);t.deps.manager.adopt(row2, replyThenApprovalFakeSession(SID2, SPOKEN));@@ -1604,7 +1338,7 @@ describe("messaging binding routes and bridge", () => {/** SID2 running one multi-message run, bound and connected. `gate` holds its LAST message. */const bindThinkingAloud = async (put: Record<string, unknown>, gate?: Promise<void>) => {- const row2 = sessionRowOf(SID2, projectId);+ const row2 = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row2);t.deps.manager.adopt(row2, multiMessageFakeSession(SID2, THINKING_ALOUD, gate));await bindEnabled(SID2, { ...PUT_BODY, ...put });@@ -1671,7 +1405,7 @@ describe("messaging binding routes and bridge", () => {});it("with linePerMessage too, the final reply is the one split per line", async () => {- const row2 = sessionRowOf(SID2, projectId);+ const row2 = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row2);t.deps.manager.adopt(row2, multiMessageFakeSession(SID2, ["a note held back", SPOKEN]));await bindEnabled(SID2, {@@ -1696,7 +1430,7 @@ describe("messaging binding routes and bridge", () => {});it("the approval notice is not an assistant message: it arrives while the run is held", async () => {- const row2 = sessionRowOf(SID2, projectId);+ const row2 = sessionRow(SID2, { projectId });row2.approvalMode = "always-ask";t.deps.sessionsRepo.insert(row2);t.deps.manager.adopt(row2, replyThenApprovalFakeSession(SID2, "the answer"));@@ -1824,7 +1558,7 @@ describe("messaging binding routes and bridge", () => {});it("the streamed compaction summary is not a reply and never reaches the chat", async () => {- const row2 = sessionRowOf(SID2, projectId);+ const row2 = sessionRow(SID2, { projectId });t.deps.sessionsRepo.insert(row2);t.deps.manager.adopt(row2, compactingFakeSession(SID2));await bindEnabled(SID2, { ...PUT_BODY, appId: "cli_compactor" });@@ -2201,7 +1935,7 @@ describe("messaging binding routes and bridge", () => {});it("an approval_request sends the waiting-for-approval notice", async () => {- const row2 = sessionRowOf(SID2, projectId);+ const row2 = sessionRow(SID2, { projectId });row2.approvalMode = "always-ask";t.deps.sessionsRepo.insert(row2);t.deps.manager.adopt(row2, parkingFakeSession(SID2));@@ -2243,7 +1977,7 @@ describe("messaging binding routes and bridge", () => {});t.deps.messagingRepo.setEnabled(SID, "feishu", true);// A saved-but-disabled binding keeps its credentials and stays dark across restarts.- t.deps.sessionsRepo.insert(sessionRowOf(SID2, projectId));+ t.deps.sessionsRepo.insert(sessionRow(SID2, { projectId }));t.deps.messagingRepo.upsert({sessionId: SID2,channel: "feishu",@@ -2678,7 +2412,7 @@ describe("messaging binding routes and bridge", () => {reply: string,appId: string,): Promise<void> => {- const row = sessionRowOf(SID2, projectId);+ const row = sessionRow(SID2, { projectId });row.workspace = workspace;t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row, echoFakeSession(SID2, runs, reply));@@ -3154,7 +2888,7 @@ describe("messaging binding routes and bridge", () => {const ws = await makeWorkspace();await fs.writeFile(path.join(ws, "draft.md"), "wip");await fs.writeFile(path.join(ws, "final.md"), "done");- const row = sessionRowOf(SID2, projectId);+ const row = sessionRow(SID2, { projectId });row.workspace = ws;t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(@@ -3463,15 +3197,20 @@ describe("the session list's messaging mark", () => {let t: TestApp;let api: ReturnType<typeof apiClient>;const projectId = "birder-default_project";+ /** The case's Session: the app is the describe's, and each case marks a row of its own. */+ let SID: string;- beforeEach(async () => {+ beforeAll(async () => {t = await createTestApp();api = apiClient(t.app, (await provisionUser(t.app, "birder")).cookie);- t.deps.sessionsRepo.insert(sessionRowOf(SID, projectId));});- afterEach(async () => {+ afterAll(async () => {await t.cleanup();});+ beforeEach(() => {+ SID = uniqueSessionId();+ t.deps.sessionsRepo.insert(sessionRow(SID, { projectId }));+ });/** The Session's row as the development list serves it. */const listedRow = async () => {@@ -3508,10 +3247,11 @@ describe("the session list's messaging mark", () => {describe("an inbound message whose Task cannot start", () => {let t: TestApp;let api: ReturnType<typeof apiClient>;- let fake: FakeSdk;+ let fake: FakeFeishuSdk;+ const SID = uniqueSessionId();beforeEach(async () => {- fake = new FakeSdk();+ fake = new FakeFeishuSdk();t = await createTestApp({feishuSdk: fake,// Not adopted, so the first task loads through here — a Workspace that has been@@ -3524,7 +3264,7 @@ describe("an inbound message whose Task cannot start", () => {});const { cookie } = await provisionUser(t.app, "birder");api = apiClient(t.app, cookie);- t.deps.sessionsRepo.insert(sessionRowOf(SID, "birder-default_project"));+ t.deps.sessionsRepo.insert(sessionRow(SID, { projectId: "birder-default_project" }));});afterEach(async () => {await t.cleanup();@@ -3566,18 +3306,19 @@ describe("an inbound message whose Task cannot start", () => {describe("a redelivered inbound message", () => {let t: TestApp;let api: ReturnType<typeof apiClient>;- let fake: FakeSdk;+ let fake: FakeFeishuSdk;+ const SID = uniqueSessionId();let runs: InputPayload[][];let clock: number;beforeEach(async () => {- fake = new FakeSdk();+ fake = new FakeFeishuSdk();clock = Date.parse("2026-08-26T09:00:00.000Z");t = await createTestApp({ feishuSdk: fake, now: () => new Date(clock) });const { cookie } = await provisionUser(t.app, "birder");api = apiClient(t.app, cookie);runs = [];- const row = sessionRowOf(SID, "birder-default_project");+ const row = sessionRow(SID, { projectId: "birder-default_project" });t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row, echoFakeSession(SID, runs));expect((await api.put(BASE(SID), PUT_BODY)).status).toBe(200);@@ -3632,6 +3373,8 @@ describe("a redelivered inbound message", () => {describe("a message carrying several files", () => {let t: TestApp;let api: ReturnType<typeof apiClient>;+ /** The case's Session: the app is the describe's, and a binding belongs to its Session. */+ let SID: string;let bridge: MessagingBridge;let runs: InputPayload[][];let fired: ((msg: MessagingInboundMessage) => Promise<void>) | null;@@ -3693,21 +3436,23 @@ describe("a message carrying several files", () => {fired!({ chatId: "oc_scripted", chatKind: "direct", text: null, ...msg });/** echoFakeSession, but parking for as long as a test holds it. */- const heldEchoSession = (): RuntimeSession => ({- sessionId: SID,- toolPermission: () => "rw",- generateTitle: async () => ({ title: null, usage: null }),- compactability: () => "ok" as const,- steer: () => false,- skipReconnectWait: () => false,- async *run(input: OmniMessage[]) {- runs.push(input.map((m) => m.payload as InputPayload));- if (park) await new Promise<void>((resolve) => (release = resolve));- yield assistantText("Reply text");- },- async *compact() {},- });+ const heldEchoSession = (): RuntimeSession =>+ fakeSession(SID, {+ async *run(input: OmniMessage[]) {+ runs.push(input.map((m) => m.payload as InputPayload));+ if (park) await new Promise<void>((resolve) => (release = resolve));+ yield assistantText("Reply text");+ },+ });+ beforeAll(async () => {+ t = await createTestApp({ feishuSdk: new FakeFeishuSdk() });+ const { cookie } = await provisionUser(t.app, "birder");+ api = apiClient(t.app, cookie);+ });+ afterAll(async () => {+ await t.cleanup();+ });beforeEach(async () => {caps = [];notices = [];@@ -3715,10 +3460,8 @@ describe("a message carrying several files", () => {park = false;release = null;runs = [];- t = await createTestApp({ feishuSdk: new FakeSdk() });- const { cookie } = await provisionUser(t.app, "birder");- api = apiClient(t.app, cookie);- const row = sessionRowOf(SID, "birder-default_project");+ SID = uniqueSessionId();+ const row = sessionRow(SID, { projectId: "birder-default_project" });t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row, heldEchoSession());expect((await api.put(BASE(SID), PUT_BODY)).status).toBe(200);@@ -3739,10 +3482,11 @@ describe("a message carrying several files", () => {});await bridge.start();});- afterEach(async () => {+ afterEach(() => {release?.();bridge.stop();- await t.cleanup();+ // The binding goes with the case, so the next case's bridge starts with its own alone.+ t.deps.messaging.unbindSession(SID);});/** The one text part of a run's input (the path lines ride it). */