A local-first multi-agent app development platform, built on PenguinHarness
feat(server,web): bind a conversation to a QQ bot (#501)
Yaowei Zheng483af5db35fc
diff --git a/changelog/unreleased/2026-08-27-messaging-qq.md b/changelog/unreleased/2026-08-27-messaging-qq.mdnew file mode 100644index 00000000..5b28772b--- /dev/null+++ b/changelog/unreleased/2026-08-27-messaging-qq.md@@ -0,0 +1,61 @@+# QQ joins Feishu and Telegram as a messaging channel++- **Date:** 2026-08-27+- **Type:** feature+- **Scope:** `server`, `web`, `docs`+- **PR:** [#501](https://github.com/Prism-Shadow/penguin-harness/pull/501)++[中文版](2026-08-27-messaging-qq.zh.md)++A Session gained a third channel to bind to: a QQ bot, behind the same connector seam Feishu+and Telegram already sat behind. The credentials are the App ID and App Secret from the QQ+open platform, and inbound messages ride the platform's WebSocket gateway, so binding one+asks for no public callback URL. The channel did not copy the other two, because QQ does not+let a bot speak freely: everything it sends is a reply to a message the user sent minutes+ago, and that shaped every delivery rule below.++## Details++- The transport landed in `qq-api.ts`: the app-access-token exchange with early refresh and+ one exchange per burst however many sends ask at once, the two message sends, and the+ gateway session — identify with the `GROUP_AND_C2C_EVENT` intent, heartbeat, resume, and+ the close codes that decide between resuming and identifying fresh. A session that stops+ carrying traffic without closing — no handshake, or heartbeats that stop being+ acknowledged — is dropped and retried on the backoff instead of sitting at `connected`+ with nothing arriving on it. It went in behind an injectable factory, so the tests reach+ it through fakes rather than the network.+- The channel policy landed in `qq-connector.ts`. `C2C_MESSAGE_CREATE` (single chat) and+ `GROUP_AT_MESSAGE_CREATE` (group @-mention) both normalize to the bridge's inbound shape;+ the un-mentioned group firehose that rides the same intent is dropped.+- **The passive reply budget.** One inbound message funds at most 4 replies in a single chat+ and 5 in a group, inside a window of minutes. A run's first `budget - 1` completed+ assistant messages go out as they complete; everything after that is withheld and sent as+ one combined final message, so a long answer is coalesced rather than truncated. The+ approval notice shares that budget and takes the reserved slot when the immediate ones are+ gone — a run parked on an approval never reaches an end that a deferred notice could wait+ for.+- That accounting is per chat, and it lives no longer than the connection that opened it:+ turning a binding off, or re-pointing it at other credentials, forgets it, so nothing+ withheld arrives in a chat the Session has stopped answering. A redelivered `msg_id` —+ which the platform repeats on purpose, to guarantee delivery — funds nothing new, and a+ reply the platform refuses keeps its text for the next inbound message's budget instead of+ losing it.+- `linePerMessage` was clamped to the reply budget on QQ rather than to the channel-neutral+ cap of 20, through a new optional `replyBudget` on the connector seam. Feishu and Telegram+ declare none and were left unchanged.+- **Nothing is pushed.** A send with no message to reply to — a turn started in the web app,+ or any reply after the window closed — is refused with a readable reason rather than+ attempted as an active message, which QQ rate-limits, gates behind separate approval, and+ lets any user switch off. The panel states that rule on screen rather than in a collapsed+ fold, since a user who does not know it reads the channel as broken.+- Outbound files are refused on this channel with a reason: the platform's rich-media path+ wants a publicly reachable URL for the bytes, the same constraint that ruled out the+ webhook mode. Inbound media is not read.+- The `/qq` route subtree arrived with the verb set the other channels carry (GET / PUT /+ state / DELETE / test / test-message). The App ID is the account identity, so the+ one-Session-per-account rule applies to a QQ bot exactly as it does to a Feishu app — on+ the enable, and on a save that would carry an already-enabled connection onto somebody+ else's bot.+- The binding editor's channel selector gained a third option, and QQ arrived with its own+ form section, setup steps, reply-budget explanation and troubleshooting entry in both+ dictionaries.diff --git a/changelog/unreleased/2026-08-27-messaging-qq.zh.md b/changelog/unreleased/2026-08-27-messaging-qq.zh.mdnew file mode 100644index 00000000..8a75a19e--- /dev/null+++ b/changelog/unreleased/2026-08-27-messaging-qq.zh.md@@ -0,0 +1,44 @@+# QQ 成为继飞书、Telegram 之后的第三个消息渠道++- **Date:** 2026-08-27+- **Type:** feature+- **Scope:** `server`, `web`, `docs`+- **PR:** [#501](https://github.com/Prism-Shadow/penguin-harness/pull/501)++[English](2026-08-27-messaging-qq.md)++Session 多了第三个可绑定的渠道:QQ 机器人,接在飞书与 Telegram 早已使用的同一套连接器接口+后面。凭据是 QQ 开放平台的 App ID 与 App Secret,入站消息走平台的 WebSocket 网关,因此绑定+它不需要任何公网回调地址。这个渠道没有照抄前两个,因为 QQ 不允许机器人自由发言:它发出的每+一条消息都是对用户几分钟内发来的某条消息的回复,下面每一条送达规则都由此而来。++## 细节++- 传输层落在 `qq-api.ts`:带提前刷新的 app access token 交换(无论一次涌入多少发送,只换一+ 次),两个发送接口,以及网关会话——以 `GROUP_AND_C2C_EVENT` intent 鉴权、心跳、断线续传,+ 以及决定「续传还是重新鉴权」的关闭码。会话若不再承载流量却也没有关闭——握手迟迟不来,或者+ 心跳不再被确认——会被断开并按退避重连,而不是停在 `connected` 上什么也收不到。它以可注入的+ 工厂形式落地,因此测试是对着假实现跑的,不碰网络。+- 渠道策略落在 `qq-connector.ts`。`C2C_MESSAGE_CREATE`(单聊)与 `GROUP_AT_MESSAGE_CREATE`+ (群聊 @ 机器人)都归一到 bridge 的入站结构;同一 intent 携带的「群内全部消息」事件被丢弃。+- **被动回复额度。** 一条入站消息在单聊中最多支撑 4 条回复、群聊 5 条,且只在数分钟的窗口内+ 有效。一次运行中前 `budget - 1` 条完成的助手消息随完成即时发出,其余的暂存并合并为最后一条+ 发出——长回复是被合并,而不是被截断。审批提醒与之共享额度,在即时槽位用尽时占用预留的最后一+ 条:停在审批上的运行不会走到「结束」,因此等待运行结束的提醒将永远等不到。+- 这套记账按会话(聊天)分别持有,且活不过开启它的那条连接:把绑定关掉、或把它改指到另一组+ 凭据,都会把它忘掉,因此暂存的内容不会送进一个 Session 已经不再应答的聊天里。被重复投递的+ `msg_id`——平台为保证送达而有意重发——不算新额度;而被平台拒收的一次回复会把文本留给下一条+ 入站消息的额度,而不是丢掉。+- QQ 上的 `linePerMessage` 收敛到该回复额度,而不是渠道无关的上限 20;实现方式是连接器接口上+ 新增的可选 `replyBudget`。飞书与 Telegram 不声明该字段,行为未变。+- **不做任何主动推送。** 没有可回复对象的发送——在网页端发起的对话,或窗口关闭之后的回复——会+ 带着可读的原因被拒绝,而不是改用主动消息:后者被限频、需单独审批,且任何用户都能自行关闭。+ 面板把这条规则直接写在界面上而非折叠区里——不知道这条规则的人会把该渠道读成「坏了」。+- 该渠道拒绝外发文件并给出原因:平台的富媒体接口要求为文件提供公网可达地址,这与当初排除+ webhook 模式的是同一个约束。入站媒体暂不读取。+- `/qq` 路由子树带着与其他渠道一致的动词集合落地(GET / PUT / state / DELETE / test /+ test-message)。账号身份是 App ID,因此「一个账号同时只能被一个 Session 启用」对 QQ 机器人+ 的适用方式与飞书应用完全相同——启用时如此,把一条已启用的连接改指到别人的机器人上的保存+ 同样如此。+- 绑定编辑器的渠道选择器多了第三项,QQ 带着自己的表单区、创建步骤、回复额度说明与常见问题条目+ 落地,中英词典成对补齐。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex ce1d5b3e..7f0fe6a4 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -289,9 +289,9 @@ Workspace files may be Agent-generated, so `GET /files/content` treats them as uThe filename always rides along as `filename*=UTF-8''` with percent-encoding. `preview=1` is where the preview redirect falls back when no separate preview origin is available: the document keeps its real type and does render and run, but the sandbox deliberately omits `allow-same-origin`, so it lands in an opaque origin and can reach neither this origin's cookies nor the API. That isolation is also why `localStorage`, `document.cookie` and third-party embeds do not work there.-### Messaging Bindings (Feishu, Telegram)+### Messaging Bindings (Feishu, Telegram, QQ)-A Session can be connected to a messaging bot — Feishu and Telegram are the channels today, each under `/messaging/<channel>`. A Session keeps **at most one saved config per channel** (both may sit saved side by side), and **at most one of them is enabled** — the enabled channel holds the live connection. Enabling is what binds the bot account to the Session and disabling releases it, so the same app or bot may sit saved on any number of Sessions and only the enable is exclusive. Inbound messages to the bot start Tasks on the Session as ordinary user input, exactly as if typed into the web composer (no marker, queued as follow-ups while the Session is busy), and completed replies are relayed back to the chat, chunked under the channel's text-size limit (Telegram's hard cap is 4096 characters). Feishu listens over the SDK's WebSocket long connection; Telegram long-polls `getUpdates` — neither needs a public callback URL. Saving and connecting are separate: PUT persists credentials only, and the explicit state endpoint owns the connection. Paths omit the `/api/sessions/:sessionId` prefix like the table above.+A Session can be connected to a messaging bot — Feishu, Telegram and QQ are the channels today, each under `/messaging/<channel>`. A Session keeps **at most one saved config per channel** (all of them may sit saved side by side), and **at most one of them is enabled** — the enabled channel holds the live connection. Enabling is what binds the bot account to the Session and disabling releases it, so the same app or bot may sit saved on any number of Sessions and only the enable is exclusive. Inbound messages to the bot start Tasks on the Session as ordinary user input, exactly as if typed into the web composer (no marker, queued as follow-ups while the Session is busy), and completed replies are relayed back to the chat, chunked under the channel's text-size limit (Telegram's hard cap is 4096 characters). Feishu listens over the SDK's WebSocket long connection, Telegram long-polls `getUpdates`, and QQ holds the platform's WebSocket gateway with the `GROUP_AND_C2C_EVENT` intent — none of them needs a public callback URL. Saving and connecting are separate: PUT persists credentials only, and the explicit state endpoint owns the connection. Paths omit the `/api/sessions/:sessionId` prefix like the table above.| Method | Path | Description || --- | --- | --- |@@ -308,9 +308,17 @@ A Session can be connected to a messaging bot — Feishu and Telegram are the ch| DELETE | /messaging/telegram | Remove this channel's config entirely (Bot Token included). API completeness only || POST | /messaging/telegram/test | Credential probe (`getMe`) with the draft token falling back to the stored one → `{ok, latencyMs?, botUsername?, groupPrivacy?, error?}` — success names the bot the token signs in as, and reports `groupPrivacy: true` when @BotFather's Group Privacy is on (the default), under which the bot receives no ordinary message in any group it does not administer || POST | /messaging/telegram/test-message | Send a short fixed text to the last known chat; 409 `telegram_no_chat` until the bot has been messaged once in Telegram |+| GET | /messaging/qq | The QQ config in the same envelope (`appId`, `appSecretMasked`) |+| PUT | /messaging/qq | Save the credential pair: `{appId, appSecret?, clearAppSecret?, linePerMessage?}` — the App ID and App Secret from the QQ open platform's development settings. Same keep-on-blank, clear flag and save/enable split as the Feishu PUT, the same 409 `account_enabled_elsewhere` when an enabled binding's App ID is swapped for one another Session has enabled, and no cross-Session conflict on save otherwise; there is no domain field, because API v2 has one host |+| POST | /messaging/qq/state | Same contract as the other toggles (400 `qq_secret_required` without a stored secret) |+| DELETE | /messaging/qq | Remove this channel's config entirely (App Secret included). API completeness only |+| POST | /messaging/qq/test | Credential probe (the app-access-token exchange) → `{ok, latencyMs?, error?}`. No account label: the platform has no call that identifies the bot |+| POST | /messaging/qq/test-message | Send a short fixed text to the last known chat; 409 `qq_no_chat` until the bot has been messaged once in QQ, and 502 `qq_send_failed` when no recent QQ message can be replied to (see below) |Masked secrets are omitted from responses when none is stored (a cleared config), and a config without a secret cannot be enabled. `linePerMessage` is the one saved field that is not a credential: with it set, every non-blank line of a relayed assistant reply is sent as its own message (blank lines dropped, each line still chunked under the size cap, and the remainder combined into one last message past a per-reply message cap); it defaults to false, an omitted value on a PUT keeps the stored one, and it never applies to the notices or the test message. The one cross-Session rule is per bot account per channel and applies to the connection only: one account has one event stream, so at most one Session may have it enabled. Feishu's account identity is the `app_id`, Telegram's is the numeric bot id in front of the token's colon (robust against token rotation). Reads and the two tests are open to any Project member; PUT, the state toggle and DELETE are owner-only (vault semantics — the binding writes carry or act on the secret). Secrets never round-trip. Deleting the Session removes all its configs, and inbound processing accepts text messages only (other types get a bilingual "text only" reply). Telegram connects by draining the backlog first: messages sent while no connection existed are skipped, matching Feishu, where missed events are simply gone.+**QQ is a reply-only channel, and it changes what delivery means.** The platform accepts no push this product may use: every outbound message is a *passive reply* carrying the `msg_id` of an inbound one, valid for a few minutes and capped at 4 replies per message in a single chat (5 in a group). Three consequences are visible through this API. A run that completes more assistant messages than the budget allows has them **coalesced** — the first `budget - 1` go out as they complete and the rest arrive combined in one final message, so nothing is dropped. `linePerMessage` is **clamped to that budget** rather than to the channel-neutral cap of 20. And a send with nothing to reply to — a turn started in the web app, or any reply after the window closed — is **refused rather than pushed**, surfacing as 502 `qq_send_failed` on the test endpoint and as one `messaging_send_failed` error record for a relayed reply. QQ's account identity is the App ID. Outbound files are refused on this channel: the platform's rich-media path requires a publicly reachable URL for the bytes.+### Preview on a separate originBoth the Files panel's rendered HTML view (an iframe) and "open in a new tab" go through `GET /files/preview-redirect?path=`, which authenticates the caller, then mints a short-lived HMAC token and 302s to a **different origin**:diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex a03c48d6..aa57e133 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -288,9 +288,9 @@ Workspace 文件可能由 Agent 生成,`GET /files/content` 一律按不可信文件名始终以 `filename*=UTF-8''` 形式携带(百分号编码)。`preview=1` 是预览跳转在没有独立预览源时的回退目标:文档保留真实类型,可以正常渲染并执行脚本,但沙箱刻意不含 `allow-same-origin`,因此它落在一个不透明源里,既拿不到本源的 Cookie,也调不动 API。这份隔离也正是那里 `localStorage`、`document.cookie` 与第三方 embed 全都不可用的原因。-### 消息绑定(飞书、Telegram)+### 消息绑定(飞书、Telegram、QQ)-Session 可以接入消息软件机器人——目前的渠道是飞书与 Telegram,各自挂在 `/messaging/<channel>` 之下。一个 Session **每个渠道至多保存一份配置**(两份可同时保存),其中**至多一个渠道处于启用状态**——启用的渠道持有在线连接。启用即把机器人账号绑定到该 Session,停用即解除绑定,因此同一个应用或机器人可以同时保存在任意多个 Session 上,只有启用是互斥的。发给机器人的消息以普通用户输入在该 Session 上发起 Task——与在网页输入框里输入完全一致(无标记块;忙碌时排入 follow-up 队列)——完成的回复再转发回对应会话,并按渠道文本上限分段(Telegram 硬上限 4096 字符)。飞书经 SDK 的 WebSocket 长连接接收事件;Telegram 用 `getUpdates` 长轮询——两者都无需公网回调地址。保存与连接是两件事:PUT 只保存凭据,连接由独立的 state 接口开关。路径同上表,省略 `/api/sessions/:sessionId` 前缀。+Session 可以接入消息软件机器人——目前的渠道是飞书、Telegram 与 QQ,各自挂在 `/messaging/<channel>` 之下。一个 Session **每个渠道至多保存一份配置**(多份可同时保存),其中**至多一个渠道处于启用状态**——启用的渠道持有在线连接。启用即把机器人账号绑定到该 Session,停用即解除绑定,因此同一个应用或机器人可以同时保存在任意多个 Session 上,只有启用是互斥的。发给机器人的消息以普通用户输入在该 Session 上发起 Task——与在网页输入框里输入完全一致(无标记块;忙碌时排入 follow-up 队列)——完成的回复再转发回对应会话,并按渠道文本上限分段(Telegram 硬上限 4096 字符)。飞书经 SDK 的 WebSocket 长连接接收事件,Telegram 用 `getUpdates` 长轮询,QQ 以 `GROUP_AND_C2C_EVENT` intent 保持平台的 WebSocket 网关连接——三者都无需公网回调地址。保存与连接是两件事:PUT 只保存凭据,连接由独立的 state 接口开关。路径同上表,省略 `/api/sessions/:sessionId` 前缀。| 方法 | 路径 | 说明 || --- | --- | --- |@@ -307,9 +307,17 @@ Session 可以接入消息软件机器人——目前的渠道是飞书与 Teleg| DELETE | /messaging/telegram | 整体删除该渠道的配置(含 Bot Token)。仅为 API 完整性保留 || POST | /messaging/telegram/test | 凭据探测(`getMe`),草稿 Token 缺省回落到已存值 → `{ok, latencyMs?, botUsername?, groupPrivacy?, error?}`——成功时报出 Token 登录到的机器人;当 @BotFather 的 Group Privacy 处于开启状态(默认如此,此时机器人在它不担任管理员的群里收不到任何普通消息)时报出 `groupPrivacy: true` || POST | /messaging/telegram/test-message | 向最近一次收到消息的会话发送一条固定测试文本;在 Telegram 里给机器人发过消息之前返回 409 `telegram_no_chat` |+| GET | /messaging/qq | 同一形态下的 QQ 配置(`appId`、`appSecretMasked`) |+| PUT | /messaging/qq | 保存凭据对:`{appId, appSecret?, clearAppSecret?, linePerMessage?}`——QQ 开放平台「开发设置」页的 App ID 与 App Secret。留空保持、清除标记、保存与启用分离都与飞书 PUT 同口径;把一条已启用绑定的 App ID 换成另一个 Session 已启用的账号时,同样返回 409 `account_enabled_elsewhere`,此外保存不会跨 Session 冲突;没有域名字段,因为 API v2 只有一个接口域名 |+| POST | /messaging/qq/state | 与其他开关同一契约(无已存密钥时返回 400 `qq_secret_required`) |+| DELETE | /messaging/qq | 整体删除该渠道的配置(含 App Secret)。仅为 API 完整性保留 |+| POST | /messaging/qq/test | 凭据探测(换取 app access token)→ `{ok, latencyMs?, error?}`。不报出账号名:平台没有能识别机器人身份的接口 |+| POST | /messaging/qq/test-message | 向最近一次收到消息的会话发送一条固定测试文本;在 QQ 里给机器人发过消息之前返回 409 `qq_no_chat`;没有可回复的近期消息时返回 502 `qq_send_failed`(见下) |没有已存密钥的配置(被清除过的)不返回掩码字段,也无法启用。`linePerMessage` 是唯一一个不属于凭据的已存字段:开启后,转发的助手回复中每个非空行各自作为一条消息发出(空行忽略,单行仍按长度上限分段,超出每条回复的消息条数上限的部分合并为最后一条);默认为 false,PUT 省略该字段则保持已存值,且它不作用于通知与测试消息。唯一的跨 Session 规则按渠道内机器人账号计,且只作用于连接:一个账号只有一条事件流,因此至多一个 Session 能将其启用。飞书的账号身份是 `app_id`,Telegram 是 Token 冒号前的数字机器人 id(换发 Token 也不会改变)。读取与两个测试接口对任意 Project 成员开放;PUT、state 开关与 DELETE 仅限所有者(与 Vault 同口径——绑定写操作携带或作用于密钥)。密钥永不回传。删除 Session 会连带删除其全部渠道配置;入站仅处理文本消息(其他类型收到双语的“仅支持文本”回复)。Telegram 建立连接时先清空积压:无连接期间发来的消息会被跳过,与飞书“错过的事件即消失”同口径。+**QQ 是只能被动回复的渠道,这改变了「送达」的含义。** 平台不提供本产品可用的主动推送:每一条外发消息都是携带入站 `msg_id` 的*被动回复*,有效期只有几分钟,且单聊对同一条消息最多 4 条回复(群聊 5 条)。由此有三点在 API 上可见。一次运行完成的助手消息超过该额度时会被**合并**——前 `budget - 1` 条随完成即时发出,其余合并为最后一条送达,内容不丢。`linePerMessage` 的拆分上限**收敛到该额度**,而不是渠道无关的 20。而没有可回复对象的发送——在网页端发起的对话,或窗口关闭之后的回复——会被**拒绝而非主动推送**:测试接口上表现为 502 `qq_send_failed`,转发回复则记为一条 `messaging_send_failed` 错误记录。QQ 的账号身份是 App ID。该渠道拒绝外发文件:平台的富媒体接口要求为文件提供公网可达地址。+### 独立源预览Files 面板内的 HTML 渲染视图(iframe)与“新页面打开”都走 `GET /files/preview-redirect?path=`:先鉴权,再签发一枚短时效 HMAC 令牌,然后 302 跳转到**另一个源**:diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 6021156d..63d193c3 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -1604,7 +1604,7 @@ export interface SessionProcessesResponse {// ---------------------------------------------------------------------------/** Messaging channels a Session can bind to. */-export type MessagingChannel = "feishu" | "telegram";+export type MessagingChannel = "feishu" | "telegram" | "qq";/** Event-connection runtime state of one binding (kept in memory, not persisted). */export type MessagingRuntimeState = "disconnected" | "connecting" | "connected" | "error";@@ -1673,8 +1673,39 @@ export interface TelegramBindingInfo {updatedAt: string;}+/** The stored QQ config, secret masked (plaintext never leaves the server). */+export interface QQBindingInfo {+ channel: "qq";+ sessionId: string;+ /** The bot's App ID — the channel-scoped account identity, never secret. */+ appId: string;+ /**+ * Masked App Secret (site-wide mask rule: `***`, or `first4…last4` for long values);+ * absent when no secret is stored (never entered, or cleared) — the binding cannot be+ * enabled until one is saved.+ */+ appSecretMasked?: string;+ /** Connection INTENT (the state toggle's value); new bindings start disabled, and at most one of a Session's channels is enabled. */+ enabled: boolean;+ /**+ * Send each non-blank line of a relayed assistant reply as its own message instead of one+ * message per reply. Off by default. On QQ the split is additionally capped at the+ * platform's passive-reply budget rather than the channel-neutral ceiling, so it yields+ * far fewer messages here than on the other channels.+ */+ linePerMessage: boolean;+ /**+ * Whether an inbound QQ chat is known (the bot has been messaged at least once).+ * Weaker than it looks on this channel: QQ accepts only replies to a recent message, so a+ * known chat is necessary but not sufficient for anything to be deliverable right now.+ */+ lastChatKnown: boolean;+ createdAt: string;+ updatedAt: string;+}+/** A Session's saved config for one messaging channel (`channel` is the discriminant). */-export type MessagingBindingInfo = FeishuBindingInfo | TelegramBindingInfo;+export type MessagingBindingInfo = FeishuBindingInfo | TelegramBindingInfo | QQBindingInfo;/** One saved channel config with its event-connection runtime status. */export interface MessagingChannelState {@@ -1704,6 +1735,12 @@ export interface TelegramBindingResponse {status: MessagingRuntimeStatus;}+/** GET / PUT …/messaging/qq response (the QQ narrowing of the same envelope). */+export interface QQBindingResponse {+ binding: QQBindingInfo | null;+ status: MessagingRuntimeStatus;+}+/*** PUT …/messaging/feishu — saves credentials/config ONLY, never flipping the connection* (exception: an enabled binding's connector restarts with the new credentials so stored@@ -1749,6 +1786,28 @@ export interface TelegramBindingPutRequest {linePerMessage?: boolean;}+/**+ * PUT …/messaging/qq — saves the credential pair ONLY, same contract as the Feishu PUT+ * (an enabled binding's connector restarts with the new credentials; the connection toggle+ * is POST …/state). The App ID is the account identity, so changing it rebinds the row to+ * a different bot and drops the remembered chat.+ */+export interface QQBindingPutRequest {+ appId: string;+ /** Omitted or blank keeps the stored secret (the masked value never round-trips). */+ appSecret?: string;+ /**+ * Drops the STORED secret (the models-page clear idiom; a typed `appSecret` wins over+ * it). Refused with 409 `messaging_disable_before_clear` while the binding is enabled.+ */+ clearAppSecret?: boolean;+ /**+ * Delivery preference (see `QQBindingInfo.linePerMessage`). Omitted keeps the stored+ * value; a binding created without it starts with it off.+ */+ linePerMessage?: boolean;+}+/*** POST …/messaging/<channel>/state — enable connects with the STORED credentials,* disable terminates. Enabling is what binds the bot account to this Session, and it is@@ -1799,9 +1858,28 @@ export interface TelegramTestResponse {error?: string;}+/** POST …/messaging/qq/test — draft values; each omitted field falls back to the stored binding. */+export interface QQTestRequest {+ appId?: string;+ appSecret?: string;+}++/**+ * QQ credential-test outcome. There is no account label: the platform's only credential+ * call is the access-token exchange, which identifies nothing beyond the App ID that was+ * sent to it.+ */+export interface QQTestResponse {+ ok: boolean;+ latencyMs?: number;+ error?: string;+}+/*** POST …/messaging/<channel>/test-message — sent to the last known chat (409- * `feishu_no_chat` / `telegram_no_chat` before one exists).+ * `feishu_no_chat` / `telegram_no_chat` / `qq_no_chat` before one exists). On QQ this can+ * still fail with 502 afterwards: the platform accepts only replies to a message sent from+ * QQ minutes earlier, so a known chat does not mean a deliverable one.*/export interface MessagingTestMessageResponse {ok: true;diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex 152b3956..32b15ed8 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -78,6 +78,9 @@ import type { FeishuSdk } from "./runtime/messaging/feishu-sdk.js";import { TelegramConnector } from "./runtime/messaging/telegram-connector.js";import { createTelegramTransport } from "./runtime/messaging/telegram-api.js";import type { TelegramTransport } from "./runtime/messaging/telegram-api.js";+import { QQConnector } from "./runtime/messaging/qq-connector.js";+import { createQQTransport } from "./runtime/messaging/qq-api.js";+import type { QQTransport } from "./runtime/messaging/qq-api.js";import { TitleGenerator, TitleNotifier } from "./runtime/title-generator.js";import { AdminService } from "./services/admin-service.js";import { DesktopService } from "./services/desktop-service.js";@@ -213,6 +216,10 @@ export interface BuildDepsOverrides {telegramTransport?: TelegramTransport;/** Test hook: the Telegram connector's poll backoff (tests collapse it to zero). */telegramRetryDelayMs?: (failures: number) => number;+ /** Test double: the QQ connector's OpenAPI + gateway transport (avoids real QQ network / a WebSocket). */+ qqTransport?: QQTransport;+ /** Test hook: how long the QQ connector withholds its coalesced tail (tests collapse it to zero). */+ qqTailFlushMs?: number;/** Test hook: the bridge's pace between a per-line reply's messages (tests collapse it to zero). */messagingLineDelayMs?: number;/**@@ -745,6 +752,10 @@ export function buildAppDeps(overrides.telegramTransport ?? createTelegramTransport(),overrides.telegramRetryDelayMs ? { retryDelayMs: overrides.telegramRetryDelayMs } : {},),+ new QQConnector(overrides.qqTransport ?? createQQTransport(), {+ ...(overrides.qqTailFlushMs !== undefined ? { tailFlushMs: overrides.qqTailFlushMs } : {}),+ ...(overrides.now ? { now: () => overrides.now!().getTime() } : {}),+ }),],errors,log,@@ -767,7 +778,8 @@ export function buildAppDeps(// stored channel reads as none (same defensive skip as the bridge and the routes).messagingChannel: (sessionId) => {const enabled = messagingRepo.findEnabled(sessionId);- return enabled !== null && (enabled.channel === "feishu" || enabled.channel === "telegram")+ return enabled !== null &&+ (enabled.channel === "feishu" || enabled.channel === "telegram" || enabled.channel === "qq")? enabled.channel: null;},diff --git a/packages/server/src/db/repos/messaging-bindings.ts b/packages/server/src/db/repos/messaging-bindings.tsindex d2d5c199..5a2ce3f8 100644--- a/packages/server/src/db/repos/messaging-bindings.ts+++ b/packages/server/src/db/repos/messaging-bindings.ts@@ -1,5 +1,5 @@/**- * Repo for Session ↔ messaging-channel bot bindings (Feishu and Telegram today).+ * Repo for Session ↔ messaging-channel bot bindings (Feishu, Telegram and QQ today).** A Session keeps at most one saved config PER channel — the `(session_id, channel)`* primary key — and both channels' credentials may sit saved side by side. Which of them@@ -30,11 +30,11 @@ import type { DatabaseSync } from "node:sqlite";export interface MessagingBindingRow {sessionId: string;- /** Messaging channel discriminator (`feishu` | `telegram`). */+ /** Messaging channel discriminator (`feishu` | `telegram` | `qq`). */channel: string;- /** Channel-scoped bot/app identity (feishu: the app_id; telegram: the bot token's numeric id); never secret. */+ /** Channel-scoped bot/app identity (feishu: the app_id; telegram: the bot token's numeric id; qq: the App ID); never secret. */accountId: string;- /** Channel-specific config document (feishu: appId/appSecret/baseDomain; telegram: botToken). */+ /** Channel-specific config document (feishu: appId/appSecret/baseDomain; telegram: botToken; qq: appId/appSecret). */config: Record<string, unknown>;/*** INTENT state: whether the binding should hold a live connection (the connection'sdiff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.tsindex 46ceba2c..a3be8bc1 100644--- a/packages/server/src/db/schema.ts+++ b/packages/server/src/db/schema.ts@@ -124,9 +124,9 @@ CREATE TABLE IF NOT EXISTS goal_state ( -- goal-mode runtime state (GOAL.CREATE INDEX IF NOT EXISTS idx_goal_session ON goal_state(session_id);CREATE TABLE IF NOT EXISTS messaging_bindings ( -- Session ↔ messaging-channel bot bindings (runtime/messaging/ holds the long connections)session_id TEXT NOT NULL, -- a Session keeps at most one saved config PER channel (composite PK below); at most ONE of them is enabled at a time (route-enforced, 409 another_channel_enabled), and enabling is what binds the account to this Session- channel TEXT NOT NULL, -- messaging channel discriminator ('feishu' | 'telegram')- account_id TEXT NOT NULL, -- channel-scoped bot/app identity (feishu: app_id; telegram: the bot token's numeric id); NOT unique — any number of Sessions may keep the same account saved side by side, each with its own config and last-chat memory; only ENABLING is exclusive (route-enforced, 409 account_enabled_elsewhere: one account has one event stream, two live connections on it would race)- config_json TEXT NOT NULL, -- channel-specific credentials/config JSON (feishu: appId/appSecret/baseDomain; telegram: botToken); secrets plaintext at rest (same trade-off as the proxy address in server_settings), masked at every API surface; a cleared secret is stored as "" (the row and its account identity stay)+ channel TEXT NOT NULL, -- messaging channel discriminator ('feishu' | 'telegram' | 'qq')+ account_id TEXT NOT NULL, -- channel-scoped bot/app identity (feishu: app_id; telegram: the bot token's numeric id; qq: the bot's App ID); NOT unique — any number of Sessions may keep the same account saved side by side, each with its own config and last-chat memory; only ENABLING is exclusive (route-enforced, 409 account_enabled_elsewhere: one account has one event stream, two live connections on it would race)+ config_json TEXT NOT NULL, -- channel-specific credentials/config JSON (feishu: appId/appSecret/baseDomain; telegram: botToken; qq: appId/appSecret); secrets plaintext at rest (same trade-off as the proxy address in server_settings), masked at every API surface; a cleared secret is stored as "" (the row and its account identity stay)enabled INTEGER NOT NULL DEFAULT 0, -- INTENT state (the connection's runtime status stays in memory): new bindings start disabled — saving credentials never opens a connection, the explicit state toggle doesline_per_message INTEGER NOT NULL DEFAULT 0, -- delivery preference: 1 = every non-blank line of a relayed assistant reply is sent as its own message (a reply written as spoken lines arrives as spoken lines), 0 = one message per reply. Channel-agnostic, so it lives here rather than in config_json, which each connector ownslast_chat_id TEXT, -- most recent inbound chat (NULL until the bot is messaged once; replies and test messages target it)diff --git a/packages/server/src/http/routes/messaging.ts b/packages/server/src/http/routes/messaging.tsindex d0656135..d3f2d060 100644--- a/packages/server/src/http/routes/messaging.ts+++ b/packages/server/src/http/routes/messaging.ts@@ -1,9 +1,9 @@/*** Messaging-binding routes: /api/sessions/:sessionId/messaging[...] — the binding* editor's and the Messaging dock panel's shared surface. A Session keeps at most one- * saved config PER channel (both may sit saved side by side); the channel-agnostic GET- * returns them all, and each channel owns a subtree with its own config shape — /feishu- * and /telegram carry the same verb set, and a further channel adds its own.+ * saved config PER channel (all of them may sit saved side by side); the channel-agnostic+ * GET returns them all, and each channel owns a subtree with its own config shape —+ * /feishu, /telegram and /qq carry the same verb set, and a further channel adds its own.** ENABLING the connection IS the binding, and disabling it is the unbind. Saving* credentials therefore never conflicts across Sessions — any number of Sessions may keep@@ -25,7 +25,7 @@* applied on Save — omitted keeps the stored value — and it never touches the connection.** Round-trip rule for secrets: GET only ever returns the masked value, and a PUT whose- * secret (feishu `appSecret`, telegram `botToken`) is omitted or blank keeps the stored+ * secret (feishu `appSecret`, telegram `botToken`, qq `appSecret`) is omitted or blank keeps the stored* one (the same never-round-trip-masked-keys convention as the models test endpoint), so* the plaintext exists only at first entry. Dropping a stored secret is the explicit* clear flag (the models-page idiom), refused while the binding is enabled — the cleared@@ -43,6 +43,9 @@ import type {MessagingBindingStateRequest,MessagingChannelState,MessagingTestMessageResponse,+ QQBindingInfo,+ QQBindingResponse,+ QQTestResponse,TelegramBindingInfo,TelegramBindingResponse,TelegramTestResponse,@@ -83,6 +86,15 @@ function telegramFieldsOf(row: MessagingBindingRow): { botToken: string } {return { botToken: typeof botToken === "string" ? botToken : "" };}+/** The stored qq config, tolerated loosely (a malformed document reads as blanks). */+function qqFieldsOf(row: MessagingBindingRow): { appId: string; appSecret: string } {+ const { appId, appSecret } = row.config;+ return {+ appId: typeof appId === "string" ? appId : row.accountId,+ appSecret: typeof appSecret === "string" ? appSecret : "",+ };+}+function toFeishuInfo(row: MessagingBindingRow): FeishuBindingInfo {const fields = feishuFieldsOf(row);return {@@ -116,10 +128,26 @@ function toTelegramInfo(row: MessagingBindingRow): TelegramBindingInfo {};}+function toQQInfo(row: MessagingBindingRow): QQBindingInfo {+ const fields = qqFieldsOf(row);+ return {+ channel: "qq",+ sessionId: row.sessionId,+ appId: fields.appId,+ ...(fields.appSecret !== "" ? { appSecretMasked: maskApiKey(fields.appSecret) } : {}),+ enabled: row.enabled,+ linePerMessage: row.linePerMessage,+ lastChatKnown: row.lastChatId !== null,+ createdAt: row.createdAt,+ updatedAt: row.updatedAt,+ };+}+/** Whatever channel the row is: its masked view, or null on an unknown discriminator (skipped defensively, like the bridge does). */function toBindingInfo(row: MessagingBindingRow): MessagingBindingInfo | null {if (row.channel === "feishu") return toFeishuInfo(row);if (row.channel === "telegram") return toTelegramInfo(row);+ if (row.channel === "qq") return toQQInfo(row);return null;}@@ -183,6 +211,14 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {};};+ const qqResponse = (sessionId: string): QQBindingResponse => {+ const row = deps.messagingRepo.find(sessionId, "qq");+ return {+ binding: row ? toQQInfo(row) : null,+ status: deps.messaging.statusOf(sessionId, "qq"),+ };+ };+/*** The one-connection-per-account rule, on its own because two paths need it: the enable,* and a save that would carry an already-live connection onto a different account.@@ -227,9 +263,18 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {}guardAccountFree(sessionId, channel, row.accountId);const secret =- channel === "feishu" ? feishuFieldsOf(row).appSecret : telegramFieldsOf(row).botToken;+ channel === "feishu"+ ? feishuFieldsOf(row).appSecret+ : channel === "qq"+ ? qqFieldsOf(row).appSecret+ : telegramFieldsOf(row).botToken;if (secret === "") {- const code = channel === "feishu" ? "feishu_secret_required" : "telegram_token_required";+ const code =+ channel === "feishu"+ ? "feishu_secret_required"+ : channel === "qq"+ ? "qq_secret_required"+ : "telegram_token_required";throw new HttpError(400, code, "The stored config has no credential: save one first.");}};@@ -529,10 +574,138 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {return c.json({ ok: true } satisfies MessagingTestMessageResponse);});+ // —— QQ ————————————————————————————————————————————————————————————————————+ //+ // Same verb set and the same save/enable split as the two channels above; the config is+ // the App ID / App Secret pair from the QQ developer console, and the App ID is the+ // account identity (the QQ analogue of the Feishu app id: stable, non-secret, and+ // unchanged by rotating the secret).++ app.get("/:sessionId/messaging/qq", (c) => {+ const row = resolveSession(c);+ return c.json(qqResponse(row.sessionId));+ });++ app.put("/:sessionId/messaging/qq", async (c) => {+ const row = resolveSession(c);+ deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);+ const body = await readJson(c);+ const appId = requireString(body, "appId", { minLen: 1, maxLen: 200 }).trim();+ if (appId === "") throw badRequest("appId must not be blank.");+ const secretInput = optionalString(body, "appSecret", { maxLen: 500 })?.trim();+ const clearSecret = (body as { clearAppSecret?: unknown }).clearAppSecret === true;+ const linePerMessage = optionalBoolean(body, "linePerMessage");+ const existing = deps.messagingRepo.find(row.sessionId, "qq");+ const typed = secretInput !== undefined && secretInput !== "" ? secretInput : undefined;+ // The same ladder as the other two channels: typed wins, then the clear flag (disable+ // first), then the stored secret; a first bind must carry one.+ let appSecret: string;+ if (typed !== undefined) appSecret = typed;+ else if (clearSecret && existing !== null) {+ if (existing.enabled) {+ throw new HttpError(+ 409,+ "messaging_disable_before_clear",+ "Disable the connection before clearing its credential.",+ );+ }+ appSecret = "";+ } else {+ const stored = existing !== null ? qqFieldsOf(existing).appSecret : "";+ if (stored === "") {+ throw new HttpError(400, "qq_secret_required", "appSecret is required to bind.");+ }+ appSecret = stored;+ }+ // Same reason as the Feishu and Telegram PUTs: an enabled binding re-pointed at another+ // App ID keeps its connection and restarts it below, which would stand two Sessions on+ // one bot's single gateway without either passing the enable gate.+ if (existing !== null && existing.enabled) guardAccountFree(row.sessionId, "qq", appId);+ const saved = deps.messagingRepo.upsert({+ sessionId: row.sessionId,+ channel: "qq",+ accountId: appId,+ config: { appId, appSecret },+ ...(linePerMessage !== undefined ? { linePerMessage } : {}),+ });+ if (saved.enabled) await deps.messaging.sync(row.sessionId);+ return c.json(qqResponse(row.sessionId));+ });++ app.post("/:sessionId/messaging/qq/state", async (c) => {+ const row = resolveSession(c);+ deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);+ const enabled = await readStateBody(c);+ const binding = deps.messagingRepo.find(row.sessionId, "qq");+ if (binding === null) {+ throw new HttpError(404, "qq_not_bound", "This Session has no QQ binding.");+ }+ if (enabled) guardEnable(row.sessionId, "qq", binding);+ deps.messagingRepo.setEnabled(row.sessionId, "qq", enabled);+ await deps.messaging.sync(row.sessionId);+ return c.json(qqResponse(row.sessionId));+ });++ app.delete("/:sessionId/messaging/qq", (c) => {+ const row = resolveSession(c);+ deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);+ deps.messaging.unbind(row.sessionId, "qq");+ return c.body(null, 204);+ });++ // Credential probe: the access-token exchange, which is the only credential call the+ // platform has. It names no account, so the response carries no label — unlike Telegram's.+ app.post("/:sessionId/messaging/qq/test", async (c) => {+ const row = resolveSession(c);+ const body = await readJson(c);+ const stored = deps.messagingRepo.find(row.sessionId, "qq");+ const storedFields = stored !== null ? qqFieldsOf(stored) : null;+ const appId = optionalString(body, "appId", { maxLen: 200 })?.trim() || storedFields?.appId;+ const appSecret =+ optionalString(body, "appSecret", { maxLen: 500 })?.trim() || storedFields?.appSecret;+ if (appId === undefined || appId === "") {+ throw badRequest("appId is required (no stored binding to fall back to).");+ }+ if (appSecret === undefined || appSecret === "") {+ throw new HttpError(400, "qq_secret_required", "appSecret is required to test.");+ }+ const result = await deps.messaging.testCredentials("qq", { appId, appSecret });+ return c.json({+ ok: result.ok,+ ...(result.latencyMs !== undefined ? { latencyMs: result.latencyMs } : {}),+ ...(result.error !== undefined ? { error: result.error } : {}),+ } satisfies QQTestResponse);+ });++ // The one test endpoint that means something different here. On Feishu and Telegram a+ // known chat is enough to send into; on QQ a message may only be sent as a reply to one+ // the user sent minutes ago, so the 409 below is the weaker of two gates and the send can+ // still fail with 502 `qq_send_failed` naming the window. The message text says so.+ app.post("/:sessionId/messaging/qq/test-message", async (c) => {+ const row = resolveSession(c);+ const binding = deps.messagingRepo.find(row.sessionId, "qq");+ if (!binding) {+ throw new HttpError(404, "qq_not_bound", "This Session has no QQ binding.");+ }+ if (binding.lastChatId === null) {+ throw new HttpError(+ 409,+ "qq_no_chat",+ "No QQ chat is known yet: message the bot once in QQ first.",+ );+ }+ try {+ await deps.messaging.sendTestMessage(binding);+ } catch (err) {+ throw new HttpError(502, "qq_send_failed", err instanceof Error ? err.message : String(err));+ }+ return c.json({ ok: true } satisfies MessagingTestMessageResponse);+ });+return app;}-/** The state toggle's `{enabled}` body, shared by both channels. */+/** The state toggle's `{enabled}` body, shared by every channel. */async function readStateBody(c: Context<AppEnv>): Promise<boolean> {const body = await readJson(c);const enabled = (body as Partial<MessagingBindingStateRequest>).enabled;diff --git a/packages/server/src/runtime/messaging/bridge.ts b/packages/server/src/runtime/messaging/bridge.tsindex cba282cb..a75eaa9c 100644--- a/packages/server/src/runtime/messaging/bridge.ts+++ b/packages/server/src/runtime/messaging/bridge.ts@@ -1,7 +1,7 @@/*** Messaging bridge: a Web server runtime component connecting Sessions to external chat- * platforms through channel connectors (Feishu and Telegram today — see- * feishu-connector.ts / telegram-connector.ts). Started by the platform next to the+ * platforms through channel connectors (Feishu, Telegram and QQ today — see+ * feishu-connector.ts / telegram-connector.ts / qq-connector.ts). Started by the platform next to the* Scheduler, stopped when the* App is disposed — a hot swap hard-stops it like the scheduler. A Session may keep a* saved config per channel, but AT MOST ONE of them is enabled (the state route enforces@@ -84,6 +84,11 @@ export const MESSAGING_TEXT_CHUNK_CHARS = 4000;* tail of a reply is the worst failure available here. The one reply that still exceeds the* ceiling is one long enough to need more messages than this unchunked — which it would have* needed with the option off too.+ *+ * A channel that declares its own `replyBudget` (QQ, whose platform accepts only a handful+ * of replies per inbound message) caps the split at that instead: 20 is sized for a channel+ * whose only limit is a rate, and asking a budgeted channel for more messages than it can+ * ever deliver would just move the combining downstream.*/export const MESSAGING_MAX_LINE_MESSAGES = 20;@@ -674,8 +679,9 @@ export class MessagingBridge {* moving — and so do the messages behind it in THIS reply: one refused message (a 429 on* the third line of twelve) must not abandon the rest, which would leave a reply stopping* mid-sentence with nothing in the chat to say why. A binding with `linePerMessage` set- * sends one message per non-blank line instead of one per reply (see splitReplyLines),- * paced MESSAGING_LINE_DELAY_MS apart so the burst stays inside the channel's per-chat+ * sends one message per non-blank line instead of one per reply (see splitReplyLines,+ * capped at the channel's own `replyBudget` where it declares one), paced+ * MESSAGING_LINE_DELAY_MS apart so the burst stays inside the channel's per-chat* allowance — chunking, threading and ordering are identical either way, and with the flag* off the send sequence is unchanged. In a group the run's* first outbound chunk threads onto the inbound message and@@ -689,7 +695,9 @@ export class MessagingBridge {const { row, chatId, client } = target;// One body per outbound message: the whole reply, or one per non-blank line when the// binding asked for that. Everything below is untouched by the choice.- const bodies = row.linePerMessage ? splitReplyLines(text) : [text];+ const bodies = row.linePerMessage+ ? splitReplyLines(text, entry.connector.replyBudget ?? MESSAGING_MAX_LINE_MESSAGES)+ : [text];const messages = bodies.flatMap((body) => chunkMessagingText(body));for (const [i, chunk] of messages.entries()) {// The messages of a per-line reply are a burst; the channel's per-chat allowance isdiff --git a/packages/server/src/runtime/messaging/connector.ts b/packages/server/src/runtime/messaging/connector.tsindex 75843391..fdfa1594 100644--- a/packages/server/src/runtime/messaging/connector.ts+++ b/packages/server/src/runtime/messaging/connector.ts@@ -1,7 +1,7 @@/*** The messaging-channel connector seam: what the MessagingBridge needs from one chat- * platform (Feishu and Telegram today; further channels implement the same interface and- * register in app assembly). A connector owns everything channel-specific — credential+ * platform (Feishu, Telegram and QQ today; further channels implement the same interface+ * and register in app assembly). A connector owns everything channel-specific — credential* shape, wire protocol, event normalization — and hands the bridge a channel-neutral* view: a client for outbound sends and credential checks, and a long-lived event* connection delivering normalized inbound messages.@@ -12,7 +12,7 @@*//** Known messaging channels (the DB stores the discriminator as text; unknown values are skipped defensively). */-export type MessagingChannel = "feishu" | "telegram";+export type MessagingChannel = "feishu" | "telegram" | "qq";/** One inbound chat message, normalized across channels. */export interface MessagingInboundMessage {@@ -91,6 +91,17 @@ export interface MessagingClient {export interface MessagingChannelConnector {readonly channel: MessagingChannel;+ /**+ * How many outbound messages this channel will accept in answer to ONE inbound message,+ * or undefined where no such limit exists (Feishu and Telegram both send freely).+ *+ * A channel that declares one enforces it itself — the connector is the only place that+ * knows what the platform rejects and how to combine messages so nothing is lost. What+ * the bridge does with the number is narrower: it caps the one-message-per-line split at+ * it, because that option's own ceiling is sized for a channel with no such budget and+ * would otherwise ask for more messages than the channel can ever deliver.+ */+ readonly replyBudget?: number;/** Builds the outbound client for one stored config (throws on a malformed document). */createClient(config: Record<string, unknown>): Promise<MessagingClient>;/**diff --git a/packages/server/src/runtime/messaging/qq-api.ts b/packages/server/src/runtime/messaging/qq-api.tsnew file mode 100644index 00000000..40d1e45e--- /dev/null+++ b/packages/server/src/runtime/messaging/qq-api.ts@@ -0,0 +1,790 @@+/**+ * The QQ bot open-platform (API v2) seam: the app-access-token exchange, the two message+ * sends, and the WebSocket gateway, behind an injectable transport so unit tests+ * substitute a fake and never open a socket to Tencent. QQ publishes no Node SDK this+ * product can take (the one Tencent ships for the scan flow is `UNLICENSED`), so the+ * production adapter is plain fetch plus undici's WebSocket — both of which resolve+ * undici's global dispatcher per call, which is how they inherit the admin proxy setting+ * (net/proxy.ts) without asking for it.+ *+ * Wire types below mirror the platform's JSON verbatim (snake_case): the transport does+ * not reshape payloads, so a test fake constructs exactly what the real API returns.+ *+ * Two properties of this platform shape the whole seam, and every caller downstream+ * inherits them:+ *+ * 1. AUTH IS A SHORT-LIVED TOKEN, NOT THE CREDENTIAL. Every OpenAPI call carries+ * `Authorization: QQBot <access_token>`, and that token lasts at most 7200 seconds.+ * The credential pair (App ID + App Secret) only ever buys a new one. So the client+ * owns a token cache with early refresh rather than making callers think about it —+ * and the platform documents that a request inside the last 60 seconds of validity+ * returns a NEW token while the old one keeps working for those 60 seconds, so+ * refreshing early can never strand a request that is already in flight.+ * 2. THE GATEWAY IS THE ONLY WAY IN FOR A LOCAL SERVER. QQ also offers an HTTP callback+ * mode, but it needs a publicly reachable HTTPS URL on one of four ports (80, 443,+ * 8080, 8443) plus an Ed25519 challenge response — the same class of constraint that+ * made Feishu a long connection and Telegram a long poll. So this seam opens a+ * WebSocket, identifies with the group-and-C2C intent, heartbeats, and resumes.+ *+ * A THIRD property does not live here but is worth naming from the transport, because it+ * is the reason `QQSendArgs` has no "just send" shape: QQ has no free outbound. Every send+ * this product makes is a PASSIVE REPLY carrying the `msg_id` of an inbound message, and+ * that is a budget — see qq-connector.ts, which owns the accounting.+ */+import { WebSocket } from "undici";++/**+ * QQ bot OpenAPI host — both the token endpoint and the resource endpoints. Deliberately+ * not configurable: API v2 has no separate sandbox host (a sandbox in v2 is a whitelist of+ * groups and accounts configured in the console, served by this same host), so there is+ * nothing for a domain field to switch between, unlike Feishu's Feishu/Lark split.+ */+export const QQ_API_BASE = "https://api.bot.qq.com";++/**+ * The one intent this bot subscribes: `GROUP_AND_C2C_EVENT` (1 << 25). It carries the two+ * events this product reads — `C2C_MESSAGE_CREATE` (a single chat with the bot) and+ * `GROUP_AT_MESSAGE_CREATE` (a group message that @-mentions it) — along with eight+ * others (friend add/remove, the push-permission toggles, robot add/remove) that+ * normalizeDispatch drops.+ *+ * Nothing else is subscribed. Guild intents a bot has no permission for are refused at+ * identify with close code 4014, and this product has no use for them.+ */+export const QQ_INTENT_GROUP_AND_C2C = 1 << 25;++/** One credential set (a binding's stored values, or a test request's draft). */+export interface QQCredentials {+ /** The bot's App ID — also the channel-scoped account identity; never secret. */+ appId: string;+ /** The App Secret from the developer console (the platform's `clientSecret`). */+ appSecret: string;+}++/**+ * `POST /app/getAppAccessToken` result. `expires_in` is seconds and never exceeds 7200 —+ * typed as a union because the platform's own response example returns it quoted while its+ * field table calls it a number.+ */+export interface QQAppAccessToken {+ access_token: string;+ expires_in: number | string;+}++/** `GET /gateway` result: the WebSocket URL to connect to. */+export interface QQGatewayInfo {+ url: string;+}++/**+ * Which side of the platform a chat lives on. It selects the send endpoint AND the passive+ * reply budget, which is not the same on both (see qq-connector.ts).+ */+export type QQChatKind = "c2c" | "group";++/**+ * One inbound message event, reduced to what the connector consumes. `openid` is the+ * conversation's own id — the user's for a single chat, the group's for a group — which is+ * also the send endpoint's path segment, so it doubles as the chat id.+ */+export interface QQInboundEvent {+ kind: QQChatKind;+ /** `author.user_openid` for a single chat, `group_openid` for a group. */+ openid: string;+ /** The platform's message id (`d.id`): the passive reply's `msg_id`, and the dedupe key. */+ messageId: string;+ /**+ * Message text, already trimmed. The platform strips the `@bot` prefix from a group+ * message's content itself but leaves the whitespace it sat in, so the trim is the+ * connector's half of that contract.+ */+ content: string;+ /** Sender openid (`author.user_openid` in a single chat, `author.member_openid` in a group). */+ senderOpenid?: string;+}++/**+ * One outbound send. Always a PASSIVE reply: `msgId` names the inbound message being+ * answered, and `msgSeq` orders the replies to it. There is no push shape here on purpose —+ * see the module doc.+ */+export interface QQSendArgs {+ kind: QQChatKind;+ openid: string;+ content: string;+ /** The inbound message being answered — what makes this a passive reply rather than a push. */+ msgId: string;+ /**+ * Sequence among the replies to `msgId`, 1-based (the platform's own default is 1).+ * A repeated `msg_id` + `msg_seq` pair is REJECTED (40054005 消息被去重), not ignored, so+ * this must genuinely increment per reply.+ */+ msgSeq: number;+}++/** OpenAPI half of the seam, bound to one credential pair. Every method throws on failure with a readable reason. */+export interface QQBotClient {+ /**+ * Credential check: exchanges the App ID / App Secret for an access token. The platform+ * has no cheaper "who am I" call — and no call at all that identifies the bot by name —+ * so the exchange itself is the probe and there is no account label to surface.+ */+ checkCredentials(): Promise<void>;+ /** Sends one passive text reply into a single chat or a group. */+ sendMessage(args: QQSendArgs): Promise<void>;+}++export interface QQGatewayHandlers {+ onMessage(evt: QQInboundEvent): void | Promise<void>;+ /** The gateway completed a handshake (fires again after an automatic reconnect). */+ onReady?(): void;+ /** The gateway failed; reported once per outage, as the Telegram poll loop does. */+ onError?(err: unknown): void;+}++/** A live gateway session; `close` ends it and stops reconnecting (idempotent). */+export interface QQGatewayConnection {+ close(): void;+}++/** Factory the QQ connector is built over: the production adapter, or a test fake. */+export interface QQTransport {+ createClient(creds: QQCredentials): QQBotClient;+ /**+ * Opens the gateway for one bot. Resolves as soon as the session is constructed and+ * connecting — lifecycle arrives via the handlers (`onReady` / `onError`), because the+ * adapter reconnects on its own and a single promise cannot carry a lifecycle.+ */+ openGateway(creds: QQCredentials, handlers: QQGatewayHandlers): Promise<QQGatewayConnection>;+}++// ---------------------------------------------------------------------------+// Production adapter over fetch + undici's WebSocket+// ---------------------------------------------------------------------------++/** Overall per-request deadline for the OpenAPI calls (token exchange, gateway lookup, sends). */+const CALL_TIMEOUT_MS = 15_000;++/**+ * Refresh the access token this many seconds before it expires. The platform keeps the+ * previous token valid for exactly this long while it issues a replacement, so the margin+ * is the documented overlap rather than a guess.+ */+const TOKEN_REFRESH_MARGIN_SEC = 60;++/** Gateway opcodes (the subset this adapter speaks; the platform reuses Discord's numbering). */+const OP = {+ DISPATCH: 0,+ HEARTBEAT: 1,+ IDENTIFY: 2,+ RESUME: 6,+ RECONNECT: 7,+ INVALID_SESSION: 9,+ HELLO: 10,+ HEARTBEAT_ACK: 11,+} as const;++/**+ * Close codes that mean "this session handle is dead, identify fresh next time" (4006+ * invalid session id, 4007 sequence error, and the 4900-4913 internal band the platform's+ * own guidance says to re-identify after). 4009 — connection expired — is the one drop+ * that stays resumable, which is why it is absent here.+ */+function closeCodeInvalidatesSession(code: number): boolean {+ return code === 4006 || code === 4007 || (code >= 4900 && code <= 4913);+}++/**+ * Close codes there is no point retrying: the bot is delisted (4914, connectable only in+ * the console's sandbox whitelist) or banned (4915). Reconnecting on a one-minute ceiling+ * forever would just log the same refusal until someone looks.+ */+function closeCodeIsFatal(code: number): boolean {+ return code === 4914 || code === 4915;+}++/**+ * How long a socket has to finish its handshake before it is dropped and retried.+ *+ * A socket that opened and then went quiet — a proxy that accepted the upgrade and+ * blackholed everything after it — never reaches HELLO, never starts a heartbeat, and never+ * fires `close`. Nothing else in this session would notice, so the binding would sit at+ * `connected` receiving nothing, forever. Generous next to a handshake that normally takes+ * one round trip.+ */+export const QQ_HANDSHAKE_TIMEOUT_MS = 30_000;++/**+ * The slice of the WebSocket API this session uses.+ *+ * Named as a type so a test can drive the handshake, the heartbeat and every close code+ * without opening a socket. It is not a module mock on purpose: the server suite shares one+ * module registry across files (see vitest.config.ts), so `vi.mock` is not available to it.+ */+export interface QQSocket {+ readonly readyState: number;+ addEventListener(type: "message", fn: (evt: { data: unknown }) => void): void;+ addEventListener(type: "error", fn: () => void): void;+ addEventListener(type: "close", fn: (evt: { code: number }) => void): void;+ send(data: string): void;+ close(): void;+}++/** Gateway reconnect backoff: 1s doubling to a 60s ceiling (a revoked secret retries once a minute). */+function defaultGatewayRetryMs(failures: number): number {+ return Math.min(1000 * 2 ** (failures - 1), 60_000);+}++/**+ * Readable failure text out of fetch's throw shapes. Nothing here may echo a request body:+ * the token exchange's carries the App Secret.+ */+function fetchErrorText(err: unknown): string {+ if (err instanceof Error) {+ if (err.name === "TimeoutError" || err.name === "AbortError") return "request timed out";+ const cause = (err as { cause?: unknown }).cause;+ if (cause instanceof Error && cause.message !== "") return cause.message;+ return err.message;+ }+ return String(err);+}++/**+ * The failure envelope. The OpenAPI answers `{err_code, message, trace_id}` and the token+ * endpoint answers `{code, message}` — two different families, so both are read and+ * `err_code` wins where the platform sends both.+ */+interface QQErrorBody {+ code?: number;+ err_code?: number;+ message?: string;+}++/**+ * The send failures whose own wording names an internal rule instead of the thing the+ * operator has to change. Everything else passes through untouched.+ *+ * 40034128 is the one this product can genuinely provoke on its own — the platform folds+ * "the reply window closed" and "the reply count ran out" into a single code, so the text+ * has to name both. qq-connector.ts exists largely to keep it from ever being returned.+ */+export function qqSendErrorText(errCode: number | undefined, message: string): string {+ if (errCode === 40034128) {+ return `${message} — QQ allows only a few replies to one message, within minutes of it`;+ }+ if (errCode === 40034005 || errCode === 304103 || errCode === 40034024) {+ return `${message} — the QQ message being replied to has expired`;+ }+ if (errCode === 40034105 || errCode === 40054013) {+ return `${message} — this QQ user has turned off messages from bots`;+ }+ return message;+}++export interface QQTransportOpts {+ /** Test hook: gateway reconnect backoff (default: exponential, 1s → 60s). */+ gatewayRetryMs?: (failures: number) => number;+ /** Test hook: the socket the gateway session runs on (default: undici's WebSocket). */+ createSocket?: (url: string) => QQSocket;+ /** Test hook: the handshake deadline (default QQ_HANDSHAKE_TIMEOUT_MS). */+ handshakeTimeoutMs?: number;+}++/** One bot's access token with early refresh, shared by the OpenAPI client and the gateway identify. */+interface TokenCache {+ get(): Promise<string>;+ invalidate(): void;+}++function tokenCacheOf(creds: QQCredentials): TokenCache {+ let token = "";+ let expiresAtMs = 0;+ let inFlight: Promise<string> | null = null;++ const exchange = async (): Promise<string> => {+ let res: Response;+ try {+ res = await fetch(`${QQ_API_BASE}/app/getAppAccessToken`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ appId: creds.appId, clientSecret: creds.appSecret }),+ signal: AbortSignal.timeout(CALL_TIMEOUT_MS),+ });+ } catch (err) {+ throw new Error(`Token exchange failed: ${fetchErrorText(err)}`);+ }+ const body = (await res.json().catch(() => null)) as (QQAppAccessToken & QQErrorBody) | null;+ if (body === null || typeof body.access_token !== "string" || body.access_token === "") {+ const detail = body?.message ?? `HTTP ${res.status}`;+ const code = body?.code ?? body?.err_code;+ throw new Error(+ `Token exchange failed: ${detail}${code !== undefined ? ` (code ${code})` : ""}`,+ );+ }+ const ttl = Number(body.expires_in);+ // A missing or nonsensical TTL falls back to the platform's own ceiling rather than+ // caching forever on a malformed response.+ const seconds = Number.isFinite(ttl) && ttl > 0 ? Math.min(ttl, 7200) : 7200;+ token = body.access_token;+ expiresAtMs = Date.now() + Math.max(seconds - TOKEN_REFRESH_MARGIN_SEC, 1) * 1000;+ return token;+ };++ return {+ async get(): Promise<string> {+ if (token !== "" && Date.now() < expiresAtMs) return token;+ // Collapse concurrent refreshes: a burst of sends must not each buy a token, which+ // the endpoint rate-limits (100001 Too many requests).+ inFlight ??= exchange().finally(() => {+ inFlight = null;+ });+ return inFlight;+ },+ invalidate(): void {+ expiresAtMs = 0;+ },+ };+}++/** The production client, plus the token cache the gateway session needs for its identify. */+interface ProductionClient extends QQBotClient {+ tokens: TokenCache;+}++function createProductionClient(creds: QQCredentials): ProductionClient {+ const tokens = tokenCacheOf(creds);++ const post = async (path: string, payload: Record<string, unknown>, retry = true) => {+ const token = await tokens.get();+ let res: Response;+ try {+ res = await fetch(`${QQ_API_BASE}${path}`, {+ method: "POST",+ headers: { "content-type": "application/json", authorization: `QQBot ${token}` },+ body: JSON.stringify(payload),+ signal: AbortSignal.timeout(CALL_TIMEOUT_MS),+ });+ } catch (err) {+ throw new Error(`Message send failed: ${fetchErrorText(err)}`);+ }+ if (res.status >= 200 && res.status < 300) return;+ const body = (await res.json().catch(() => null)) as QQErrorBody | null;+ if (res.status === 401) {+ // The cached token died before its stated expiry — a secret rotated in the console,+ // or a clock further off than the refresh margin covers. Drop it and replay ONCE, so+ // a genuinely revoked credential still surfaces as an error instead of looping.+ tokens.invalidate();+ if (retry) return post(path, payload, false);+ }+ const errCode = body?.err_code ?? body?.code;+ const detail = qqSendErrorText(errCode, body?.message ?? `HTTP ${res.status}`);+ throw new Error(+ `Message send failed: ${detail}${errCode !== undefined ? ` (code ${errCode})` : ""}`,+ );+ };++ return {+ tokens,+ async checkCredentials(): Promise<void> {+ await tokens.get();+ },+ sendMessage(args: QQSendArgs): Promise<void> {+ const path =+ args.kind === "group"+ ? `/v2/groups/${encodeURIComponent(args.openid)}/messages`+ : `/v2/users/${encodeURIComponent(args.openid)}/messages`;+ return post(path, {+ content: args.content,+ // 0 = plain text. Markdown, ark and rich-media types each need separate approval.+ msg_type: 0,+ msg_id: args.msgId,+ msg_seq: args.msgSeq,+ });+ },+ };+}++/** The production factory: plain HTTPS for the OpenAPI, undici's WebSocket for the gateway. */+export function createQQTransport(opts: QQTransportOpts = {}): QQTransport {+ const retryMs = opts.gatewayRetryMs ?? defaultGatewayRetryMs;+ const createSocket = opts.createSocket ?? ((url: string): QQSocket => new WebSocket(url));+ const handshakeMs = opts.handshakeTimeoutMs ?? QQ_HANDSHAKE_TIMEOUT_MS;+ return {+ createClient: (creds) => createProductionClient(creds),+ async openGateway(creds, handlers): Promise<QQGatewayConnection> {+ const session = new GatewaySession(createProductionClient(creds), handlers, {+ retryMs,+ createSocket,+ handshakeMs,+ });+ session.start();+ return { close: () => session.close() };+ },+ };+}++/**+ * One gateway session with its own reconnect loop.+ *+ * Every step of the handshake is the platform's, and each earns its line: HELLO carries the+ * heartbeat interval in milliseconds (a socket that stops sending them is closed), IDENTIFY+ * authenticates with the same `QQBot <token>` string the OpenAPI takes (a still-published+ * doc page describes a `Bot <appid>.<token>` form — that is the retired v1 scheme and it is+ * rejected), READY hands back a `session_id` that RESUME replays a dropped connection from,+ * and every DISPATCH's `s` is the sequence RESUME rewinds to — so `seq` is tracked from the+ * first frame, not from the first message.+ *+ * The reconnect decision is protocol state nobody above this file holds, which is why it+ * lives here: a close is resumable unless its code says the session handle is dead (4006 /+ * 4007 / the internal band), an INVALID_SESSION says the resume was refused, and a+ * RECONNECT is the platform asking for the same round trip while keeping the session+ * resumable. Two codes end the session for good — a delisted or banned bot will not connect+ * however long it is retried.+ *+ * The gateway URL is fetched once and reused across reconnects: `GET /gateway` is rate+ * limited to 2 requests a minute, which a reconnect storm would spend on nothing.+ *+ * Two watchdogs bound a session that is neither speaking nor closing, because a socket that+ * stops carrying traffic without a FIN — a NAT or proxy drop, and this path deliberately+ * inherits the admin proxy dispatcher — keeps `readyState` OPEN and fires no `close` at+ * all: one deadline on the handshake (QQ_HANDSHAKE_TIMEOUT_MS), and one on the heartbeat,+ * which the platform acknowledges with HEARTBEAT_ACK and which is therefore a round trip+ * rather than a write. Either drops the socket into the same fail-and-back-off path a real+ * close takes — and drives it directly rather than waiting on a `close` event a half-open+ * socket may never produce.+ *+ * What surfaces upward is only the outcome: `onReady` per successful handshake, `onError`+ * once per outage — the same contract the Feishu long connection and the Telegram poll loop+ * report, so the bridge's status means the same thing on all three channels.+ */+class GatewaySession {+ private ws: QQSocket | null = null;+ private closed = false;+ private failures = 0;+ /** The resume handle from READY; null until the first successful identify. */+ private sessionId: string | null = null;+ /** Latest dispatch sequence (the heartbeat's `d`, and the resume's). */+ private seq: number | null = null;+ /** Cached `GET /gateway` URL (see the class doc: 2 QPM). */+ private gatewayUrl: string | null = null;+ private heartbeat: ReturnType<typeof setInterval> | null = null;+ private retryTimer: ReturnType<typeof setTimeout> | null = null;+ /** Armed with the socket, disarmed by the handshake: see QQ_HANDSHAKE_TIMEOUT_MS. */+ private handshakeTimer: ReturnType<typeof setTimeout> | null = null;+ /** When the last HEARTBEAT_ACK arrived, against which the heartbeat tick measures silence. */+ private lastAckAt = 0;+ /** This outage already reported; the retries stay quiet until a handshake succeeds. */+ private reported = false;++ constructor(+ private readonly client: ProductionClient,+ private readonly handlers: QQGatewayHandlers,+ private readonly opts: {+ retryMs: (failures: number) => number;+ createSocket: (url: string) => QQSocket;+ handshakeMs: number;+ },+ ) {}++ start(): void {+ void this.connect();+ }++ close(): void {+ this.closed = true;+ this.stopHeartbeat();+ this.disarmHandshake();+ if (this.retryTimer !== null) clearTimeout(this.retryTimer);+ this.retryTimer = null;+ const ws = this.ws;+ this.ws = null;+ try {+ ws?.close();+ } catch {+ // A socket already closing throws on some paths; the session is going away regardless.+ }+ }++ private async connect(): Promise<void> {+ if (this.closed) return;+ try {+ const token = await this.client.tokens.get();+ if (this.closed) return;+ this.gatewayUrl ??= await this.fetchGatewayUrl(token);+ if (this.closed) return;+ this.openSocket(this.gatewayUrl, token);+ } catch (err) {+ this.fail(err);+ }+ }++ private async fetchGatewayUrl(token: string): Promise<string> {+ let res: Response;+ try {+ res = await fetch(`${QQ_API_BASE}/gateway`, {+ headers: { authorization: `QQBot ${token}` },+ signal: AbortSignal.timeout(CALL_TIMEOUT_MS),+ });+ } catch (err) {+ throw new Error(`Gateway lookup failed: ${fetchErrorText(err)}`);+ }+ const body = (await res.json().catch(() => null)) as (QQGatewayInfo & QQErrorBody) | null;+ if (body === null || typeof body.url !== "string" || body.url === "") {+ throw new Error(`Gateway lookup failed: ${body?.message ?? `HTTP ${res.status}`}`);+ }+ return body.url;+ }++ private openSocket(url: string, token: string): void {+ const ws = this.opts.createSocket(url);+ this.ws = ws;+ // The socket is open; nothing says the far end is listening. This is the deadline for+ // it to prove it, and it covers both silences: no HELLO, and an IDENTIFY nobody answers.+ this.handshakeTimer = setTimeout(() => {+ this.handshakeTimer = null;+ this.dropSocket(ws, new Error("gateway handshake did not complete"));+ }, this.opts.handshakeMs);+ this.handshakeTimer.unref?.();+ ws.addEventListener("message", (evt) => {+ if (this.ws !== ws) return;+ this.onFrame(String(evt.data), token);+ });+ // A WebSocket `error` event carries no usable detail and is always followed by `close`,+ // which is where the outage is reported; this listener exists so it is not unhandled.+ ws.addEventListener("error", () => {});+ ws.addEventListener("close", (evt) => {+ if (this.ws !== ws) return;+ this.stopHeartbeat();+ this.disarmHandshake();+ this.ws = null;+ if (closeCodeInvalidatesSession(evt.code)) {+ this.sessionId = null;+ this.seq = null;+ }+ if (closeCodeIsFatal(evt.code)) {+ this.closed = true;+ this.handlers.onError?.(+ new Error(+ `gateway refused this bot (close code ${evt.code}) — it is delisted or banned on the QQ open platform`,+ ),+ );+ return;+ }+ this.fail(new Error(`gateway connection closed (code ${evt.code})`));+ });+ }++ private onFrame(raw: string, token: string): void {+ let frame: QQGatewayFrame;+ try {+ frame = JSON.parse(raw) as QQGatewayFrame;+ } catch {+ return;+ }+ if (typeof frame.s === "number") this.seq = frame.s;+ switch (frame.op) {+ case OP.HELLO: {+ const interval = (frame.d as { heartbeat_interval?: number } | undefined)+ ?.heartbeat_interval;+ this.startHeartbeat(typeof interval === "number" && interval > 0 ? interval : 45_000);+ // A session handle from a previous connection makes this a resume; otherwise identify.+ this.send(+ this.sessionId !== null+ ? {+ op: OP.RESUME,+ d: { token: `QQBot ${token}`, session_id: this.sessionId, seq: this.seq ?? 0 },+ }+ : {+ op: OP.IDENTIFY,+ d: {+ token: `QQBot ${token}`,+ intents: QQ_INTENT_GROUP_AND_C2C,+ // Unsharded: this product runs one connection per bot.+ shard: [0, 1],+ // Documented as having no effect today; sent empty rather than inventing values.+ properties: {},+ },+ },+ );+ return;+ }+ case OP.DISPATCH:+ this.onDispatch(frame);+ return;+ case OP.INVALID_SESSION:+ // The resume was refused: forget the handle so the next handshake identifies fresh.+ this.sessionId = null;+ this.seq = null;+ this.ws?.close();+ return;+ case OP.RECONNECT:+ // Politely asked to reconnect; the session stays resumable.+ this.ws?.close();+ return;+ case OP.HEARTBEAT_ACK:+ // The one frame that proves the socket is still a round trip rather than a write+ // into a dead pipe. startHeartbeat measures its silence.+ this.lastAckAt = Date.now();+ return;+ default:+ // The webhook-only opcodes need no action.+ return;+ }+ }++ private onDispatch(frame: QQGatewayFrame): void {+ if (frame.t === "READY") {+ const d = frame.d as { session_id?: string } | undefined;+ if (typeof d?.session_id === "string") this.sessionId = d.session_id;+ this.onHandshake();+ return;+ }+ if (frame.t === "RESUMED") {+ this.onHandshake();+ return;+ }+ const evt = normalizeDispatch(frame);+ if (evt !== null) void this.handlers.onMessage(evt);+ }++ /** A handshake completed: the outage (if any) is over and the backoff resets. */+ private onHandshake(): void {+ this.disarmHandshake();+ this.failures = 0;+ this.reported = false;+ this.handlers.onReady?.();+ }++ private disarmHandshake(): void {+ if (this.handshakeTimer !== null) clearTimeout(this.handshakeTimer);+ this.handshakeTimer = null;+ }++ /**+ * Abandons a socket the session has given up on and starts the backoff itself.+ *+ * The `close` handler is not enough on its own here: the failure both watchdogs cover is+ * a socket that never fires `close`, and asking a half-open one to close is a request the+ * far end may never answer. Detaching first makes the `close` that may eventually arrive+ * a no-op (every listener is gated on `this.ws === ws`).+ */+ private dropSocket(ws: QQSocket, err: Error): void {+ if (this.ws !== ws) return;+ this.stopHeartbeat();+ this.disarmHandshake();+ this.ws = null;+ try {+ ws.close();+ } catch {+ // Same as close(): a socket already going away throws on some paths and it changes+ // nothing here.+ }+ this.fail(err);+ }++ private startHeartbeat(intervalMs: number): void {+ this.stopHeartbeat();+ const ws = this.ws;+ if (ws === null) return;+ // HELLO is the last thing heard from this socket so far, which is what the first+ // interval is measured against.+ this.lastAckAt = Date.now();+ this.heartbeat = setInterval(() => {+ // Two intervals of silence: the platform acknowledges every heartbeat, so a socket+ // still writable but no longer answering is a dead pipe rather than a slow one. One+ // interval would be a lost ack; two is an outage.+ if (Date.now() - this.lastAckAt > intervalMs * 2) {+ this.dropSocket(ws, new Error("gateway stopped acknowledging heartbeats"));+ return;+ }+ this.send({ op: OP.HEARTBEAT, d: this.seq });+ }, intervalMs);+ // A heartbeat must never be the reason the process cannot exit.+ this.heartbeat.unref?.();+ }++ private stopHeartbeat(): void {+ if (this.heartbeat !== null) clearInterval(this.heartbeat);+ this.heartbeat = null;+ }++ private send(frame: QQGatewayFrame): void {+ try {+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify(frame));+ } catch {+ // A send into a socket that died between the check and the write is the same outage+ // the `close` handler is about to report; there is nothing extra to say here.+ }+ }++ /** One report per outage, then retry with backoff — the Telegram poll loop's contract. */+ private fail(err: unknown): void {+ if (this.closed) return;+ this.failures += 1;+ if (!this.reported) {+ this.reported = true;+ this.handlers.onError?.(err);+ }+ this.retryTimer = setTimeout(() => {+ this.retryTimer = null;+ void this.connect();+ }, this.opts.retryMs(this.failures));+ this.retryTimer.unref?.();+ }+}++/** One gateway frame. `s` and `t` ride dispatches only. */+export interface QQGatewayFrame {+ op: number;+ d?: unknown;+ s?: number;+ t?: string;+ /** The dispatch's own event id (an alternative passive-reply anchor this product does not use). */+ id?: string;+}++/**+ * One dispatch frame reduced to the connector's inbound shape; null for anything that is+ * not one of the two message events this product answers.+ *+ * A single-chat message and a group @-message differ in exactly two places — where the+ * conversation's openid lives, and which author field carries the sender — so they+ * normalize to one record with a `kind` discriminator rather than two shapes. The group+ * event's sender is `author.member_openid`, NOT `user_openid`: that field exists on the+ * group event too and is empty there, so reading it would quietly yield blanks.+ *+ * `GROUP_MESSAGE_CREATE` — every group message rather than only the @-mentions — rides the+ * same intent when a console switch is on, and is deliberately dropped: a bot that answered+ * everything said in a group is not what binding a conversation to it asks for.+ */+export function normalizeDispatch(frame: QQGatewayFrame): QQInboundEvent | null {+ const d = frame.d as+ | {+ id?: string;+ content?: string;+ group_openid?: string;+ author?: { user_openid?: string; member_openid?: string };+ }+ | undefined;+ if (d === undefined || typeof d.id !== "string" || d.id === "") return null;+ // The platform strips the "@bot" prefix but not the space it sat in.+ const content = typeof d.content === "string" ? d.content.trim() : "";+ if (frame.t === "C2C_MESSAGE_CREATE") {+ const openid = d.author?.user_openid;+ if (typeof openid !== "string" || openid === "") return null;+ return { kind: "c2c", openid, messageId: d.id, content, senderOpenid: openid };+ }+ if (frame.t === "GROUP_AT_MESSAGE_CREATE") {+ const openid = d.group_openid;+ if (typeof openid !== "string" || openid === "") return null;+ const sender = d.author?.member_openid;+ return {+ kind: "group",+ openid,+ messageId: d.id,+ content,+ ...(typeof sender === "string" && sender !== "" ? { senderOpenid: sender } : {}),+ };+ }+ return null;+}diff --git a/packages/server/src/runtime/messaging/qq-connector.ts b/packages/server/src/runtime/messaging/qq-connector.tsnew file mode 100644index 00000000..47a3b551--- /dev/null+++ b/packages/server/src/runtime/messaging/qq-connector.ts@@ -0,0 +1,568 @@+/**+ * QQ messaging connector — the third implementation of the MessagingChannelConnector seam,+ * and the first one whose platform will not let a bot speak freely. It owns everything+ * QQ-specific: the config document's shape (App ID + App Secret), the transport behind it+ * (injectable for tests — see qq-api.ts), the reduction of the two subscribed gateway+ * events to the bridge's normalized inbound shape, and — the part with no counterpart on+ * the other two channels — the PASSIVE REPLY BUDGET.+ *+ * ## Why this file has a budget in it+ *+ * QQ has two ways to send a message and this product can only use one of them. A PASSIVE+ * REPLY carries the `msg_id` of an inbound message, and the platform allows a small,+ * fixed number of them per inbound message inside a short window (see+ * QQ_REPLY_BUDGET / QQ_PASSIVE_WINDOW_MS). An ACTIVE message carries no `msg_id`, is rate+ * limited per bot and per relationship, is capped at a thousand a day, and fails outright+ * for any user who has turned bot pushes off in their QQ client — a switch this product+ * cannot see, ask about, or work around. So every send here is a passive reply, and the+ * budget is not an optimization: past it the platform answers 40034128 and the message is+ * simply gone.+ *+ * The bridge's outbound model does not fit that shape on its own. It relays EVERY+ * completed assistant message of a run as its own chat message, and one run routinely+ * completes more of them than QQ will accept. So this connector reconciles the two:+ *+ * - The first `budget - 1` messages of an inbound message's answer go out immediately,+ * one per completed assistant message, exactly as on Feishu and Telegram. The chat+ * follows the run as it happens for as long as the budget can afford to.+ * - Everything after that accumulates in a tail buffer, which is sent as ONE combined+ * message using the reserved final slot. Dropping the end of a reply is the worst+ * failure available here, so nothing is ever dropped — it is combined.+ * - The tail is flushed after a short quiet period (QQ_TAIL_FLUSH_MS). This connector+ * cannot see run boundaries — the seam deliberately does not show it any — and quiet+ * is the honest local proxy for "the answer is finished". The delay applies only to+ * runs that overflowed the budget in the first place.+ * - The approval notice competes for the same budget, and it must not lose: a run+ * blocked on approval will not produce another message until a human acts, so a notice+ * that waited for the run to finish would wait forever. It is therefore an ordinary+ * send — it takes an immediate slot when one is free, and otherwise joins the tail,+ * whose quiet timer fires a second later precisely because the run has gone quiet+ * waiting for the approval. Either way it arrives.+ * - Once the final slot is spent, further messages keep accumulating and are flushed by+ * the next inbound message, whose `msg_id` carries a fresh budget — that is the only new+ * budget that ever exists — provided the message they were written for has not itself+ * expired in the meantime (see noteInbound).+ * - A chat's accounting lives no longer than the connection that opened it. Closing the+ * gateway — the unbind, or the restart a credential change makes — forgets that+ * account's ledgers, so nothing withheld can arrive in a chat the binding has stopped+ * answering; and a chat left quiet past the window is swept when the map next grows.+ *+ * ## Why an undeliverable reply throws instead of vanishing+ *+ * With no fundable slot — no inbound message yet, the window closed, or the budget spent+ * with the tail already flushed — a send THROWS rather than silently returning. QQ offers+ * no push this product may use, so the honest report is that the reply did not arrive, and+ * the bridge turns that into one error record (the error recorder collapses a storm of the+ * same code into one row per window, so a conversation driven from the web UI does not+ * flood it). Silence would be worse in both directions: the "send test message" button+ * would claim a delivery that never happened, and a user watching QQ for an answer would+ * have nothing to explain its absence.+ *+ * ## Why `replyText` and `sendText` do the same thing here+ *+ * On Feishu and Telegram a reply-to is a visible relation — the chat renders a quote header+ * — which is why the bridge threads a run's first message onto the inbound one and sends+ * the rest plainly. On QQ `msg_id` is an authorization anchor, not a quote: a passive reply+ * renders exactly like any other message. So both seam methods resolve to the same+ * operation, and the bridge's threading choice is invisible here rather than wrong.+ *+ * ## Media+ *+ * Text only, in both directions. Inbound images are not normalized (a non-text message+ * reads as no text, which the bridge answers with its notice) and outbound files are+ * refused with a reason — see refuseMedia, which explains what QQ would require.+ */+import { chunkMessagingText } from "./bridge.js";+import type {+ MessagingChannelConnector,+ MessagingClient,+ MessagingConnection,+ MessagingConnectorHandlers,+} from "./connector.js";+import type {+ QQBotClient,+ QQChatKind,+ QQCredentials,+ QQInboundEvent,+ QQTransport,+} from "./qq-api.js";++/** The QQ binding's stored config document (`messaging_bindings.config_json`). */+export interface QQBindingConfig extends Record<string, unknown> {+ appId: string;+ appSecret: string;+}++/**+ * How many passive replies one inbound message funds, per chat scene. These are the+ * platform's numbers and they are NOT the same on both sides: a single chat allows 4, a+ * group 5.+ */+export const QQ_REPLY_BUDGET: Record<QQChatKind, number> = { c2c: 4, group: 5 };++/**+ * The tighter of the two budgets, which is what channel-neutral callers clamp to. Using the+ * smaller number everywhere keeps a binding's delivery behaviour the same whether the bot+ * was messaged in a single chat or a group — a setting that changed meaning depending on+ * where the last message came from would be indefensible.+ */+export const QQ_MIN_REPLY_BUDGET = Math.min(...Object.values(QQ_REPLY_BUDGET));++/**+ * How long an inbound message stays repliable.+ *+ * The platform's own documentation contradicts itself here: the single-chat overview says+ * 60 minutes while the `msg_id` parameter table on the same page says 5, and the group+ * pages say 5 in both places. 5 minutes is the number every normative table agrees on, so+ * it is the one this product designs against — treating the window as short can only cost+ * a reply that would have been delivered, while treating it as long costs replies that are+ * silently rejected.+ */+export const QQ_PASSIVE_WINDOW_MS = 5 * 60_000;++/**+ * How long the tail waits for the run to say something else before it is sent.+ *+ * Short enough that a finished answer is not left hanging, long enough that a run+ * completing several messages in quick succession combines them into one send instead of+ * spending the final slot on the first of them.+ */+export const QQ_TAIL_FLUSH_MS = 1500;++/**+ * Ceiling on the withheld tail's size. It exists only as a bound — one run's output is+ * finite — and when it is hit the OLDEST buffered text is dropped, never the newest: the+ * end of an answer is its conclusion, and the elision marker says what happened.+ */+export const QQ_TAIL_MAX_CHARS = 20_000;++/** Marker left in place of buffered text dropped by the tail ceiling (bilingual, like the other chat notices). */+const QQ_TAIL_ELIDED = "…(earlier part omitted 前略)…";++/**+ * The bridge's outbound-file shape, mirrored structurally rather than imported: it is a+ * two-field record, and matching it by structure keeps this connector compiling against a+ * seam it never adds to.+ */+interface QQOutboundFile {+ fileName: string;+ data: Buffer;+}++/**+ * Outbound media, refused rather than faked.+ *+ * QQ does have a rich-media path, and this product cannot reach it. Sending a picture on+ * API v2 is a two-step: the bytes are first registered against `/v2/{users,groups}/…/files`,+ * which takes a PUBLICLY REACHABLE https URL — the same requirement that ruled the webhook+ * mode out and made this a gateway connection in the first place — and only then can a+ * `msg_type: 7` message reference the handle it returns. Documents are worse still: the+ * platform lists a file type and does not open it. And any such message would spend a slot+ * from the same passive-reply budget the text is already rationing.+ *+ * So the honest answer is a refusal that names the reason. The bridge records one error per+ * undeliverable file and the reply's text still arrives — quietly resolving would tell it a+ * picture reached a chat that never received one.+ */+function refuseMedia(file: QQOutboundFile): Promise<never> {+ return Promise.reject(+ new Error(+ `QQ cannot receive "${file.fileName}": sending a file to QQ requires a publicly reachable URL for it, which this server has no way to provide`,+ ),+ );+}++/** Narrows a stored config document; throws a readable error on a malformed one. */+export function qqConfigOf(config: Record<string, unknown>): QQBindingConfig {+ const { appId, appSecret } = config;+ if (+ typeof appId !== "string" ||+ appId === "" ||+ typeof appSecret !== "string" ||+ appSecret === ""+ ) {+ throw new Error("malformed qq binding config (appId/appSecret)");+ }+ return { appId, appSecret };+}++/**+ * The chat id the bridge stores and hands back on every outbound send. A QQ chat is a+ * (scene, openid) pair — the same openid can name a user on one side and a group on the+ * other, and the two are answered by different endpoints — so both ride the id.+ */+export function qqChatIdOf(kind: QQChatKind, openid: string): string {+ return `${kind}:${openid}`;+}++/** The inverse; throws on an id this connector did not mint. */+export function parseQQChatId(chatId: string): { kind: QQChatKind; openid: string } {+ const i = chatId.indexOf(":");+ const kind = i > 0 ? chatId.slice(0, i) : "";+ const openid = i > 0 ? chatId.slice(i + 1) : "";+ if ((kind !== "c2c" && kind !== "group") || openid === "") {+ throw new Error(`malformed qq chat id "${chatId}"`);+ }+ return { kind, openid };+}++/**+ * The reply ref: the chat id with the message's own id appended. It is also the bridge's+ * inbound dedupe key, so it must identify the message rather than the delivery — which is+ * exactly what it does, and it matters here more than on the other channels: the platform+ * documents that it may push the same `msg_id` more than once to guarantee delivery.+ */+function qqReplyRefOf(kind: QQChatKind, openid: string, messageId: string): string {+ return `${qqChatIdOf(kind, openid)}:${messageId}`;+}++/** Reads a reply ref back to its chat (the message id is not needed: see the module doc). */+function chatOfReplyRef(ref: string): { kind: QQChatKind; openid: string } {+ const cut = ref.lastIndexOf(":");+ if (cut <= 0) throw new Error(`malformed qq reply ref "${ref}"`);+ return parseQQChatId(ref.slice(0, cut));+}++/**+ * One chat's passive-reply state: which inbound message is currently repliable, how much+ * of its budget is spent, and what is waiting for the reserved final slot.+ *+ * Kept per chat rather than per message on purpose. A reply always anchors to the NEWEST+ * inbound message of its chat, because that is the one furthest from expiring; an older+ * message's remaining budget is worth nothing next to a window that may have minutes left.+ */+interface QQReplyLedger {+ /** The bot this chat belongs to — what a closing connection matches its own ledgers on. */+ appId: string;+ kind: QQChatKind;+ openid: string;+ /** The message replies anchor to; null before the bot has ever been messaged here. */+ msgId: string | null;+ /** When it arrived (the window is measured from here). */+ receivedAt: number;+ /** Replies already sent against `msgId` — also the next `msg_seq`, which must never repeat. */+ spent: number;+ /** Text withheld for the reserved final slot. */+ tail: string[];+ /**+ * The client the last send used, which is the one a deferred flush uses too. Held here+ * rather than passed in: a flush can be triggered by an INBOUND event, whose path has no+ * outbound client of its own, and minting one there would open a second token cache for+ * the same bot. Null until this chat has sent something — and a tail cannot exist before+ * then, so a flush never finds it null.+ */+ bot: QQBotClient | null;+ timer: ReturnType<typeof setTimeout> | null;+ /** Sends are serialised per chat: `msg_seq` must increase in the order the platform sees them. */+ chain: Promise<void>;+}++export interface QQConnectorOpts {+ /** Test hook: how long the tail waits for more output before it is sent (default 1500ms). */+ tailFlushMs?: number;+ now?: () => number;+}++export class QQConnector implements MessagingChannelConnector {+ readonly channel = "qq" as const;+ /**+ * The budget channel-neutral callers clamp to — the bridge uses it to cap the+ * one-message-per-line split, whose own ceiling of 20 is meaningless against 4.+ */+ readonly replyBudget = QQ_MIN_REPLY_BUDGET;++ /**+ * Passive-reply state per `(appId, chat)`. It lives on the connector rather than on a+ * client, because the two halves that need it arrive separately: inbound events come+ * through `connect`, and sends through the client `createClient` hands the bridge. The+ * account is part of the key so two bindings on different bots can never spend each+ * other's budget.+ */+ private readonly ledgers = new Map<string, QQReplyLedger>();+ private readonly tailFlushMs: number;+ private readonly now: () => number;++ constructor(+ private readonly transport: QQTransport,+ opts: QQConnectorOpts = {},+ ) {+ this.tailFlushMs = opts.tailFlushMs ?? QQ_TAIL_FLUSH_MS;+ this.now = opts.now ?? (() => Date.now());+ }++ async createClient(config: Record<string, unknown>): Promise<MessagingClient> {+ const creds = qqConfigOf(config);+ const bot = this.transport.createClient(creds);+ const deliver = (chatId: string, text: string): Promise<void> => {+ const { kind, openid } = parseQQChatId(chatId);+ return this.enqueue(creds, bot, kind, openid, text);+ };+ // Assembled into a variable rather than returned as a literal: the media methods below+ // are refusals rather than implementations, and a channel that grows one later should+ // be able to fill them in without the shape of this function changing.+ const client = {+ async checkCredentials(): Promise<null> {+ await bot.checkCredentials();+ // The platform has no call that names the bot, so there is no account label to+ // surface — the App ID the user just typed is the only identity, and echoing it+ // back would confirm nothing.+ return null;+ },+ sendText: (chatId: string, text: string) => deliver(chatId, text),+ // Same operation as sendText: `msg_id` is an authorization anchor on QQ, not a+ // visible quote, so there is no threading to honour (see the module doc).+ replyText: (ref: string, text: string) => {+ const { kind, openid } = chatOfReplyRef(ref);+ return this.enqueue(creds, bot, kind, openid, text);+ },+ sendImage: (_chatId: string, file: QQOutboundFile) => refuseMedia(file),+ sendFile: (_chatId: string, file: QQOutboundFile) => refuseMedia(file),+ };+ return client;+ }++ async connect(+ config: Record<string, unknown>,+ handlers: MessagingConnectorHandlers,+ ): Promise<MessagingConnection> {+ const creds = qqConfigOf(config);+ const connection = await this.transport.openGateway(creds, {+ onMessage: async (evt: QQInboundEvent) => {+ // The ledger learns of the new message BEFORE the bridge does: this is the moment+ // fresh budget exists, and anything the previous message could not fund goes out+ // on it, ahead of whatever this message's own answer will be.+ this.noteInbound(creds, evt);+ await handlers.onMessage({+ chatId: qqChatIdOf(evt.kind, evt.openid),+ chatKind: evt.kind === "c2c" ? "direct" : "group",+ messageId: qqReplyRefOf(evt.kind, evt.openid, evt.messageId),+ // Only text is read today; an empty content is every non-text message type+ // (image, voice, card, forwarded record), which the bridge answers with the+ // text-only notice. Inbound media is a follow-up, not a gap.+ text: evt.content !== "" ? evt.content : null,+ ...(evt.senderOpenid !== undefined ? { senderName: evt.senderOpenid } : {}),+ });+ },+ ...(handlers.onReady ? { onReady: handlers.onReady } : {}),+ ...(handlers.onError ? { onError: handlers.onError } : {}),+ });+ return {+ close: () => {+ connection.close();+ // A ledger exists only because THIS gateway delivered an inbound message, and a+ // passive reply may not outlive the binding that earned it: without this, a tail+ // withheld a second ago is sent into the chat after the user turned the connection+ // off, and a tail from before a disable is carried onto the first message after a+ // re-enable. Closing the gateway alone leaves both, because the ledgers hang off+ // the connector rather than off the connection.+ this.dropLedgers(creds.appId);+ },+ };+ }++ // —— The passive-reply budget ————————————————————————————————————————————++ private ledgerKey(appId: string, kind: QQChatKind, openid: string): string {+ return `${appId}:${kind}:${openid}`;+ }++ private ledgerFor(appId: string, kind: QQChatKind, openid: string): QQReplyLedger {+ const key = this.ledgerKey(appId, kind, openid);+ let ledger = this.ledgers.get(key);+ if (ledger === undefined) {+ // Every chat the bot is ever messaged in opens a ledger, each able to hold+ // QQ_TAIL_MAX_CHARS — so the map is swept whenever it is about to grow. Nothing past+ // the reply window can be replied to at all (see repliable), which makes an expired+ // ledger's whole content unusable: its budget funds nothing, and its tail would be+ // dropped by the next noteInbound anyway.+ this.evictExpired();+ ledger = {+ appId,+ kind,+ openid,+ msgId: null,+ receivedAt: 0,+ spent: 0,+ tail: [],+ bot: null,+ timer: null,+ chain: Promise.resolve(),+ };+ this.ledgers.set(key, ledger);+ }+ return ledger;+ }++ /** Clears a ledger's pending flush and forgets it. */+ private dropLedger(key: string, ledger: QQReplyLedger): void {+ if (ledger.timer !== null) clearTimeout(ledger.timer);+ this.ledgers.delete(key);+ }++ /** Forgets every ledger of one credential set — the connection's close (see connect). */+ private dropLedgers(appId: string): void {+ for (const [key, ledger] of this.ledgers) {+ if (ledger.appId === appId) this.dropLedger(key, ledger);+ }+ }++ /**+ * Forgets every ledger whose anchor message is past the reply window. An unanchored one+ * is left alone: it holds no budget to lose, and the client that just created it is+ * holding the object.+ */+ private evictExpired(): void {+ for (const [key, ledger] of this.ledgers) {+ if (ledger.msgId === null) continue;+ if (this.now() - ledger.receivedAt <= QQ_PASSIVE_WINDOW_MS) continue;+ this.dropLedger(key, ledger);+ }+ }++ /**+ * A new inbound message: fresh budget, and the moment a withheld tail can finally go out.+ *+ * A tail is carried onto the new budget only while the message it was written for is+ * still inside its own window. Past that it is dropped — the one place anything is — and+ * deliberately: text withheld longer than the platform's whole reply window is no longer+ * an answer to anything the user still has in view, and delivering it as the first thing+ * they see after saying "hi" would read as the bot malfunctioning. The loss is bounded by+ * the same window everything else on this channel is.+ */+ private noteInbound(creds: QQCredentials, evt: QQInboundEvent): void {+ const ledger = this.ledgerFor(creds.appId, evt.kind, evt.openid);+ // A REDELIVERY is not new budget. The platform repeats a `msg_id` to guarantee delivery+ // (see qqReplyRefOf) and the bridge's dedupe runs downstream of this, so a repeat lands+ // here mid-run — re-anchoring to the id already held would reset `spent` to zero and+ // make the next reply reuse a (msg_id, msg_seq) pair the platform has already accepted,+ // which it REFUSES (40054005) rather than deduplicates. Every remaining message of the+ // run would be rejected: half an answer, then silence. Nothing below may run for it,+ // the pending flush included — it is already scheduled against this same anchor.+ if (ledger.msgId === evt.messageId) return;+ if (ledger.timer !== null) {+ clearTimeout(ledger.timer);+ ledger.timer = null;+ }+ const carry = ledger.tail.length > 0 && this.repliable(ledger);+ if (!carry) ledger.tail = [];+ ledger.msgId = evt.messageId;+ ledger.receivedAt = this.now();+ ledger.spent = 0;+ if (carry) this.scheduleFlush(ledger, 0);+ }++ /** True while `ledger.msgId` can still be replied to at all. */+ private repliable(ledger: QQReplyLedger): boolean {+ return ledger.msgId !== null && this.now() - ledger.receivedAt <= QQ_PASSIVE_WINDOW_MS;+ }++ /**+ * One outbound body. Sends immediately while an ordinary slot is free, otherwise+ * withholds it for the reserved final slot; throws when the chat has no repliable+ * message at all, which is the one thing QQ gives no way around (see the module doc).+ */+ private async enqueue(+ creds: QQCredentials,+ bot: QQBotClient,+ kind: QQChatKind,+ openid: string,+ text: string,+ ): Promise<void> {+ const ledger = this.ledgerFor(creds.appId, kind, openid);+ ledger.bot = bot;+ if (!this.repliable(ledger)) {+ // `async` so this is a rejection rather than a synchronous throw: the seam's methods+ // are typed as promises, and a caller that only attaches `.catch` — as any caller+ // reasonably may — would never see a throw raised before the promise exists.+ throw new Error(+ "QQ only accepts replies to a message sent from QQ, within a few minutes of it — send the bot a message in QQ and it will answer",+ );+ }+ const budget = QQ_REPLY_BUDGET[kind];+ if (ledger.spent < budget - 1) {+ await this.chain(ledger, () => this.sendNow(ledger, text));+ return;+ }+ this.withhold(ledger, text);+ // The final slot is only spendable once. Past it the tail waits for the next inbound+ // message rather than being sent into a rejection.+ if (ledger.spent < budget) this.scheduleFlush(ledger, this.tailFlushMs);+ }++ /** Appends to the withheld tail, dropping from the FRONT if the ceiling is reached. */+ private withhold(ledger: QQReplyLedger, text: string): void {+ ledger.tail.push(text);+ let total = ledger.tail.reduce((n, part) => n + part.length + 2, 0);+ while (total > QQ_TAIL_MAX_CHARS && ledger.tail.length > 1) {+ const dropped = ledger.tail.shift();+ total -= (dropped?.length ?? 0) + 2;+ if (ledger.tail[0] !== QQ_TAIL_ELIDED) ledger.tail.unshift(QQ_TAIL_ELIDED);+ }+ }++ private scheduleFlush(ledger: QQReplyLedger, delayMs: number): void {+ if (ledger.timer !== null) clearTimeout(ledger.timer);+ ledger.timer = setTimeout(() => {+ ledger.timer = null;+ void this.chain(ledger, () => this.flush(ledger)).catch(() => {});+ }, delayMs);+ // A pending flush must never be the reason the process cannot exit.+ ledger.timer.unref?.();+ }++ /**+ * Spends the reserved final slot on everything withheld, as one message. A combined tail+ * over the channel's size cap is chunked as usual and only its FIRST chunk is sent — the+ * rest returns to the tail, to ride the next inbound message's budget rather than a+ * rejection.+ */+ private async flush(ledger: QQReplyLedger): Promise<void> {+ if (ledger.tail.length === 0) return;+ if (!this.repliable(ledger) || ledger.spent >= QQ_REPLY_BUDGET[ledger.kind]) return;+ const chunks = chunkMessagingText(ledger.tail.join("\n\n"));+ const head = chunks[0];+ if (head === undefined) {+ ledger.tail = [];+ return;+ }+ ledger.tail = chunks.slice(1);+ try {+ await this.sendNow(ledger, head);+ } catch (err) {+ // The slot is spent (sendNow reserves the sequence number before the wire) but the+ // TEXT is not lost: `head` goes back to the front of the tail, so the next inbound+ // message's budget carries it. Anything withheld while the send was in flight was+ // appended to that same array and keeps its place behind it.+ ledger.tail.unshift(head);+ throw err;+ }+ }++ /** One real send: the next `msg_seq` against the ledger's anchor message. */+ private async sendNow(ledger: QQReplyLedger, text: string): Promise<void> {+ const msgId = ledger.msgId;+ const bot = ledger.bot;+ if (msgId === null || bot === null) return;+ // Reserved before the await: a rejected send has still consumed its sequence number,+ // and reusing one is refused by the platform (40054005) rather than retried.+ ledger.spent += 1;+ await bot.sendMessage({+ kind: ledger.kind,+ openid: ledger.openid,+ content: text,+ msgId,+ msgSeq: ledger.spent,+ });+ }++ /**+ * Appends to the chat's send chain. Two sends against one `msg_id` must reach the+ * platform in `msg_seq` order, and the chain never rejects — the caller's promise carries+ * the failure, and one failed send must not poison the chat's later ones.+ */+ private chain(ledger: QQReplyLedger, run: () => Promise<void>): Promise<void> {+ const result = ledger.chain.then(run);+ ledger.chain = result.catch(() => {});+ return result;+ }+}diff --git a/packages/server/test/messaging-qq-transport.test.ts b/packages/server/test/messaging-qq-transport.test.tsnew file mode 100644index 00000000..ee093260--- /dev/null+++ b/packages/server/test/messaging-qq-transport.test.ts@@ -0,0 +1,535 @@+/**+ * The QQ production adapter — the half of the channel that talks to Tencent.+ *+ * 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.+ *+ * 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).+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import type {+ QQCredentials,+ QQGatewayFrame,+ QQInboundEvent,+ QQSocket,+} from "../src/runtime/messaging/qq-api.js";+import {+ QQ_API_BASE,+ QQ_INTENT_GROUP_AND_C2C,+ createQQTransport,+} from "../src/runtime/messaging/qq-api.js";+import { waitFor } from "./helpers.js";++const CREDS: QQCredentials = { appId: "102000001", appSecret: "qq-app-secret-ABCD-1234" };++/** Gateway opcodes, spelled out here so a test asserts the wire number rather than a name. */+const OP_DISPATCH = 0;+const OP_HEARTBEAT = 1;+const OP_IDENTIFY = 2;+const OP_RESUME = 6;+const OP_RECONNECT = 7;+const OP_INVALID_SESSION = 9;+const OP_HELLO = 10;+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.+ */+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);+ if (answered !== null) return answered;+ if (call.url.endsWith("/app/getAppAccessToken")) {+ return jsonResponse({ access_token: `token-${calls.length}`, 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;+ }+}++/** 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.+// ---------------------------------------------------------------------------++class FakeSocket {+ /** WebSocket.OPEN; the session only ever writes into a socket in this state. */+ readyState = 1;+ readonly sent: QQGatewayFrame[] = [];+ closes = 0;+ /** Answer every heartbeat with HEARTBEAT_ACK, as a healthy gateway does. */+ autoAck = true;+ private readonly listeners = new Map<string, ((evt: never) => void)[]>();++ constructor(readonly url: string) {}++ // The seam's own three signatures, so the fake is assignable to QQSocket rather than+ // cast into it: a fake whose listener shape has drifted should not compile.+ addEventListener(type: "message", fn: (evt: { data: unknown }) => void): void;+ addEventListener(type: "error", fn: () => void): void;+ addEventListener(type: "close", fn: (evt: { code: number }) => void): void;+ addEventListener(type: string, fn: (evt: never) => void): void {+ const list = this.listeners.get(type) ?? [];+ list.push(fn);+ this.listeners.set(type, list);+ }++ send(data: string): void {+ const frame = JSON.parse(data) as QQGatewayFrame;+ this.sent.push(frame);+ if (frame.op === OP_HEARTBEAT && this.autoAck) this.deliver({ op: OP_HEARTBEAT_ACK });+ }++ close(): void {+ this.closes += 1;+ this.readyState = 3;+ }++ /** Pushes one frame in, as a dispatch would. */+ deliver(frame: QQGatewayFrame): void {+ this.emit("message", { data: JSON.stringify(frame) });+ }++ /** The far end closed with this code. */+ drop(code: number): void {+ this.readyState = 3;+ this.emit("close", { code });+ }++ /** The frames of one opcode, in order. */+ frames(op: number): QQGatewayFrame[] {+ return this.sent.filter((f) => f.op === op);+ }++ private emit(type: string, evt: { data?: unknown; code?: number }): void {+ for (const fn of this.listeners.get(type) ?? []) (fn as (e: unknown) => void)(evt);+ }+}++/** A gateway under test: the transport, the sockets it opened, and what it reported. */+interface Harness {+ sockets: FakeSocket[];+ inbound: QQInboundEvent[];+ errors: unknown[];+ readies: number;+ open(): Promise<{ close(): void }>;+}++function harnessOf(opts: { handshakeTimeoutMs?: number; retryMs?: number } = {}): Harness {+ const sockets: FakeSocket[] = [];+ const inbound: QQInboundEvent[] = [];+ const errors: unknown[] = [];+ const state = { readies: 0 };+ const transport = createQQTransport({+ gatewayRetryMs: () => opts.retryMs ?? 5,+ createSocket: (url): QQSocket => {+ const socket = new FakeSocket(url);+ sockets.push(socket);+ return socket;+ },+ // Long enough that a test which is not about this deadline never trips it.+ handshakeTimeoutMs: opts.handshakeTimeoutMs ?? 10_000,+ });+ return {+ sockets,+ inbound,+ errors,+ get readies() {+ return state.readies;+ },+ async open() {+ const conn = await transport.openGateway(CREDS, {+ onMessage: (evt) => {+ inbound.push(evt);+ },+ onReady: () => {+ state.readies += 1;+ },+ onError: (err) => {+ errors.push(err);+ },+ });+ await waitFor(() => sockets.length > 0);+ return conn;+ },+ };+}++/** HELLO → (IDENTIFY | RESUME) → READY, the handshake every connected test starts from. */+function handshake(socket: FakeSocket, sessionId = "gw-session-1", intervalMs = 45_000): void {+ socket.deliver({ op: OP_HELLO, d: { heartbeat_interval: intervalMs } });+ socket.deliver({ op: OP_DISPATCH, t: "READY", s: 1, d: { session_id: sessionId } });+}++// ---------------------------------------------------------------------------++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,+ });+ });+ });++ 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);+ },+ );+ });++ 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);+ },+ );+ });++ 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);+ },+ );+ });+});++describe("the QQ OpenAPI send", () => {+ const args = {+ kind: "c2c" as const,+ openid: "user_openid_aaa",+ content: "hello",+ msgId: "msg_1",+ msgSeq: 2,+ };++ 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,+ });+ });+ });++ 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",+ ]);+ },+ );+ });++ 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");+ },+ );+ });+});++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();+ }+ });+ });++ 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();+ }+ });+ });++ 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);+ } 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();+ }+ });+ });++ 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");+ } 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");+ } finally {+ conn.close();+ }+ });+ });++ 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);+ });+ });+});diff --git a/packages/server/test/messaging-qq.test.ts b/packages/server/test/messaging-qq.test.tsnew file mode 100644index 00000000..54bdd394--- /dev/null+++ b/packages/server/test/messaging-qq.test.ts@@ -0,0 +1,831 @@+/**+ * 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.+ *+ * 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 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; and a send with nothing to reply to failing+ * loudly rather than pretending. No test opens a socket.+ */+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { approvalDecision, assistantText, toolCall } from "@prismshadow/penguin-core";+import type { ApproveFn, OmniMessage, TextPayload } from "@prismshadow/penguin-core";+import type {+ MessagingBindingsResponse,+ QQBindingResponse,+ QQTestResponse,+} 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_APPROVAL_NOTICE,+ MESSAGING_TEST_MESSAGE,+ MESSAGING_TEXT_ONLY_NOTICE,+} from "../src/runtime/messaging/bridge.js";+import type {+ QQBotClient,+ QQCredentials,+ QQGatewayConnection,+ QQGatewayHandlers,+ QQInboundEvent,+ QQSendArgs,+ QQTransport,+} from "../src/runtime/messaging/qq-api.js";+import { normalizeDispatch, qqSendErrorText } from "../src/runtime/messaging/qq-api.js";+import type { QQConnectorOpts } from "../src/runtime/messaging/qq-connector.js";+import {+ QQ_PASSIVE_WINDOW_MS,+ QQ_REPLY_BUDGET,+ QQConnector,+ parseQQChatId,+ qqChatIdOf,+ qqConfigOf,+} from "../src/runtime/messaging/qq-connector.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";+const USER_OPENID = "user_openid_aaa";+const GROUP_OPENID = "group_openid_bbb";++/**+ * The tail's flush delay in tests. Non-zero on purpose: a zero timer would fire between two+ * relayed messages of the same run (the bridge awaits a repo read and a client build per+ * message), which would coalesce a different set than production does. Small enough that+ * every wait below still settles well inside waitFor's timeout.+ */+const TAIL_MS = 120;++// ---------------------------------------------------------------------------+// Fake transport: records sends, and hands each opened gateway back to the test so it can+// push events. Never constructs a socket or a fetch.+// ---------------------------------------------------------------------------++class FakeQQClient implements QQBotClient {+ readonly sends: QQSendArgs[] = [];+ credentialChecks = 0;+ constructor(+ readonly creds: QQCredentials,+ private readonly t: FakeQQTransport,+ ) {}++ async checkCredentials(): Promise<void> {+ this.credentialChecks++;+ if (this.t.failAuth !== null) throw new Error(this.t.failAuth);+ }++ async sendMessage(args: QQSendArgs): Promise<void> {+ if (this.t.failSend !== null) throw new Error(this.t.failSend);+ this.sends.push(args);+ }+}++class FakeQQGateway implements QQGatewayConnection {+ closed = false;+ constructor(+ readonly creds: QQCredentials,+ private readonly handlers: QQGatewayHandlers,+ ) {}+ close(): void {+ this.closed = true;+ }+ /** Pushes one inbound event, as the gateway's dispatch would. */+ fire(evt: QQInboundEvent): Promise<void> {+ return Promise.resolve(this.handlers.onMessage(evt));+ }+}++class FakeQQTransport implements QQTransport {+ readonly clients: FakeQQClient[] = [];+ readonly gateways: FakeQQGateway[] = [];+ /** Non-null makes the credential probe throw with this message. */+ failAuth: string | null = null;+ /** Non-null makes every send throw with this message. */+ failSend: string | null = null;++ createClient(creds: QQCredentials): FakeQQClient {+ const client = new FakeQQClient(creds, this);+ this.clients.push(client);+ return client;+ }++ async openGateway(+ creds: QQCredentials,+ handlers: QQGatewayHandlers,+ ): Promise<QQGatewayConnection> {+ const gw = new FakeQQGateway(creds, handlers);+ this.gateways.push(gw);+ handlers.onReady?.();+ return gw;+ }++ lastGateway(): FakeQQGateway {+ const gw = this.gateways.at(-1);+ if (!gw) throw new Error("no fake qq gateway was opened");+ return gw;+ }++ /** Every send across every client, in the order the platform would have seen them. */+ allSends(): QQSendArgs[] {+ return this.clients.flatMap((c) => c.sends);+ }+}++/** A single-chat text message from a fixed user. */+function c2cText(content: string, messageId: string): QQInboundEvent {+ return { kind: "c2c", openid: USER_OPENID, messageId, content, senderOpenid: USER_OPENID };+}++/** Fake Session: records each run's input payloads and replies with a fixed assistant text. */+function echoFakeSession(+ sessionId: string,+ runs: TextPayload[][],+ reply = "Reply text",+): RuntimeSession {+ return {+ sessionId,+ 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 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,+ 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,+ 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" });+ yield tc;+ 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(),+ };+}++// ---------------------------------------------------------------------------++describe("qq config and chat ids", () => {+ it("narrows a stored config and rejects a malformed one", () => {+ expect(qqConfigOf({ appId: APP_ID, appSecret: APP_SECRET })).toEqual({+ appId: APP_ID,+ appSecret: APP_SECRET,+ });+ expect(() => qqConfigOf({ appId: APP_ID })).toThrow(/malformed qq binding config/);+ expect(() => qqConfigOf({ appId: "", appSecret: APP_SECRET })).toThrow();+ });++ it("round-trips a chat id, which carries the scene as well as the openid", () => {+ // The same openid means different things on the two sides and is answered by different+ // endpoints, so the scene has to ride the id the bridge stores.+ expect(parseQQChatId(qqChatIdOf("c2c", USER_OPENID))).toEqual({+ kind: "c2c",+ openid: USER_OPENID,+ });+ expect(parseQQChatId(qqChatIdOf("group", GROUP_OPENID))).toEqual({+ kind: "group",+ openid: GROUP_OPENID,+ });+ expect(() => parseQQChatId("nonsense")).toThrow(/malformed qq chat id/);+ expect(() => parseQQChatId("c2c:")).toThrow();+ });+});++describe("normalizeDispatch", () => {+ it("reads the two subscribed events, each from its own author field", () => {+ // The group event's sender is member_openid; user_openid exists there too and is blank,+ // so reading the wrong one yields silent nonsense rather than an error.+ expect(+ normalizeDispatch({+ op: 0,+ t: "C2C_MESSAGE_CREATE",+ d: { id: "m1", content: "hello", author: { user_openid: USER_OPENID } },+ }),+ ).toEqual({+ kind: "c2c",+ openid: USER_OPENID,+ messageId: "m1",+ content: "hello",+ senderOpenid: USER_OPENID,+ });+ expect(+ normalizeDispatch({+ op: 0,+ t: "GROUP_AT_MESSAGE_CREATE",+ d: {+ id: "m2",+ // The platform strips the @-mention but leaves the space it sat in.+ content: " status?",+ group_openid: GROUP_OPENID,+ author: { user_openid: "", member_openid: "member_1" },+ },+ }),+ ).toEqual({+ kind: "group",+ openid: GROUP_OPENID,+ messageId: "m2",+ content: "status?",+ senderOpenid: "member_1",+ });+ });++ it("takes the platform at its word on the @bot prefix and edits nothing else", () => {+ // The whole of this channel's mention handling: the platform removes the bot's own+ // mention from a group message's content and leaves the whitespace it sat in, and the+ // trim is this side's half of that contract. Pinned because it is the sibling of the+ // defect #497 fixed on the other two channels — where the placeholder or handle DOES+ // reach the connector and has to be resolved or cut.+ const mentioning = normalizeDispatch({+ op: 0,+ t: "GROUP_AT_MESSAGE_CREATE",+ d: {+ id: "m_at",+ content: " summarize what <@!member_2> said\t",+ group_openid: GROUP_OPENID,+ author: { member_openid: "member_1" },+ },+ });+ // A mention of somebody ELSE is content. This connector has no identity to resolve it+ // against and makes no claim about its shape, so whatever the platform put there+ // reaches the model exactly as it arrived — the trim is the only edit.+ expect(mentioning?.content).toBe("summarize what <@!member_2> said");+ // ...and a group message left with nothing but the stripped mention reads as no text,+ // which the bridge answers with the text-only notice instead of starting a run on it.+ expect(+ normalizeDispatch({+ op: 0,+ t: "GROUP_AT_MESSAGE_CREATE",+ d: {+ id: "m_bare",+ content: " ",+ group_openid: GROUP_OPENID,+ author: { member_openid: "member_1" },+ },+ })?.content,+ ).toBe("");+ });++ it("drops everything else the intent carries, including the un-mentioned group firehose", () => {+ for (const t of ["GROUP_MESSAGE_CREATE", "FRIEND_ADD", "READY", "RESUMED"]) {+ expect(normalizeDispatch({ op: 0, t, d: { id: "m", content: "x" } })).toBeNull();+ }+ // A message with no id cannot be replied to and is not a message this product can use.+ expect(normalizeDispatch({ op: 0, t: "C2C_MESSAGE_CREATE", d: { content: "x" } })).toBeNull();+ });+});++describe("qqSendErrorText", () => {+ it("names the rule behind the one failure this product can provoke", () => {+ expect(qqSendErrorText(40034128, "msg over limit")).toContain("only a few replies");+ expect(qqSendErrorText(40034005, "invalid msg_id")).toContain("expired");+ // Anything else is the platform's own wording, untouched.+ expect(qqSendErrorText(12345, "something else")).toBe("something else");+ expect(qqSendErrorText(undefined, "HTTP 500")).toBe("HTTP 500");+ });+});++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[][];++ /** Save the credentials, then flip the toggle on and wait for the gateway handshake. */+ const bindEnabled = async (sid: string, appId = APP_ID) => {+ expect((await api.put(BASE(sid), { appId, appSecret: APP_SECRET })).status).toBe(200);+ expect((await api.post(`${BASE(sid)}/state`, { enabled: true })).status).toBe(200);+ await waitFor(() => t.deps.messaging.statusOf(sid, "qq").state === "connected");+ };++ beforeEach(async () => {+ fake = new FakeQQTransport();+ t = await createTestApp({ qqTransport: fake, qqTailFlushMs: TAIL_MS });+ const { cookie } = await provisionUser(t.app, "birder");+ api = apiClient(t.app, cookie);+ projectId = "birder-default_project";+ runs = [];+ const row = sessionRowOf(SID, projectId);+ t.deps.sessionsRepo.insert(row);+ t.deps.manager.adopt(row, echoFakeSession(SID, runs));+ });+ afterEach(async () => {+ await t.cleanup();+ });++ // —— Routes ——————————————————————————————————————————————————————————————++ it("PUT saves the pair only (secret masked, App ID as the account, disabled, no gateway)", async () => {+ const res = await api.put(BASE(SID), { appId: APP_ID, appSecret: APP_SECRET });+ expect(res.status).toBe(200);+ const body = (await res.json()) as QQBindingResponse;+ expect(body.binding?.channel).toBe("qq");+ expect(body.binding?.appId).toBe(APP_ID);+ expect(body.binding?.appSecretMasked).toBe("qq-a…1234");+ expect(JSON.stringify(body)).not.toContain(APP_SECRET);+ expect(body.binding?.enabled).toBe(false);+ expect(body.status.state).toBe("disconnected");+ expect(fake.gateways).toHaveLength(0);+ // The App ID is the account identity, exactly as the Feishu app id is.+ expect(t.deps.messagingRepo.find(SID, "qq")?.accountId).toBe(APP_ID);++ // Blank secret keeps the stored one; still dark.+ expect((await api.put(BASE(SID), { appId: APP_ID })).status).toBe(200);+ expect(t.deps.messagingRepo.find(SID, "qq")?.config.appSecret).toBe(APP_SECRET);+ expect(fake.gateways).toHaveLength(0);++ // A first bind with no secret at all is refused.+ t.deps.messagingRepo.delete(SID, "qq");+ const bare = await api.put(BASE(SID), { appId: APP_ID });+ expect(bare.status).toBe(400);+ expect(((await bare.json()) as { error: { code: string } }).error.code).toBe(+ "qq_secret_required",+ );+ });++ it("POST /state owns the connection, and a re-save while enabled restarts the gateway", async () => {+ expect((await api.post(`${BASE(SID)}/state`, { enabled: true })).status).toBe(404);+ await bindEnabled(SID);+ expect(fake.lastGateway().creds).toEqual({ appId: APP_ID, appSecret: APP_SECRET });++ const rotated = "qq-app-secret-EFGH-5678";+ expect((await api.put(BASE(SID), { appId: APP_ID, appSecret: rotated })).status).toBe(200);+ expect(fake.gateways[0]!.closed).toBe(true);+ await waitFor(() => t.deps.messaging.statusOf(SID, "qq").state === "connected");+ expect(fake.lastGateway().creds.appSecret).toBe(rotated);++ const off = await api.post(`${BASE(SID)}/state`, { enabled: false });+ expect(((await off.json()) as QQBindingResponse).status.state).toBe("disconnected");+ expect(fake.lastGateway().closed).toBe(true);+ });++ it("the account is the App ID: saving never collides, enabling does", async () => {+ t.deps.sessionsRepo.insert(sessionRowOf(SID2, projectId));+ await bindEnabled(SID);+ expect(+ (await api.put(BASE(SID2), { appId: APP_ID, appSecret: "other-secret-9999" })).status,+ ).toBe(200);++ const blocked = await api.post(`${BASE(SID2)}/state`, { enabled: true });+ expect(blocked.status).toBe(409);+ const refusal = (await blocked.json()) as { error: { code: string; message: string } };+ expect(refusal.error.code).toBe("account_enabled_elsewhere");+ expect(refusal.error.message).not.toContain(SID);++ expect((await api.post(`${BASE(SID)}/state`, { enabled: false })).status).toBe(200);+ expect((await api.post(`${BASE(SID2)}/state`, { enabled: true })).status).toBe(200);+ await waitFor(() => t.deps.messaging.statusOf(SID2, "qq").state === "connected");+ });++ it("...and a save cannot carry an enabled connection onto another Session's bot either", async () => {+ // The enable gate's other half. A binding that is already ON keeps its connection+ // across a save and restarts it with the new credentials, so a PUT re-pointing it at+ // 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));+ await bindEnabled(SID, other);+ await bindEnabled(SID2, APP_ID);++ const collide = await api.put(BASE(SID2), { appId: other, appSecret: APP_SECRET });+ expect(collide.status).toBe(409);+ const refusal = (await collide.json()) as { error: { code: string; message: string } };+ expect(refusal.error.code).toBe("account_enabled_elsewhere");+ expect(refusal.error.message).not.toContain(SID);+ // Nothing was written and nothing was restarted.+ expect(t.deps.messagingRepo.find(SID2, "qq")?.accountId).toBe(APP_ID);++ // A DISABLED binding stays free to be saved onto that App ID: only the enable binds.+ expect((await api.post(`${BASE(SID2)}/state`, { enabled: false })).status).toBe(200);+ expect((await api.put(BASE(SID2), { appId: other, appSecret: APP_SECRET })).status).toBe(200);+ expect(t.deps.messagingRepo.find(SID2, "qq")?.accountId).toBe(other);+ });++ it("clearing the stored secret is gated on the connection being off", async () => {+ await bindEnabled(SID);+ const blocked = await api.put(BASE(SID), { appId: APP_ID, clearAppSecret: true });+ expect(blocked.status).toBe(409);+ expect(((await blocked.json()) as { error: { code: string } }).error.code).toBe(+ "messaging_disable_before_clear",+ );+ await api.post(`${BASE(SID)}/state`, { enabled: false });+ expect((await api.put(BASE(SID), { appId: APP_ID, clearAppSecret: true })).status).toBe(200);+ const cleared = (await (await api.get(BASE(SID))).json()) as QQBindingResponse;+ // The row and its account identity survive; only the secret is gone.+ expect(cleared.binding?.appSecretMasked).toBeUndefined();+ expect(cleared.binding?.appId).toBe(APP_ID);+ // ...and a config with no secret cannot be enabled.+ const enable = await api.post(`${BASE(SID)}/state`, { enabled: true });+ expect(enable.status).toBe(400);+ expect(((await enable.json()) as { error: { code: string } }).error.code).toBe(+ "qq_secret_required",+ );+ });++ it("the credential probe is the token exchange, and names no account", async () => {+ await api.put(BASE(SID), { appId: APP_ID, appSecret: APP_SECRET });+ const ok = (await (await api.post(`${BASE(SID)}/test`, {})).json()) as QQTestResponse;+ expect(ok.ok).toBe(true);+ // The platform has no call that identifies the bot, so success carries no label.+ expect(Object.keys(ok)).not.toContain("accountLabel");++ fake.failAuth = "invalid appid or secret";+ const bad = (await (await api.post(`${BASE(SID)}/test`, {})).json()) as QQTestResponse;+ expect(bad.ok).toBe(false);+ expect(bad.error).toContain("invalid appid");+ });++ it("GET /messaging lists qq beside the other channels", async () => {+ await bindEnabled(SID);+ const body = (await (+ await api.get(`/api/sessions/${SID}/messaging`)+ ).json()) as MessagingBindingsResponse;+ const qq = body.bindings.find((b) => b.binding.channel === "qq");+ expect(qq?.binding.enabled).toBe(true);+ expect(qq?.status.state).toBe("connected");+ expect(qq?.binding.channel === "qq" && qq.binding.appId).toBe(APP_ID);+ });++ // —— Inbound ————————————————————————————————————————————————————————————++ it("an inbound single-chat message starts a Task as ordinary user input and is answered", async () => {+ await bindEnabled(SID);+ await fake.lastGateway().fire(c2cText("what is the status?", "msg_1"));+ await waitFor(() => runs.length === 1);+ // No marker block and no special sender: the model does not learn where this came from.+ expect(runs[0]!.map((p) => p.text)).toEqual(["what is the status?"]);+ await waitFor(() => fake.allSends().length === 1);+ const sent = fake.allSends()[0]!;+ expect(sent).toMatchObject({+ kind: "c2c",+ openid: USER_OPENID,+ content: "Reply text",+ msgId: "msg_1",+ });+ // The chat is remembered with its scene, so a later send knows which endpoint to use.+ expect(t.deps.messagingRepo.find(SID, "qq")?.lastChatId).toBe(qqChatIdOf("c2c", USER_OPENID));+ });++ it("a redelivered message is a complete no-op (the platform repeats a msg_id on purpose)", async () => {+ await bindEnabled(SID);+ await fake.lastGateway().fire(c2cText("hello", "msg_dup"));+ await waitFor(() => runs.length === 1);+ await fake.lastGateway().fire(c2cText("hello", "msg_dup"));+ await new Promise((r) => setTimeout(r, 30));+ expect(runs).toHaveLength(1);+ });++ it("a message with no text gets the text-only notice, as a reply to that same message", async () => {+ await bindEnabled(SID);+ await fake+ .lastGateway()+ .fire({ kind: "c2c", openid: USER_OPENID, messageId: "msg_img", content: "" });+ await waitFor(() => fake.allSends().length === 1);+ expect(fake.allSends()[0]).toMatchObject({+ content: MESSAGING_TEXT_ONLY_NOTICE,+ msgId: "msg_img",+ msgSeq: 1,+ });+ expect(runs).toHaveLength(0);+ });++ // —— The budget ——————————————————————————————————————————————————————————++ it("a run of six messages reaches QQ as four, the last carrying the remainder", async () => {+ const row = sessionRowOf(SID2, projectId);+ t.deps.sessionsRepo.insert(row);+ t.deps.manager.adopt(row, multiMessageFakeSession(SID2, ["m1", "m2", "m3", "m4", "m5", "m6"]));+ await bindEnabled(SID2);+ await fake.lastGateway().fire(c2cText("go", "msg_budget"));++ await waitFor(() => fake.allSends().length === QQ_REPLY_BUDGET.c2c);+ // Nothing arrives after the reserved slot is spent, however long the test waits.+ await new Promise((r) => setTimeout(r, TAIL_MS * 3));+ const sends = fake.allSends();+ expect(sends).toHaveLength(4);+ expect(sends.map((s) => s.content)).toEqual(["m1", "m2", "m3", "m4\n\nm5\n\nm6"]);+ // One anchor message, and a sequence that increases without ever repeating: a repeated+ // (msg_id, msg_seq) pair is refused by the platform, not deduplicated away.+ expect(new Set(sends.map((s) => s.msgId))).toEqual(new Set(["msg_budget"]));+ expect(sends.map((s) => s.msgSeq)).toEqual([1, 2, 3, 4]);+ });++ it("a group chat gets the platform's larger budget", async () => {+ const row = sessionRowOf(SID2, projectId);+ t.deps.sessionsRepo.insert(row);+ t.deps.manager.adopt(row, multiMessageFakeSession(SID2, ["g1", "g2", "g3", "g4", "g5", "g6"]));+ await bindEnabled(SID2);+ await fake.lastGateway().fire({+ kind: "group",+ openid: GROUP_OPENID,+ messageId: "msg_group",+ content: "go",+ senderOpenid: "member_1",+ });+ await waitFor(() => fake.allSends().length === QQ_REPLY_BUDGET.group);+ await new Promise((r) => setTimeout(r, TAIL_MS * 3));+ const sends = fake.allSends();+ expect(sends).toHaveLength(5);+ expect(sends.map((s) => s.content)).toEqual(["g1", "g2", "g3", "g4", "g5\n\ng6"]);+ expect(sends.every((s) => s.kind === "group" && s.openid === GROUP_OPENID)).toBe(true);+ });++ 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);+ row.approvalMode = "always-ask";+ t.deps.sessionsRepo.insert(row);+ t.deps.manager.adopt(row, parkingAfterMessagesSession(SID2, ["a1", "a2", "a3"]));+ await bindEnabled(SID2);+ await fake.lastGateway().fire(c2cText("do something risky", "msg_approval"));++ await waitFor(() => fake.allSends().length === QQ_REPLY_BUDGET.c2c);+ await new Promise((r) => setTimeout(r, TAIL_MS * 3));+ const sends = fake.allSends();+ // Four sends, and nothing lost inside them. Which slot the notice lands in is not+ // pinned on purpose: the bridge sends a notice outside the relay chain, so it may+ // overtake a relayed message or ride the reserved slot with it. What must hold is that+ // it arrives at all — the run is parked until a human acts on it, so a notice that+ // waited for the run to finish would wait forever.+ expect(sends).toHaveLength(4);+ expect(sends.map((s) => s.msgSeq)).toEqual([1, 2, 3, 4]);+ const everything = sends.map((s) => s.content).join("\n");+ for (const part of ["a1", "a2", "a3", MESSAGING_APPROVAL_NOTICE]) {+ expect(everything).toContain(part);+ }+ t.deps.manager.decideApproval(SID2, "tc-qq", "allow");+ await waitFor(() => t.deps.manager.statusOf(SID2) === "idle");+ });++ 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);+ 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 });+ expect((await api.post(`${BASE(SID2)}/state`, { enabled: true })).status).toBe(200);+ await waitFor(() => t.deps.messaging.statusOf(SID2, "qq").state === "connected");+ await fake.lastGateway().fire(c2cText("go", "msg_lines"));++ await waitFor(() => fake.allSends().length === 4);+ await new Promise((r) => setTimeout(r, TAIL_MS * 3));+ const sends = fake.allSends();+ // Four messages, not ten and not twenty: the first three lines, then the rest combined+ // with their own line breaks intact.+ expect(sends.map((s) => s.content)).toEqual([+ "line 1",+ "line 2",+ "line 3",+ lines.slice(3).join("\n"),+ ]);+ });++ // —— Nothing to reply to ——————————————————————————————————————————————————++ it("a send with no repliable message fails loudly instead of pretending", async () => {+ await bindEnabled(SID);+ // A chat the bridge knows about but the platform gives nothing to reply to: the state a+ // conversation is in whenever it was driven from the web app, or simply left for a while.+ t.deps.messagingRepo.recordChat(SID, "qq", qqChatIdOf("c2c", USER_OPENID), true);+ const res = await api.post(`${BASE(SID)}/test-message`, {});+ expect(res.status).toBe(502);+ const body = (await res.json()) as { error: { code: string; message: string } };+ expect(body.error.code).toBe("qq_send_failed");+ expect(body.error.message).toContain("only accepts replies");+ expect(fake.allSends()).toHaveLength(0);+ });++ it("before any inbound message the test-message endpoint refuses ahead of the send", async () => {+ await bindEnabled(SID);+ const res = await api.post(`${BASE(SID)}/test-message`, {});+ expect(res.status).toBe(409);+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe("qq_no_chat");+ });++ it("a test message rides the passive reply of a message just received", async () => {+ await bindEnabled(SID);+ await fake+ .lastGateway()+ .fire({ kind: "c2c", openid: USER_OPENID, messageId: "msg_test", content: "" });+ await waitFor(() => fake.allSends().length === 1);+ expect((await api.post(`${BASE(SID)}/test-message`, {})).status).toBe(200);+ await waitFor(() => fake.allSends().some((s) => s.content === MESSAGING_TEST_MESSAGE));+ expect(fake.allSends().at(-1)).toMatchObject({ msgId: "msg_test", msgSeq: 2 });+ });+});++/**+ * The seam's media half, as THIS branch sees it. `MessagingClient` grows `sendImage` /+ * `sendFile` in the media change, which is a sibling of this stack rather than something+ * below it, so the two methods are reached through their own structural type here instead+ * of through the seam. When the two land together, this local type is what disappears.+ */+interface MediaHalf {+ sendImage(chatId: string, file: { fileName: string; data: Buffer }): Promise<void>;+ sendFile(chatId: string, file: { fileName: string; data: Buffer }): Promise<void>;+}++describe("the QQ client's media half", () => {+ it("refuses an outbound file with a reason rather than silently succeeding", async () => {+ // Nothing about this needs a server: the seam's media methods are refusals, and the+ // reason has to reach whoever reads the error record the bridge writes.+ const connector = new QQConnector(new FakeQQTransport());+ const client = await connector.createClient({ appId: APP_ID, appSecret: APP_SECRET });+ const media = client as unknown as MediaHalf;+ const file = { fileName: "chart.png", data: Buffer.from("x") };+ await expect(media.sendImage(qqChatIdOf("c2c", USER_OPENID), file)).rejects.toThrow(+ /chart\.png/,+ );+ await expect(media.sendFile(qqChatIdOf("c2c", USER_OPENID), file)).rejects.toThrow(+ /publicly reachable URL/,+ );+ });++ it("refuses a text send before the bot has ever been messaged in that chat", async () => {+ const connector = new QQConnector(new FakeQQTransport());+ const client = await connector.createClient({ appId: APP_ID, appSecret: APP_SECRET });+ await expect(client.sendText(qqChatIdOf("c2c", USER_OPENID), "unprompted")).rejects.toThrow(+ /only accepts replies/,+ );+ });+});++/**+ * The ledger's LIFETIME, driven through the connector's two halves directly.+ *+ * The route tests above always see the same shape: one run, inside the window, on a live+ * connection. What is left is when the passive-reply accounting is reset, kept and+ * forgotten — a redelivered anchor, a connection that goes away with text still withheld, a+ * send that fails carrying the withheld text, and a chat nobody has spoken in for longer+ * than the platform will accept a reply. Each of those is a message that silently never+ * arrives, or one that arrives where it no longer should.+ */+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;++ /** A connector on a fake transport with its gateway open and its client built. */+ async function connected(opts: QQConnectorOpts = {}) {+ const fake = new FakeQQTransport();+ const connector = new QQConnector(fake, { tailFlushMs: TAIL_MS, ...opts });+ const client = await connector.createClient(CONFIG);+ const connection = await connector.connect(CONFIG, { onMessage: () => {} });+ return { fake, connector, client, connection, gateway: fake.lastGateway() };+ }++ /** Spends every immediate slot of a single chat's budget, leaving only the reserved one. */+ async function spendImmediate(client: { sendText(chatId: string, text: string): Promise<void> }) {+ for (const text of ["a", "b", "c"]) await client.sendText(CHAT, text);+ }++ it("a redelivered msg_id is not fresh budget", async () => {+ const { fake, client, gateway } = await connected();+ await gateway.fire(c2cText("go", "msg_1"));+ await client.sendText(CHAT, "first");+ await client.sendText(CHAT, "second");+ // The platform repeats a msg_id to guarantee delivery, and the bridge's redelivery+ // guard runs downstream of the connector — so a repeat lands here mid-run, between two+ // replies to the same message.+ await gateway.fire(c2cText("go", "msg_1"));+ await client.sendText(CHAT, "third");+ // A (msg_id, msg_seq) pair the platform has already accepted is REFUSED (40054005),+ // not deduplicated: a sequence that restarts here is the rest of the answer never+ // arriving, and the chat going quiet halfway through it.+ expect(fake.allSends().map((s) => s.msgSeq)).toEqual([1, 2, 3]);+ expect(new Set(fake.allSends().map((s) => s.msgId))).toEqual(new Set(["msg_1"]));+ });++ it("closing the connection drops a withheld tail instead of delivering it after the unbind", async () => {+ const { fake, client, connector, connection, gateway } = await connected();+ await gateway.fire(c2cText("go", "msg_close"));+ await spendImmediate(client);+ await client.sendText(CHAT, "withheld"); // no immediate slot left: waits for the reserved one+ connection.close();+ await settle(TAIL_MS * 3);+ // 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"]);++ // ...and the next connection starts the chat over rather than inheriting that tail.+ 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);+ 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();+ });++ it("a flush that fails keeps its text for the next inbound message's budget", async () => {+ const { fake, client, gateway } = await connected();+ await gateway.fire(c2cText("go", "msg_fail"));+ await spendImmediate(client);+ 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);+ 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);+ expect(fake.allSends().at(-1)).toMatchObject({+ content: "the end",+ msgId: "msg_next",+ msgSeq: 1,+ });+ });++ it("forgets a chat left quiet past the reply window", async () => {+ let clock = Date.now();+ const { fake, client, connector, 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.+ clock += QQ_PASSIVE_WINDOW_MS + 1;+ await gateway.fire({+ kind: "group",+ openid: GROUP_OPENID,+ messageId: "msg_new",+ 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");+ expect(fake.allSends().at(-1)).toMatchObject({ msgId: "msg_new", msgSeq: 1 });+ await expect(client.sendText(CHAT, "too late")).rejects.toThrow(/only accepts replies/);+ });+});diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 6e76768a..941455bc 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -96,6 +96,10 @@ import type {SkillArchiveInstallRequest,SkillInstallRequest,SkillLibraryResponse,+ QQBindingPutRequest,+ QQBindingResponse,+ QQTestRequest,+ QQTestResponse,RecalledMessageResponse,RetryNowResponse,SteerRequest,@@ -527,13 +531,20 @@ export const putTelegramBinding = (sessionId: string, body: TelegramBindingPutRe{ method: "PUT", body },);+/** Saves the QQ App ID / App Secret pair only — the same save/enable split as the Feishu PUT. */+export const putQQBinding = (sessionId: string, body: QQBindingPutRequest) =>+ apiFetch<QQBindingResponse>(`/api/sessions/${encodeURIComponent(sessionId)}/messaging/qq`, {+ method: "PUT",+ body,+ });+/** The connection toggle, which is also the bind/unbind: enable connects with the STORED credentials (409 `another_channel_enabled` while the other channel is enabled, 409 `account_enabled_elsewhere` while another conversation has this bot enabled), disable releases the account. */export const setMessagingBindingState = (sessionId: string,channel: MessagingChannel,enabled: boolean,) =>- apiFetch<FeishuBindingResponse | TelegramBindingResponse>(+ apiFetch<FeishuBindingResponse | TelegramBindingResponse | QQBindingResponse>(`/api/sessions/${encodeURIComponent(sessionId)}/messaging/${channel}/state`,{ method: "POST", body: { enabled } },);@@ -552,7 +563,14 @@ export const testTelegramBinding = (sessionId: string, body: TelegramTestRequest{ method: "POST", body },);-/** Short fixed text to the binding's last known chat (409 `feishu_no_chat` / `telegram_no_chat` before one exists). */+/** QQ credential probe (the access-token exchange); the platform names no account, so success carries no label. */+export const testQQBinding = (sessionId: string, body: QQTestRequest) =>+ apiFetch<QQTestResponse>(`/api/sessions/${encodeURIComponent(sessionId)}/messaging/qq/test`, {+ method: "POST",+ body,+ });++/** Short fixed text to the binding's last known chat (409 `feishu_no_chat` / `telegram_no_chat` / `qq_no_chat` before one exists; on QQ the send can still fail with 502 when no recent QQ message can be replied to). */export const sendMessagingTestMessage = (sessionId: string, channel: MessagingChannel) =>apiFetch<MessagingTestMessageResponse>(`/api/sessions/${encodeURIComponent(sessionId)}/messaging/${channel}/test-message`,diff --git a/packages/web/src/features/messaging/messaging-binding-editor.tsx b/packages/web/src/features/messaging/messaging-binding-editor.tsxindex a1df987a..5d455741 100644--- a/packages/web/src/features/messaging/messaging-binding-editor.tsx+++ b/packages/web/src/features/messaging/messaging-binding-editor.tsx@@ -4,15 +4,17 @@* place the Save action and the FAQ folds, so the state machine is a hook and the pieces* are body components; neither host forks the form).*- * Channel model: a Session keeps at most one saved config PER channel — both may sit- * saved side by side — and AT MOST ONE of them is enabled. The channel selector switches- * freely between the two channel forms (each independently savable, each showing its own- * configured/enabled state); enabling one channel while the other is enabled is gated+ * Channel model: a Session keeps at most one saved config PER channel — all of them may+ * sit saved side by side — and AT MOST ONE of them is enabled. The channel selector+ * switches freely between the channel forms (each independently savable, each showing its+ * own configured/enabled state); enabling one channel while another is enabled is gated* with a "turn that one off first" hint (the server refuses it too, 409).*- * The form opens on the connection controls and the credential fields trail them: the two+ * The form opens on the connection controls and the credential fields trail them: the* channels' field lists differ in length, so controls placed under the fields would sit at- * a different height in each channel and move on every switch. The explanation lives in+ * a different height in each channel and move on every switch. That is also why QQ's+ * replies-only rule — the one piece of channel copy too load-bearing to leave in a+ * collapsed fold — sits below its fields rather than above them. The explanation lives in* collapsed FAQ folds below the save area (`MessagingBindingHelp`), and the channel's* leading credential field — where the value starts being pasted — carries at its label's* top-right corner a link to wherever that channel issues the credential (the models-page@@ -92,6 +94,17 @@ const CHANNEL_LINKS: Record<MessagingChannel, { tutorial: string; credentialSour// from @BotFather inside the app, and this link is the one that leads there.credentialSource: "https://t.me/BotFather",},+ qq: {+ // The wiki ROOT is the onboarding guide itself — "介绍与接入指南": registering a+ // developer account, creating the bot, and the page its AppID and AppSecret are shown+ // on. That is what a reader of the setup fold is after; the API reference one level+ // down at /develop/api-v2/ answers a question they are not asking yet.+ tutorial: "https://bot.q.qq.com/wiki/",+ // The trailing slash is load-bearing and must not be tidied away: /qqbot/dashboard+ // answers 404, while /qqbot/ alone serves a 700-byte shell that only lands anywhere+ // because the retired hash-route app still redirects out of it.+ credentialSource: "https://q.qq.com/qqbot/dashboard/",+ },};const STATUS_TONE: Record<MessagingRuntimeStatus["state"], Tone> = {@@ -145,7 +158,7 @@ function factsOf(}function factsFromList(res: MessagingBindingsResponse): ChannelFactsMap {- const map: ChannelFactsMap = { feishu: EMPTY_FACTS, telegram: EMPTY_FACTS };+ const map: ChannelFactsMap = { feishu: EMPTY_FACTS, telegram: EMPTY_FACTS, qq: EMPTY_FACTS };for (const entry of res.bindings) {map[entry.binding.channel] = factsOf(entry.binding, entry.status);}@@ -235,6 +248,7 @@ export function useMessagingBinding(const [channels, setChannels] = useState<ChannelFactsMap>({feishu: EMPTY_FACTS,telegram: EMPTY_FACTS,+ qq: EMPTY_FACTS,});const [fieldErrors, setFieldErrors] = useState<MessagingFormErrors>({});const [busy, setBusy] = useState(false);@@ -307,7 +321,9 @@ export function useMessagingBinding(? "feishu": channels.telegram.enabled? "telegram"- : null;+ : channels.qq.enabled+ ? "qq"+ : null;const otherEnabled = enabledChannel !== null && enabledChannel !== selected;const dirty = form !== null && baseline !== null && formDirty(form, baseline);@@ -320,7 +336,12 @@ export function useMessagingBinding(setChannels((prev) => ({ ...prev, [channel]: factsOf(binding, status) }));if (binding !== null) {const fresh = bindingsToForm([binding]);- const sub = channel === "feishu" ? { feishu: fresh.feishu } : { telegram: fresh.telegram };+ const sub =+ channel === "feishu"+ ? { feishu: fresh.feishu }+ : channel === "qq"+ ? { qq: fresh.qq }+ : { telegram: fresh.telegram };setForm((prev) => (prev ? { ...prev, ...sub } : prev));setBaseline((prev) => (prev ? { ...prev, ...sub } : prev));}@@ -338,6 +359,10 @@ export function useMessagingBinding(else if (notice.tone === "info") toastInfo(notice.text);else toastSuccess(notice.text);}+ } else if (draft.channel === "qq") {+ const res = await api.testQQBinding(sessionId, draft.body);+ if (res.ok) toastSuccess(S.messaging.testOk(res.latencyMs ?? 0));+ else toastError(S.messaging.testFail(res.error ?? S.common.unknownError));} else {const res = await api.testFeishuBinding(sessionId, draft.body);if (res.ok) toastSuccess(S.messaging.testOk(res.latencyMs ?? 0));@@ -375,7 +400,9 @@ export function useMessagingBinding(const res =built.channel === "telegram"? await api.putTelegramBinding(sessionId, built.body)- : await api.putFeishuBinding(sessionId, built.body);+ : built.channel === "qq"+ ? await api.putQQBinding(sessionId, built.body)+ : await api.putFeishuBinding(sessionId, built.body);applyChannel(built.channel, res.binding, res.status);toastSuccess(S.common.saved);} catch (e) {@@ -543,10 +570,11 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })switches forms rather than locking (the mcp transport idiom). */}<div role="group" aria-label={S.messaging.channelLabel}><Segmented- cols={2}+ cols={3}options={[{ value: "feishu" as MessagingChannel, label: S.messaging.channelName.feishu },{ value: "telegram" as MessagingChannel, label: S.messaging.channelName.telegram },+ { value: "qq" as MessagingChannel, label: S.messaging.channelName.qq },]}value={channel}onChange={(v) => b.selectChannel(v)}@@ -612,7 +640,9 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })title:channel === "telegram"? S.telegram.testMessageNoChat- : S.feishu.testMessageNoChat,+ : channel === "qq"+ ? S.qq.testMessageNoChat+ : S.feishu.testMessageNoChat,}: {})}onClick={() => void b.sendTestMessage()}@@ -666,6 +696,53 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })/>)}</>+ ) : channel === "qq" ? (+ <>+ <CornerLinkedField+ label={S.qq.appId}+ required+ link={<ExternalLink href={links.credentialSource} label={S.messaging.console} />}+ >+ <Input+ size="sm"+ aria-label={S.qq.appId}+ error={errorText(b.fieldErrors.appId)}+ value={form.qq.appId}+ onChange={(e) => b.patchForm({ qq: { ...form.qq, appId: e.target.value } })}+ className="font-mono"+ placeholder="102000000"+ autoComplete="off"+ />+ </CornerLinkedField>+ <PasswordInput+ size="sm"+ label={S.qq.appSecret}+ {...(facts.secretConfigured+ ? { placeholder: S.qq.appSecretKeepHint }+ : { required: true })}+ error={errorText(b.fieldErrors.appSecret)}+ value={form.qq.appSecret}+ onChange={(e) =>+ b.patchForm({ qq: { ...form.qq, appSecret: e.target.value, clearSecret: false } })+ }+ autoComplete="off"+ />+ {facts.secretMasked !== null && form.qq.appSecret === "" && (+ <StoredSecretRow+ masked={facts.secretMasked}+ clearLabel={S.qq.clearSecret}+ checked={form.qq.clearSecret}+ enabled={facts.enabled}+ onChange={(checked) => b.patchForm({ qq: { ...form.qq, clearSecret: checked } })}+ />+ )}+ {/* The one channel whose rule cannot wait for a collapsed fold: QQ delivers only+ replies to messages sent from QQ, so a user who binds it and then types in the+ web app sees nothing arrive and concludes the binding is broken. It sits under+ this channel's fields rather than above them, which keeps the controls at the+ same height across channels. */}+ <p className="text-xs text-gray-500 dark:text-gray-400">{S.qq.repliesOnly}</p>+ </>) : (<><CornerLinkedField@@ -739,13 +816,19 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })<Switcharia-label={S.messaging.linePerMessage}checked={- channel === "telegram" ? form.telegram.linePerMessage : form.feishu.linePerMessage+ channel === "telegram"+ ? form.telegram.linePerMessage+ : channel === "qq"+ ? form.qq.linePerMessage+ : form.feishu.linePerMessage}onChange={(v) =>b.patchForm(channel === "telegram"? { telegram: { ...form.telegram, linePerMessage: v } }- : { feishu: { ...form.feishu, linePerMessage: v } },+ : channel === "qq"+ ? { qq: { ...form.qq, linePerMessage: v } }+ : { feishu: { ...form.feishu, linePerMessage: v } },)}/>@@ -761,7 +844,7 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })* form itself opening on the channel selector and the connection controls.*/export function MessagingBindingHelp({ channel }: { channel: MessagingChannel }) {- const per = channel === "telegram" ? S.telegram : S.feishu;+ const per = channel === "telegram" ? S.telegram : channel === "qq" ? S.qq : S.feishu;const links = CHANNEL_LINKS[channel];return (<div className="space-y-2 border-t border-gray-200 pt-3 dark:border-gray-800">@@ -779,6 +862,9 @@ export function MessagingBindingHelp({ channel }: { channel: MessagingChannel })<p>{per.intro}</p>{/* The channel's own flavor first, then the channel-neutral rule that owns thequestion a reader actually arrives with: how the bot moves conversations. */}+ {/* QQ's reply budget belongs to "what binding does" rather than troubleshooting:+ it is not a fault, it is how the channel delivers a long answer. */}+ {channel === "qq" && <p className="mt-1.5">{S.qq.replyBudget}</p>}<p className="mt-1.5">{S.messaging.faqWhatBinding}</p></HelpFold><HelpFold title={S.messaging.faqTroubleTitle}>@@ -787,6 +873,7 @@ export function MessagingBindingHelp({ channel }: { channel: MessagingChannel })<li>{S.messaging.troubleConnError}</li>{channel === "telegram" && <li>{S.messaging.troubleOnePoller}</li>}{channel === "telegram" && <li>{S.messaging.troubleGroupPrivacy}</li>}+ {channel === "qq" && <li>{S.messaging.troubleQQPassive}</li>}</ul></HelpFold></div>diff --git a/packages/web/src/features/messaging/messaging-binding-form.ts b/packages/web/src/features/messaging/messaging-binding-form.tsindex b89bc063..5cf46c8c 100644--- a/packages/web/src/features/messaging/messaging-binding-form.ts+++ b/packages/web/src/features/messaging/messaging-binding-form.ts@@ -5,6 +5,9 @@* selector back and forth never loses what was typed; `channel` names the selected one,* and only its fields are validated or submitted.*+ * QQ's sub-state mirrors Feishu's minus the domain field: the platform has one host, so+ * there is nothing for a domain to switch between.+ ** Not every field is a credential: `linePerMessage` is a per-binding delivery preference* (send a reply one message per non-blank line) that rides the same Save as the rest, which* is why it lives in the form state rather than behind a toggle of its own.@@ -19,6 +22,8 @@ import type {FeishuTestRequest,MessagingBindingInfo,MessagingChannel,+ QQBindingPutRequest,+ QQTestRequest,TelegramBindingPutRequest,TelegramTestRequest,} from "@prismshadow/penguin-server/api";@@ -40,6 +45,16 @@ export interface FeishuFormFields {linePerMessage: boolean;}+export interface QQFormFields {+ appId: string;+ /** Always starts empty; a non-empty value replaces the stored secret on save. */+ appSecret: string;+ /** The stored-secret clear checkbox (models idiom): applied on save, a typed secret wins over it. */+ clearSecret: boolean;+ /** Deliver a reply as one message per non-blank line (saved, not a connection setting). */+ linePerMessage: boolean;+}+export interface TelegramFormFields {/** Always starts empty; a non-empty value replaces the stored token on save. */botToken: string;@@ -49,11 +64,12 @@ export interface TelegramFormFields {linePerMessage: boolean;}-/** Editable state backing the binding editor: the selected channel plus both channels' fields. */+/** Editable state backing the binding editor: the selected channel plus every channel's fields. */export interface MessagingFormState {channel: MessagingChannel;feishu: FeishuFormFields;telegram: TelegramFormFields;+ qq: QQFormFields;}export type MessagingFormField = "appId" | "appSecret" | "baseDomain" | "botToken";@@ -66,11 +82,13 @@ export type MessagingFormErrors = Partial<Record<MessagingFormField, MessagingFoexport type MessagingFormResult =| { ok: true; channel: "feishu"; body: FeishuBindingPutRequest }| { ok: true; channel: "telegram"; body: TelegramBindingPutRequest }+ | { ok: true; channel: "qq"; body: QQBindingPutRequest }| { ok: false; errors: MessagingFormErrors };export type MessagingTestRequestByChannel =| { channel: "feishu"; body: FeishuTestRequest }- | { channel: "telegram"; body: TelegramTestRequest };+ | { channel: "telegram"; body: TelegramTestRequest }+ | { channel: "qq"; body: QQTestRequest };export function emptyMessagingForm(channel: MessagingChannel = "feishu"): MessagingFormState {return {@@ -83,6 +101,7 @@ export function emptyMessagingForm(channel: MessagingChannel = "feishu"): MessaglinePerMessage: false,},telegram: { botToken: "", clearToken: false, linePerMessage: false },+ qq: { appId: "", appSecret: "", clearSecret: false, linePerMessage: false },};}@@ -104,6 +123,13 @@ export function bindingsToForm(bindings: MessagingBindingInfo[]): MessagingFormSclearSecret: false,linePerMessage: info.linePerMessage,};+ } else if (info.channel === "qq") {+ form.qq = {+ appId: info.appId,+ appSecret: "",+ clearSecret: false,+ linePerMessage: info.linePerMessage,+ };} else {// Telegram's only credential field is the secret itself, so its sub-state loads empty// apart from the delivery preference, which is not a credential.@@ -153,6 +179,25 @@ export function formToPut(form: MessagingFormState, hasStoredSecret: boolean): M},};}+ if (form.channel === "qq") {+ const appId = form.qq.appId.trim();+ if (appId === "") errors.appId = "required";+ const appSecret = form.qq.appSecret.trim();+ const clearing = appSecret === "" && form.qq.clearSecret && hasStoredSecret;+ if (appSecret === "" && !hasStoredSecret) errors.appSecret = "required";+ if (Object.keys(errors).length > 0) return { ok: false, errors };+ return {+ ok: true,+ channel: "qq",+ body: {+ appId,+ ...(appSecret !== "" ? { appSecret } : {}),+ ...(clearing ? { clearAppSecret: true } : {}),+ // Always sent, for the same reason as the other channels': an omitted flag means "keep".+ linePerMessage: form.qq.linePerMessage,+ },+ };+ }const appId = form.feishu.appId.trim();if (appId === "") errors.appId = "required";const appSecret = form.feishu.appSecret.trim();@@ -185,6 +230,17 @@ export function formToTest(form: MessagingFormState): MessagingTestRequestByChanconst botToken = form.telegram.botToken.trim();return { channel: "telegram", body: { ...(botToken !== "" ? { botToken } : {}) } };}+ if (form.channel === "qq") {+ const appId = form.qq.appId.trim();+ const appSecret = form.qq.appSecret.trim();+ return {+ channel: "qq",+ body: {+ ...(appId !== "" ? { appId } : {}),+ ...(appSecret !== "" ? { appSecret } : {}),+ },+ };+ }const appId = form.feishu.appId.trim();const appSecret = form.feishu.appSecret.trim();const baseDomain = form.feishu.baseDomain.trim();@@ -210,6 +266,14 @@ export function formDirty(form: MessagingFormState, baseline: MessagingFormStateform.telegram.linePerMessage !== baseline.telegram.linePerMessage);}+ if (form.channel === "qq") {+ return (+ form.qq.appId !== baseline.qq.appId ||+ form.qq.appSecret.trim() !== "" ||+ form.qq.clearSecret ||+ form.qq.linePerMessage !== baseline.qq.linePerMessage+ );+ }return (form.feishu.appId !== baseline.feishu.appId ||form.feishu.baseDomain !== baseline.feishu.baseDomain ||@@ -228,6 +292,9 @@ export function formTestable(form: MessagingFormState, secretConfigured: booleanif (form.channel === "telegram") {return form.telegram.botToken.trim() !== "" || secretConfigured;}+ if (form.channel === "qq") {+ return (form.qq.appId.trim() !== "" && form.qq.appSecret.trim() !== "") || secretConfigured;+ }return ((form.feishu.appId.trim() !== "" && form.feishu.appSecret.trim() !== "") || secretConfigured);diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex e8b47c2d..bf5b8020 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1815,9 +1815,42 @@ Scenarios:],},+ /** QQ-channel strings of the messaging binding editor (channel-neutral ones live under `messaging`). */+ qq: {+ /** The what-binding-does FAQ fold's body (this channel's flavor). */+ intro:+ "Once bound, messages sent to the bot in QQ flow into this conversation, and the AI's replies are sent back to QQ. Create a bot on the QQ open platform and set its event subscription to WebSocket — no public URL is needed.",+ appId: "App ID",+ appSecret: "App Secret",+ /** Shown while a saved secret exists: submitting an empty field keeps it. */+ appSecretKeepHint: "Leave empty to keep the saved App Secret",+ /** The stored-secret row's clear checkbox (the models-page clear idiom). */+ clearSecret: "Clear stored App Secret",+ /** Why "send test message" is disabled before the bot has ever been messaged. */+ testMessageNoChat: "Message the bot once in QQ first, so it knows which chat to send to",+ /**+ * The rule that shapes this whole channel, stated where it is first needed rather than+ * left for the user to infer from a reply that never arrives.+ */+ repliesOnly:+ "QQ only lets a bot reply to a message you just sent it — it cannot start one. So a turn you begin in the web app is not mirrored to QQ, and once a few minutes have passed since your last QQ message, replies can no longer be delivered either. Send the bot another message in QQ to continue.",+ /** The passive-reply budget, in the terms a user experiences it. */+ replyBudget:+ "One QQ message can receive at most 4 replies (5 in a group). When a run produces more than that, the last one carries the rest combined — nothing is lost, it just arrives as a single message.",+ /** The setup FAQ fold's steps. */+ setupSteps: [+ "Register as a developer on the QQ open platform and create a bot",+ "Copy the App ID and App Secret from the development settings page into the form above",+ "Set the event subscription mode to WebSocket — leave the callback URL empty",+ "Add your own QQ account or a test group to the sandbox allowlist",+ "Find the bot in QQ and send it one message",+ ],+ },+/*** Session ↔ messaging-bot binding: the dock panel, the row action + dialog, and the- * channel-neutral editor strings (per-channel fields live under `feishu` / `telegram`).+ * channel-neutral editor strings (per-channel fields live under `feishu` / `telegram` /+ * `qq`).*/messaging: {panelTitle: "Messaging",@@ -1829,6 +1862,7 @@ Scenarios:channelName: {feishu: "Feishu",telegram: "Telegram",+ qq: "QQ",},/*** Shared link labels: the tutorial (in the setup FAQ fold) and, at the credential field's@@ -1880,6 +1914,7 @@ Scenarios:enabledIndicator: {feishu: "Feishu connection enabled",telegram: "Telegram connection enabled",+ qq: "QQ connection enabled",},/** The collapsed FAQ folds below the save area. */faqSetupTitle: "Set up the bot",@@ -1888,7 +1923,7 @@ Scenarios:faqWhatBinding:"The same bot can stay saved in several conversations, but only one of them may have its connection enabled at a time. To move it, turn the connection off where it is on and enable it here — no credential has to be deleted.",faqTroubleTitle: "Troubleshooting",- /** Troubleshooting entries (bot must be messaged once; connection errors point at credentials; one poller per Telegram token; Telegram Group Privacy withholds group messages from a non-admin bot). */+ /** Troubleshooting entries (bot must be messaged once; connection errors point at credentials; one poller per Telegram token; Telegram Group Privacy withholds group messages from a non-admin bot; QQ answers only a message just sent). */troubleNoChat:"“Send test message” disabled? The bot must have received one message first, so it knows which chat to send to.",troubleConnError:@@ -1897,6 +1932,9 @@ Scenarios:"Telegram reports that another program is polling? A Bot Token serves exactly one program at a time — close the other PenguinHarness server or bot script using it, or give this conversation a bot of its own.",troubleGroupPrivacy:"The bot ignores everything you say in a Telegram group? Telegram's Group Privacy is on by default, and under it a bot that is not an administrator of the group receives only commands addressed to it (such as /start@your_bot) and replies to its own messages — ordinary group messages are never delivered at all, and the connection itself looks perfectly healthy. Making the bot an administrator of that group fixes it on its own, since administrators always receive every message. Otherwise turn Group Privacy off with /setprivacy in @BotFather, then remove the bot from the group and add it back — a group it is already in does not pick up the change.",+ /** The QQ-only failure a user will otherwise read as "the bot is broken". */+ troubleQQPassive:+ "No replies arriving in QQ? QQ only lets a bot answer a message you just sent: a turn started in the web app is not mirrored there, and replies stop being deliverable a few minutes after your last QQ message. Send another message in QQ to continue.",},/** Subagents side panel: call-graph of the latest Task + the selected child conversation. */diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 3710c3a9..c3dfde6c 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1777,9 +1777,42 @@ Benchmark:],},+ /** QQ-channel strings of the messaging binding editor (channel-neutral ones live under `messaging`). */+ qq: {+ /** The what-binding-does FAQ fold's body (this channel's flavor). */+ intro:+ "绑定后,在 QQ 中发给机器人的消息会进入本对话,AI 的回复会发回 QQ。需要在 QQ 开放平台创建一个机器人,事件订阅方式选择 WebSocket,无需公网地址。",+ appId: "App ID",+ appSecret: "App Secret",+ /** Shown while a saved secret exists: submitting an empty field keeps it. */+ appSecretKeepHint: "留空保持已保存的 App Secret 不变",+ /** The stored-secret row's clear checkbox (the models-page clear idiom). */+ clearSecret: "清除已存 App Secret",+ /** Why "send test message" is disabled before the bot has ever been messaged. */+ testMessageNoChat: "先在 QQ 中给机器人发一条消息,机器人才知道要发到哪个会话",+ /**+ * The rule that shapes this whole channel, stated where it is first needed rather than+ * left for the user to infer from a reply that never arrives.+ */+ repliesOnly:+ "QQ 只允许机器人回复你刚发出的消息,不允许主动发消息。因此:在网页端发起的对话不会同步到 QQ;距离你上一条 QQ 消息过去几分钟后,回复也发不出去。想继续对话,在 QQ 里再发一条消息即可。",+ /** The passive-reply budget, in the terms a user experiences it. */+ replyBudget:+ "同一条 QQ 消息最多能收到 4 条回复(群聊 5 条)。一次运行产生的消息更多时,最后一条会把余下内容合并发出——内容不会丢失,只是合并成一条。",+ /** The setup FAQ fold's steps. */+ setupSteps: [+ "在 QQ 开放平台注册开发者,创建一个机器人",+ "在「开发设置」页取得 App ID 与 App Secret,填入上方表单",+ "在「开发配置」中把事件订阅方式设为 WebSocket,无需填写回调地址",+ "在沙箱配置中把自己的 QQ 号或测试群加入白名单",+ "在 QQ 中找到这个机器人,给它发一条消息",+ ],+ },+/*** Session ↔ messaging-bot binding: the dock panel, the row action + dialog, and the- * channel-neutral editor strings (per-channel fields live under `feishu` / `telegram`).+ * channel-neutral editor strings (per-channel fields live under `feishu` / `telegram` /+ * `qq`).*/messaging: {panelTitle: "消息软件",@@ -1791,6 +1824,7 @@ Benchmark:channelName: {feishu: "飞书",telegram: "Telegram",+ qq: "QQ",},/*** Shared link labels: the tutorial (in the setup FAQ fold) and, at the credential field's@@ -1840,6 +1874,7 @@ Benchmark:enabledIndicator: {feishu: "飞书连接已启用",telegram: "Telegram 连接已启用",+ qq: "QQ 连接已启用",},/** The collapsed FAQ folds below the save area. */faqSetupTitle: "如何创建机器人",@@ -1848,7 +1883,7 @@ Benchmark:faqWhatBinding:"同一个机器人可以同时保存在多个对话里,但同一时刻只能有一个对话启用它的连接。要换一个对话使用,先在原对话停用连接,再在这里启用——凭证不必删除。",faqTroubleTitle: "常见问题",- /** Troubleshooting entries (bot must be messaged once; connection errors point at credentials; one poller per Telegram token; Telegram Group Privacy withholds group messages from a non-admin bot). */+ /** Troubleshooting entries (bot must be messaged once; connection errors point at credentials; one poller per Telegram token; Telegram Group Privacy withholds group messages from a non-admin bot; QQ answers only a message just sent). */troubleNoChat: "「发送测试消息」不可用?机器人要先收到过一条消息,才知道要发到哪个会话。",troubleConnError:"连接状态显示错误?检查凭证是否正确;飞书还需确认 API 域名与事件订阅方式(长连接)。",@@ -1856,6 +1891,9 @@ Benchmark:"Telegram 提示已有其他程序在轮询?一个 Bot Token 同一时刻只能被一个程序使用——关闭正在占用它的另一个 PenguinHarness 服务端或机器人脚本,或为该会话单独建一个机器人。",troubleGroupPrivacy:"在 Telegram 群里发消息,机器人毫无反应?Telegram 的 Group Privacy 默认开启,此时不担任该群管理员的机器人只能收到明确指向它的命令(如 /start@your_bot)和对它自己消息的回复,普通群消息根本不会送达,连接本身也没有任何异常。把机器人设为该群的管理员即可单独解决,管理员始终收到全部消息。也可以到 @BotFather 用 /setprivacy 关闭 Group Privacy,然后把机器人移出该群再重新拉入——已在的群不会自动生效。",+ /** The QQ-only failure a user will otherwise read as "the bot is broken". */+ troubleQQPassive:+ "QQ 里收不到回复?QQ 只允许机器人回复你刚发出的消息:在网页端发起的对话不会同步过去,距离你上一条 QQ 消息过去几分钟后也发不出。在 QQ 里再发一条消息即可继续。",},/** Subagents side panel: call-graph of the latest Task + the selected child conversation. */diff --git a/packages/web/test/messaging-binding-editor.test.ts b/packages/web/test/messaging-binding-editor.test.tsindex cd64aa2b..7e3df5cc 100644--- a/packages/web/test/messaging-binding-editor.test.ts+++ b/packages/web/test/messaging-binding-editor.test.ts@@ -49,7 +49,7 @@ function stateOf(form: emptyMessagingForm(channel),patchForm: () => {},selectChannel: () => {},- channels: { feishu: DARK, telegram: DARK, ...facts },+ channels: { feishu: DARK, telegram: DARK, qq: DARK, ...facts },fieldErrors: {},dirty: false,busy: false,@@ -88,6 +88,11 @@ describe("MessagingBindingBody", () => {const telegram = render(stateOf("telegram"));expect(telegram).toContain('href="https://t.me/BotFather"');expect(telegram).not.toContain("core.telegram.org/bots/api");+ // QQ's trailing slash is load-bearing — https://q.qq.com/qqbot/dashboard answers 404 —+ // so it is pinned here rather than left to be tidied away by someone normalizing URLs.+ const qq = render(stateOf("qq"));+ expect(qq).toContain('href="https://q.qq.com/qqbot/dashboard/"');+ expect(qq).not.toContain('href="https://q.qq.com/qqbot/dashboard"');});it("labels that corner link with what it opens, never with a console Telegram has not got", () => {@@ -105,6 +110,7 @@ describe("MessagingBindingBody", () => {expect(telegram).not.toContain(dict.messaging.console);// ...and the channels that do have a console keep it.expect(render(stateOf("feishu"))).toContain(dict.messaging.console);+ expect(render(stateOf("qq"))).toContain(dict.messaging.console);}});@@ -169,7 +175,7 @@ describe("MessagingBindingBody", () => {});it('closes the form with the delivery option, its explanation behind the label\'s "?"', () => {- for (const channel of ["feishu", "telegram"] as MessagingChannel[]) {+ for (const channel of ["feishu", "telegram", "qq"] as MessagingChannel[]) {const html = render(stateOf(channel));// Both channels carry it: it is a delivery preference, not a credential.expect(html).toContain(S.messaging.linePerMessage);@@ -177,12 +183,43 @@ describe("MessagingBindingBody", () => {expect(html).toContain(S.common.moreInfoAbout(S.messaging.linePerMessage));expect(html).not.toContain(S.messaging.linePerMessageHelp);// After the credential fields, not among them.- const fieldAt = html.indexOf(channel === "telegram" ? S.telegram.botToken : S.feishu.appId);+ const fieldAt = html.indexOf(+ channel === "telegram"+ ? S.telegram.botToken+ : channel === "qq"+ ? S.qq.appId+ : S.feishu.appId,+ );expect(fieldAt).toBeGreaterThanOrEqual(0);expect(html.indexOf(S.messaging.linePerMessage)).toBeGreaterThan(fieldAt);}});+ it("states QQ's replies-only rule on screen, not in a collapsed fold", () => {+ // The one piece of channel copy that cannot wait to be unfolded. QQ delivers only+ // replies to messages sent from QQ, so a user who binds it and then works in the web app+ // sees nothing arrive and concludes the binding is broken. Every other channel's+ // explanation stays in the FAQ; this one is a line under the fields.+ const html = render(stateOf("qq"));+ expect(html).toContain(S.qq.repliesOnly);+ // Under the credential fields, so the controls above hold one height across channels.+ expect(html.indexOf(S.qq.repliesOnly)).toBeGreaterThan(html.indexOf(S.qq.appSecret));+ // ...and it belongs to QQ alone.+ expect(render(stateOf("feishu"))).not.toContain(S.qq.repliesOnly);+ });++ it("offers all three channels in the selector", () => {+ const html = render(stateOf("qq"));+ for (const name of [+ S.messaging.channelName.feishu,+ S.messaging.channelName.telegram,+ S.messaging.channelName.qq,+ ]) {+ expect(html).toContain(`>${name}</button>`);+ }+ expect(html).toContain("grid-cols-3");+ });+it("shows the switch's gating reason when the other channel holds the connection", () => {const hint = S.messaging.otherEnabledHint(S.messaging.channelName.feishu);const html = render(@@ -250,6 +287,18 @@ describe("MessagingBindingHelp", () => {// creating a bot to paste a token from, not writing one.expect(telegram).toContain('href="https://core.telegram.org/bots/features#botfather"');expect(telegram).toContain(S.telegram.setupSteps[0]);+ const qq = renderToStaticMarkup(+ createElement(MessagingBindingHelp, { channel: "qq" as MessagingChannel }),+ );+ // The onboarding guide, not the API reference: this fold is read by someone creating a+ // bot and looking for its credentials.+ expect(qq).toContain('href="https://bot.q.qq.com/wiki/"');+ expect(qq).toContain(S.qq.setupSteps[0]);+ // The reply budget is how this channel delivers a long answer, not a fault: it rides the+ // "what binding does" fold, while the passive-reply failure rides troubleshooting.+ expect(qq).toContain(S.qq.replyBudget);+ expect(qq).toContain(S.messaging.troubleQQPassive);+ expect(telegram).not.toContain(S.messaging.troubleQQPassive);});});diff --git a/packages/web/test/messaging-binding-form.test.ts b/packages/web/test/messaging-binding-form.test.tsindex ca079079..b8ed67de 100644--- a/packages/web/test/messaging-binding-form.test.ts+++ b/packages/web/test/messaging-binding-form.test.ts@@ -9,7 +9,11 @@* (an omitted flag would mean "keep", leaving no way to turn the option back off).*/import { describe, expect, it } from "vitest";-import type { FeishuBindingInfo, TelegramBindingInfo } from "@prismshadow/penguin-server/api";+import type {+ FeishuBindingInfo,+ QQBindingInfo,+ TelegramBindingInfo,+} from "@prismshadow/penguin-server/api";import {FEISHU_DEFAULT_DOMAIN,bindingsToForm,@@ -46,6 +50,18 @@ const STORED_TELEGRAM: TelegramBindingInfo = {updatedAt: "2026-08-26T00:00:00.000Z",};+const STORED_QQ: QQBindingInfo = {+ channel: "qq",+ sessionId: "session-1",+ appId: "102000001",+ appSecretMasked: "qq-a…1234",+ enabled: false,+ linePerMessage: false,+ lastChatKnown: true,+ createdAt: "2026-08-27T00:00:00.000Z",+ updatedAt: "2026-08-27T00:00:00.000Z",+};+describe("emptyMessagingForm / bindingsToForm", () => {it("starts empty forms on Feishu with the default domain, both channels blank", () => {expect(emptyMessagingForm()).toEqual({@@ -58,6 +74,7 @@ describe("emptyMessagingForm / bindingsToForm", () => {linePerMessage: false,},telegram: { botToken: "", clearToken: false, linePerMessage: false },+ qq: { appId: "", appSecret: "", clearSecret: false, linePerMessage: false },});});@@ -76,9 +93,17 @@ describe("emptyMessagingForm / bindingsToForm", () => {},// Each channel's delivery preference comes from its own stored config.telegram: { botToken: "", clearToken: false, linePerMessage: true },+ // An unsaved channel keeps its empty sub-state, so switching to it shows a blank form.+ qq: { appId: "", appSecret: "", clearSecret: false, linePerMessage: false },});+ // All three coexist: every saved channel loads its own non-secret fields.+ const all = bindingsToForm([STORED_FEISHU, STORED_TELEGRAM, STORED_QQ]);+ expect(all.feishu.appId).toBe("cli_abc");+ expect(all.qq.appId).toBe("102000001");+ expect(all.qq.appSecret).toBe("");// No enabled channel: the first saved one is selected; nothing saved: Feishu.expect(bindingsToForm([STORED_FEISHU]).channel).toBe("feishu");+ expect(bindingsToForm([STORED_QQ]).channel).toBe("qq");expect(bindingsToForm([]).channel).toBe("feishu");});});@@ -315,3 +340,74 @@ describe("formDirty / formTestable", () => {expect(formTestable(typed, false)).toBe(true);});});++describe("the QQ channel", () => {+ it("loads its non-secret field and leaves the secret empty, like the other channels", () => {+ const form = bindingsToForm([STORED_QQ]);+ // The selector lands on the only saved channel; the App ID loads, the secret never does.+ expect(form.channel).toBe("qq");+ expect(form.qq.appId).toBe("102000001");+ expect(form.qq.appSecret).toBe("");+ expect(form.qq.clearSecret).toBe(false);+ });++ it("submits the pair, omits a blank secret, and always sends the delivery flag", () => {+ const form = bindingsToForm([STORED_QQ]);+ const kept = formToPut(form, true);+ expect(kept).toEqual({+ ok: true,+ channel: "qq",+ // No `appSecret` key at all: an omitted secret is what tells the server to keep the+ // stored one, and the masked value must never round-trip.+ body: { appId: "102000001", linePerMessage: false },+ });++ form.qq.appSecret = " fresh-secret ";+ expect(formToPut(form, true)).toEqual({+ ok: true,+ channel: "qq",+ body: { appId: "102000001", appSecret: "fresh-secret", linePerMessage: false },+ });+ });++ it("requires both halves on a first bind and honours the clear checkbox after one", () => {+ const fresh = emptyMessagingForm("qq");+ expect(formToPut(fresh, false)).toEqual({+ ok: false,+ errors: { appId: "required", appSecret: "required" },+ });++ const stored = bindingsToForm([STORED_QQ]);+ stored.qq.clearSecret = true;+ expect(formToPut(stored, true)).toEqual({+ ok: true,+ channel: "qq",+ body: { appId: "102000001", clearAppSecret: true, linePerMessage: false },+ });+ // A typed secret wins over a stale clear checkbox (the models idiom).+ stored.qq.appSecret = "typed";+ expect(formToPut(stored, true)).toEqual({+ ok: true,+ channel: "qq",+ body: { appId: "102000001", appSecret: "typed", linePerMessage: false },+ });+ });++ it("routes its probe and its dirty/testable checks to its own fields", () => {+ const form = bindingsToForm([STORED_QQ]);+ expect(formToTest(form)).toEqual({ channel: "qq", body: { appId: "102000001" } });++ const baseline = bindingsToForm([STORED_QQ]);+ expect(formDirty(form, baseline)).toBe(false);+ form.qq.linePerMessage = true;+ expect(formDirty(form, baseline)).toBe(true);++ // A stored secret is testable as-is; a draft needs both halves.+ expect(formTestable(emptyMessagingForm("qq"), true)).toBe(true);+ const half = emptyMessagingForm("qq");+ half.qq.appId = "102000001";+ expect(formTestable(half, false)).toBe(false);+ half.qq.appSecret = "s";+ expect(formTestable(half, false)).toBe(true);+ });+});