Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

WeChat as a fourth messaging channel, bound by scanning a QR code (#533)

Yaowei Zheng5bee10c8f125
diff --git a/changelog/unreleased/2026-08-28-messaging-wechat.md b/changelog/unreleased/2026-08-28-messaging-wechat.md
new file mode 100644
index 00000000..a809b1aa
--- /dev/null
+++ b/changelog/unreleased/2026-08-28-messaging-wechat.md
@@ -0,0 +1,97 @@
+# WeChat joins as a fourth messaging channel, bound by scanning a QR code
+
+- **Date:** 2026-08-28
+- **Type:** feature
+- **Scope:** `server`, `web`, `docs`
+- **PR:** [#533](https://github.com/Prism-Shadow/penguin-harness/pull/533)
+
+[中文版](2026-08-28-messaging-wechat.zh.md)
+
+A Session gained a fourth channel to bind to: WeChat's official claw bot, behind the same
+connector seam the other three already sat behind. Binding it is a QR code scanned in WeChat
+and nothing else — there is no console to copy a credential out of, so the scan is not the
+convenient path here but the only one. Inbound messages arrive on a long poll, so binding one
+asks for no public callback URL, and the channel carries text, images and files in both
+directions, which none of the other three manage.
+
+## Details
+
+- The transport landed in `wechat-api.ts`: the request envelope and its headers, the
+ `getupdates` long poll with its opaque cursor, the single-item sends, and the CDN media
+ path in both directions — a pre-signed upload of AES-128-ECB ciphertext under a per-file
+ key, and the matching decrypt on the way in. It went in behind an injectable factory, so
+ the tests reach it through fakes rather than the network. The protocol is Tencent's, taken
+ from its own MIT-licensed OpenClaw plugin and the independent SDK derived from it; neither
+ is a dependency, because both own the process's message loop, carry one account, and render
+ their login QR to a terminal.
+- The channel policy landed in `wechat-connector.ts`. The poll loop backs off on failure and
+ reports once per outage, and its FIRST call is a drain on a short deadline: an empty cursor
+ means "from the beginning", so a binding switched on after a week dark confirms that week
+ rather than replaying it as a flood of Tasks — and asking only for what the platform is
+ already holding keeps the drain from swallowing the first message a user sends after
+ enabling. A window that closes with nothing to report is the ordinary quiet case on a long
+ poll and resolves empty rather than reading as an outage.
+- **Readiness is reported by the credential probe, never by a poll.** A poll is a request held
+ open until something arrives, so a connection reported ready only when one came back would
+ sit at "connecting" for the whole window on an idle bot — usable throughout, and saying so
+ nowhere. Each cycle opens with a probe that answers at once, and it runs again ahead of every
+ recovery, so a token revoked during an outage stops the loop with the right reason.
+- **The credential probe reads the authentication layer and nothing else.** Every authenticated
+ endpoint here shares one auth layer and then does something with a side condition a
+ freshly-scanned binding cannot satisfy — `getconfig` wants a live conversation to mint a
+ typing ticket for, `getuploadurl` a peer and a file, `getupdates` a long-poll window it would
+ park for. So a non-zero business code on an accepted request reports the credential as GOOD,
+ while an HTTP 401/403 and the platform's stale-token code (-14) report it as bad. Test
+ connection therefore passes on a bot nobody has messaged yet, and says only that the token
+ signs in — not that the bot can deliver.
+- **Scan-to-connect is the whole credential form.** `wechat-scan.ts` holds the in-flight
+ codes and the platform's poll handles — the thing that turns into a bot token — in memory
+ only, scoped to the Session that started them and bounded per Session. The browser is given
+ a handle this server mints instead, plus the URL to draw and a status. The flow reports more
+ states than QQ's because WeChat has more: scanned-but-unconfirmed, a pairing code shown on
+ the phone that is typed into the panel, a code spent on too many wrong digits, and a bot
+ already bound here, which ends the flow without being a failure. An IDC redirect switches
+ the polling host mid-flow without surfacing as a state of its own.
+- The `/wechat` route subtree arrived with the verb set the other channels carry, and two
+ differences that follow from having no typed credential: its PUT saves the delivery
+ preferences alone and refuses to create a binding (400 `wechat_token_required`), and its
+ credential test takes no body at all, probing the stored binding because there is no draft.
+ The scanned bot id is the account identity, so the one-Session-per-account rule applies to a
+ WeChat bot exactly as it does to a Feishu app.
+- **Direct chats only.** The channel has no group inbound: a message addressed to the bot in a
+ group never arrives, so the panel states that under the controls rather than leaving it in a
+ collapsed fold.
+- Media travels both ways. A reply's pictures and attachments are uploaded and arrive as real
+ images and files; inbound images, files and videos arrive as lazy handles that are fetched
+ only after the bridge has decided the message is worth acting on. A voice message is relayed
+ as WeChat's OWN transcription of it, so a spoken question is answered rather than refused; a
+ recording the platform could not transcribe reaches the chat as the shared not-supported
+ notice.
+- `wechat-markdown.ts` renders a reply for a client that reads Markdown itself, so it
+ subtracts rather than translates: headings, bold, strikethrough, lists, quotes, rules,
+ links, inline code, fenced code and tables are emitted as written — the widest subset of the
+ four — while what the client will not show keeps its words and loses its markers (headings
+ past the fourth level, emphasis around CJK text, and inline images, which become links).
+- The three delivery preferences apply here unchanged, and none of them costs anything
+ different on this channel: it has no reply budget and no expiring reply window, so its
+ binding type re-declares nothing.
+- The binding editor's channel selector gained a fourth option, and WeChat arrived with its
+ own scan panel, setup steps, media note and troubleshooting entry in both dictionaries.
+- The Session row's messaging action, its dialog and the dock panel's tab are now labelled
+ **Remote control** (`远程控制`). Only the labels changed; the route, the keys and every
+ identifier are the same.
+- That row-menu action now wears the paper plane the Session row already flies while it is
+ relaying, in place of the chat bubble. The entry and the mark it produces are one feature, and
+ a reader should not have to learn two shapes for it; the dock panel's tab keeps the bubble,
+ which marks the panel rather than the relay.
+- The backlog drain is spent only on a window the platform actually answered. A drain that
+ closes on its own deadline reports an empty list with the cursor it was given, so treating it
+ as drained left the cursor at the beginning and let the next ordinary poll relay a whole
+ backlog to the Agent as live traffic. It is retried instead, bounded, since an idle bot's poll
+ may park every time.
+- The poll loop's failure counter is cleared after a poll that returned, not beside the
+ credential probe. The probe and the poll are different endpoints, so a failure that only ever
+ hit the poll was zeroed by every recovery: the backoff never left its first step and one error
+ record was written per attempt.
+- A table cell's literal markers are escaped like any other text. Only `|` was escaped before,
+ so a lone `*` in one cell could pair with one in another and open emphasis through the table.
diff --git a/changelog/unreleased/2026-08-28-messaging-wechat.zh.md b/changelog/unreleased/2026-08-28-messaging-wechat.zh.md
new file mode 100644
index 00000000..0e197931
--- /dev/null
+++ b/changelog/unreleased/2026-08-28-messaging-wechat.zh.md
@@ -0,0 +1,71 @@
+# 微信成为第四个消息渠道,通过扫码完成绑定
+
+- **Date:** 2026-08-28
+- **Type:** feature
+- **Scope:** `server`, `web`, `docs`
+- **PR:** [#533](https://github.com/Prism-Shadow/penguin-harness/pull/533)
+
+[English](2026-08-28-messaging-wechat.md)
+
+Session 多了第四个可绑定的渠道:微信官方的 claw 机器人,接在前三个渠道早已使用的同一套连接器
+接口后面。绑定它只有一条路——用微信扫码授权,没有任何可以复制凭据的后台,因此扫码在这里不是
+更省事的那条路,而是唯一的一条。入站消息走长轮询,绑定它不需要任何公网回调地址;而且它能双向
+传输文字、图片与文件,这是另外三个渠道都做不到的。
+
+## 细节
+
+- 传输层落在 `wechat-api.ts`:请求信封与其请求头、带不透明游标的 `getupdates` 长轮询、单条
+ 消息项的发送,以及双向的 CDN 媒体链路——出站是把按文件随机生成密钥的 AES-128-ECB 密文上传到
+ 预签名地址,入站是与之对应的解密。它以可注入的工厂形式落地,因此测试是对着假实现跑的,不碰
+ 网络。协议来自腾讯自己以 MIT 协议开源的 OpenClaw 插件,以及由它衍生的独立 SDK;两者都没有被
+ 当作依赖引入,因为它们都要接管进程的消息循环、只承载单个账号,并把登录二维码画在终端里。
+- 渠道策略落在 `wechat-connector.ts`。轮询循环失败后按退避重试,且每次故障只上报一次;它的
+ **第一次**调用是一次用短超时发起的清空:空游标意味着「从头开始」,因此一个搁置了一周才启用
+ 的绑定只是确认掉这一周,而不是把它重放成一堆 Task——而「只要平台此刻已经攒着的东西」这一点,
+ 又让清空不会把用户启用之后发出的第一条消息一并吞掉。长轮询窗口无事可报而关闭是正常情况,
+ 按空结果返回,不当作故障。
+- **就绪由凭据探测上报,而不是由某次轮询。** 轮询是一个一直挂着、等东西到来的请求,因此「等
+ 某次轮询返回才算就绪」会让一个空闲的机器人在整个窗口期里停在「连接中」——这段时间它完全可用,
+ 却无处说明这一点。每一轮循环都以一次立即返回的探测开始;每次故障恢复前也会再跑一次,因此
+ 在故障期间被吊销的 Token 会以正确的原因终止循环。
+- **凭据探测只读认证层。** 这里每一个需要鉴权的接口都共用同一层认证,然后各自去做一件刚扫码
+ 完成的绑定还满足不了的事——`getconfig` 需要一个活跃会话才能签发输入中票据,`getuploadurl`
+ 需要对端和文件,`getupdates` 则是会一直挂着的长轮询。因此:请求被受理后返回的非零业务码
+ 说明凭据**是好的**,而 HTTP 401/403 与平台的 Token 失效码(-14)说明凭据有问题。于是「测试
+ 连接」在一个还没有人发过消息的机器人上也能通过,并且它只说明 Token 能通过认证——不说明这个
+ 机器人能把消息发出去。
+- **扫码连接就是这个渠道的全部凭据表单。** `wechat-scan.ts` 只在内存中持有进行中的二维码与
+ 平台的轮询句柄——也就是能换取 Bot Token 的那个——按发起的 Session 隔离,并按 Session 设上限。
+ 浏览器拿到的是服务端另行签发的句柄,外加要渲染的 URL 和一个状态。相比 QQ,这套流程要上报更多
+ 状态,因为微信本身就更多:已扫码但未确认、手机上显示、需要在面板里输入的配对码、因多次输错而
+ 作废的二维码,以及「该机器人已连接过本服务」——最后一种结束流程但不是失败。IDC 重定向会在流程
+ 中途切换轮询主机,而不作为一个独立状态暴露出去。
+- `/wechat` 路由子树带来了其他渠道同样的动词集合,以及两处因「没有可填写的凭据」而产生的差异:
+ 它的 PUT 只保存投递偏好、且拒绝凭空创建绑定(400 `wechat_token_required`),它的凭据探测则
+ 完全不接受请求体——没有草稿可探,只能探已存绑定。扫码得到的 bot id 就是账号身份,因此
+ 「一个账号同时只由一个 Session 持有连接」的规则对微信机器人与对飞书应用完全一致。
+- **只支持单聊。** 这个渠道不接收群消息:在群里发给机器人的消息根本不会到达,因此面板把这一点
+ 写在控件下方,而不是留在折叠的说明里。
+- 媒体是双向的。回复中的图片与附件会被上传,并以真正的图片和文件到达;入站的图片、文件与视频
+ 以惰性句柄的形式到达,只有在 bridge 判定这条消息值得处理之后才真正下载。语音消息按微信**自带**
+ 的语音转文字结果转发,因此一句说出来的问题会被回答而不是被拒绝;微信没能转写的语音则以共用的
+ 「不支持」提示回到聊天。
+- `wechat-markdown.ts` 面向的是一个本身就读 Markdown 的客户端,因此它做的是删减而不是翻译:
+ 标题、粗体、删除线、列表、引用、分割线、链接、行内代码、代码块与表格都按原样发出——四个渠道
+ 里最全的一份——而客户端不渲染的部分只去掉标记、保留文字(五级以下的标题、中文两侧的斜体,以及
+ 行内图片,后者改为链接)。
+- 三个投递偏好在这里原样适用,且没有一个在本渠道有不同的代价:它既没有回复额度,也没有会过期的
+ 回复窗口,因此它的绑定类型不重复声明任何字段。
+- 绑定编辑器的渠道选择器多了第四个选项,微信也在两份词典里带来了自己的扫码面板、配置步骤、媒体
+ 说明与排查条目。
+- Session 行的消息动作、它打开的对话框,以及停靠面板的页签,现在都标注为**远程控制**(英文
+ `Remote control`)。只改了文案,路由、键名与各类标识符都没有变。
+- 行菜单里的这一项改用 Session 行在中继时已经挂着的那枚纸飞机,替换原来的聊天气泡。入口与它产生的
+ 标记本是同一个功能,读者不该为它记两种形状;停靠面板的页签仍用气泡——它标的是面板,不是中继。
+- 积压清空只在平台确实作答的那一次窗口上「用掉」。因自身截止时间而关闭的清空返回空列表,且带回的是
+ 它被给出的那个游标;把它当作已清空,游标便停在起点,随后一次普通轮询会把整批积压当作实时消息转给
+ 智能体。改为重试,并设上限——空闲机器人的轮询可能每次都停到截止。
+- 轮询循环的失败计数在「有返回的那次轮询之后」清零,而不是挨着凭据探测清零。探测与轮询是两个不同的
+ 端点,因此只打在轮询上的故障会被每一次恢复清零:退避永远停在第一档,且每次尝试都写一条错误记录。
+- 表格单元格中的字面标记与其他文本一样转义。此前只转义 `|`,于是某个单元格里孤立的 `*` 会与另一个
+ 单元格里的 `*` 配对,把强调一路打开穿过整张表。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 22548925..eef12fdb 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -309,9 +309,9 @@ Workspace files may be Agent-generated, so `GET /files/content` treats them as u
The 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, QQ)
+### Messaging Bindings (Feishu, Telegram, QQ, WeChat)
-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.
+A Session can be connected to a messaging bot — Feishu, Telegram, QQ and WeChat 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`, QQ holds the platform's WebSocket gateway with the `GROUP_AND_C2C_EVENT` intent, and WeChat long-polls `ilink/bot/getupdates` — 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 |
| --- | --- | --- |
@@ -337,11 +337,22 @@ A Session can be connected to a messaging bot — Feishu, Telegram and QQ are th
| POST | /messaging/qq/scan/poll | `{taskId}` → `{status, appId?, binding?}`. `completed` means the server already decrypted the App Secret and **saved** the binding (enabling stays separate); `expired` means start a new task. 404 `qq_scan_task_unknown` for an unknown, foreign or already-resolved task |
| POST | /messaging/qq/scan/cancel | `{taskId}` — drop a scan the user walked away from, so its key is forgotten now rather than at the sweep |
| 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`, `finalReplyOnly` and `renderMarkdown` are the three saved fields that are not credentials. With `linePerMessage` 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). With `finalReplyOnly` set, a run relays only its LAST completed assistant message, delivered when the run ends, instead of mirroring each one as it completes — the working notes a run writes between tool calls stay in the web app, and the files that follow the reply are then read from that final message alone, since it is the only text the chat received. The two compose: with both set, the final reply is the one split per line. Both default to false, an omitted value on a PUT keeps the stored one, and neither applies to the notices or the test message — the approval reminder in particular is not a reply and arrives immediately whatever `finalReplyOnly` says. `renderMarkdown` renders a relayed reply's Markdown in the channel's own markup instead of sending its characters as written; it **defaults to true**, an omitted value on a PUT keeps the stored one, and it likewise never applies to the notices or the test message. Each channel shows what it can and degrades the rest deliberately rather than leaking the source: Telegram sends `parse_mode: "HTML"` and has no headings, lists or tables (a heading becomes a bold line, list markers become literal text, a table becomes a `<pre>` block); Feishu sends an interactive card carrying the JSON 2.0 rich-text component and renders everything, over-long tables becoming code blocks so no row is silently dropped; QQ sends `msg_type: 2` free-form markdown and has no code formatting and no tables (a fenced block becomes plain escaped lines, a table becomes its rows). Chunking follows the setting, cutting at block boundaries and re-fencing a code block that spans messages, so no message opens a construct it does not close. **A formatted send the channel refuses falls back to a plain-text send of the same message**, so the setting can cost formatting and never a reply. 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. Inbound processing accepts text, images and files: an image becomes an ordinary `image_url` input part, capped at the server's inline-image ceiling per image and by a rolling per-binding byte budget in aggregate — an inline image is written verbatim into the Trace, and this path, unlike the composer, has no authentication in front of it. A file becomes the composer's other attachment shape — written into the Session scratchpad and handed to the model as an `[attached file: <path>]` line, so its bytes never enter the conversation — under the same admin-settable per-file and per-message attachment caps an authenticated upload answers to, narrowed further by any tighter ceiling the channel itself has (Telegram serves a bot no file over 20MB). Feishu takes the `file` message type and Telegram the `document` field: a file the sender chose to send AS a file, which is also the only one of Telegram's media fields carrying the sender's own name. Video, audio and voice are deliberately not delivered — nothing downstream decodes or transcribes them, and what a sender wants the Agent to have arrives as a file the moment they attach it as one. The caption of a message whose attachment IS delivered (a photo, a document) is that message's text; a caption on any other media kind is not, since its bytes never arrive and running the model on the caption alone answers about a file it never received. An image over the ceiling, one past the budget and one the channel refuses answer with three different bilingual notices, as do a file over a cap, a batch over the per-message total and a file the channel refuses; none of them runs half a message, and a refusal the bot's own permissions caused names the scopes to grant and carries the channel's console link, which for Feishu is the usual case (receiving messages and downloading their attachments are separate scopes). Every other type still gets the bilingual "not supported" reply. Outbound, a finished run's reply is followed by the files it MENTIONED AND PRODUCED — path-like tokens that resolve inside the Workspace, exist, and were written at or after the run started, wherever in the reply they appear (the mention picks which output was the point; the mtime is what keeps a steerable reply from becoming a read primitive, since a reply that declines to paste a file still names it) — images as images and everything else as attachments, classified by the file the read actually reached rather than by the name the reply spelled, at most 5 per run and at most 10MB per image / 30MB per file (the tighter of each channel's own limits). Every way a mentioned file does not arrive is said in the chat — over a cap, past the count cap, no such file in the Workspace, or an upload the channel refused — except a file the run did not write, which is dropped silently because a reply naming the config it read is the ordinary case. Telegram connects by draining the backlog first: messages sent while no connection existed are skipped, matching Feishu, where missed events are simply gone. A binding's runtime status additionally reports what the live connection has SEEN — `lastInboundAt` (when a message last arrived; absent while none has since this connection opened), `lastDeliveryError` (`{at, stage, detail}`, where `stage` is `inbound` when the message arrived and its Task never started, or `send` when a reply never reached the chat, and which no later success clears) and `lastConnectionError` (`{at, detail}` for the last connection failure, kept after the connection recovers — unlike `lastError`, which belongs to the `error` state and is gone the moment the state leaves it). All three are in-process and reset on every (re)connect — a re-enable or a credential save opens a new one — so an absent `lastInboundAt` means "nothing since this connection opened", never "nothing ever". They exist because a channel that withholds messages produces `connected` with no error at all.
+| GET | /messaging/wechat | The WeChat config in the same envelope (`botId`, `botTokenMasked`) |
+| PUT | /messaging/wechat | Save the delivery preferences ONLY: `{clearBotToken?, linePerMessage?, finalReplyOnly?, renderMarkdown?}`. The one PUT here that carries no credential — a WeChat bot token exists only where a scan put it, and there is no console to copy one out of — so it presupposes a binding and answers 400 `wechat_token_required` before one exists. The clear flag works like the others' (409 `messaging_disable_before_clear` while enabled; the cleared config keeps its row and its bot identity, and only a fresh scan makes it connectable again) |
+| POST | /messaging/wechat/state | Same contract as the other toggles (400 `wechat_token_required` without a stored token) |
+| DELETE | /messaging/wechat | Remove this channel's config entirely (bot token included). API completeness only |
+| POST | /messaging/wechat/test | Credential probe (`ilink/bot/getconfig` on behalf of the account that scanned) → `{ok, latencyMs?, error?}`. The only test here that takes NO body: nothing on this channel is typed, so the stored binding is the only thing to probe (400 `wechat_token_required` without one). No account label — the probe names neither the bot nor the person |
+| POST | /messaging/wechat/scan | Start scan-to-connect, which on this channel is the ONLY way to bind → `{taskId, qrUrl, pollMs}`. Render `qrUrl` as a QR code; it is opened by WeChat, never fetched. The platform's own poll handle — the thing that collects the bot token — stays on the server, and `taskId` is a handle this server mints in its place. 409 `messaging_disable_before_scan` while the connection is enabled; 502 `wechat_scan_failed` when the platform refuses |
+| POST | /messaging/wechat/scan/poll | `{taskId}` → `{status, botId?, binding?}`. `status` is one of `pending`, `scanned`, `need_verify_code`, `blocked`, `expired`, `already_bound`, `completed`. `completed` means the server already **saved** the binding (enabling stays separate); `already_bound` is not a failure — the bot is bound already and nothing new was issued. It does not say WHERE: the scan offers the platform no token list, so it cannot distinguish a binding on this server from one anywhere else. 404 `wechat_scan_task_unknown` for an unknown, foreign or already-resolved task. Unlike QQ's poll, an OVERLAPPING request answers `pending` rather than 404: the upstream call is a long poll and spans several client intervals |
+| POST | /messaging/wechat/scan/verify | `{taskId, verifyCode}` → 204. The pairing code WeChat showed on the phone. It rides the NEXT poll rather than a request of its own, because the platform takes it as a parameter of its status call, so this only records it — a wrong code surfaces as the next poll reporting `need_verify_code` again |
+| POST | /messaging/wechat/scan/cancel | `{taskId}` — drop a scan the user walked away from, so its handle is forgotten now rather than at the sweep |
+| POST | /messaging/wechat/test-message | Send a short fixed text to the last known chat; 409 `wechat_no_chat` until the bot has been messaged once in WeChat |
+
+Masked secrets are omitted from responses when none is stored (a cleared config), and a config without a secret cannot be enabled. `linePerMessage`, `finalReplyOnly` and `renderMarkdown` are the three saved fields that are not credentials. With `linePerMessage` 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). With `finalReplyOnly` set, a run relays only its LAST completed assistant message, delivered when the run ends, instead of mirroring each one as it completes — the working notes a run writes between tool calls stay in the web app, and the files that follow the reply are then read from that final message alone, since it is the only text the chat received. The two compose: with both set, the final reply is the one split per line. Both default to false, an omitted value on a PUT keeps the stored one, and neither applies to the notices or the test message — the approval reminder in particular is not a reply and arrives immediately whatever `finalReplyOnly` says. `renderMarkdown` renders a relayed reply's Markdown in the channel's own markup instead of sending its characters as written; it **defaults to true**, an omitted value on a PUT keeps the stored one, and it likewise never applies to the notices or the test message. Each channel shows what it can and degrades the rest deliberately rather than leaking the source: Telegram sends `parse_mode: "HTML"` and has no headings, lists or tables (a heading becomes a bold line, list markers become literal text, a table becomes a `<pre>` block); Feishu sends an interactive card carrying the JSON 2.0 rich-text component and renders everything, over-long tables becoming code blocks so no row is silently dropped; QQ sends `msg_type: 2` free-form markdown and has no code formatting and no tables (a fenced block becomes plain escaped lines, a table becomes its rows); WeChat reads Markdown itself, so rendering SUBTRACTS rather than translates — what the client will not show keeps its words and loses its markers (headings past the fourth level, emphasis around CJK, and inline images, which become links). Chunking follows the setting, cutting at block boundaries and re-fencing a code block that spans messages, so no message opens a construct it does not close. **A formatted send the channel refuses falls back to a plain-text send of the same message**, so the setting can cost formatting and never a reply. 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), and WeChat's is the bot id the scan returns. 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. Inbound processing accepts text, images and files: an image becomes an ordinary `image_url` input part, capped at the server's inline-image ceiling per image and by a rolling per-binding byte budget in aggregate — an inline image is written verbatim into the Trace, and this path, unlike the composer, has no authentication in front of it. A file becomes the composer's other attachment shape — written into the Session scratchpad and handed to the model as an `[attached file: <path>]` line, so its bytes never enter the conversation — under the same admin-settable per-file and per-message attachment caps an authenticated upload answers to, narrowed further by any tighter ceiling the channel itself has (Telegram serves a bot no file over 20MB). Feishu takes the `file` message type and Telegram the `document` field: a file the sender chose to send AS a file, which is also the only one of Telegram's media fields carrying the sender's own name. Video, audio and voice are deliberately not delivered on those two channels — nothing downstream decodes or transcribes them, and what a sender wants the Agent to have arrives as a file the moment they attach it as one. WeChat is the exception, and only because the platform does the work itself: it ships its own transcription with a voice message, and a video arrives as an ordinary file. The caption of a message whose attachment IS delivered (a photo, a document) is that message's text; a caption on any other media kind is not, since its bytes never arrive and running the model on the caption alone answers about a file it never received. An image over the ceiling, one past the budget and one the channel refuses answer with three different bilingual notices, as do a file over a cap, a batch over the per-message total and a file the channel refuses; none of them runs half a message, and a refusal the bot's own permissions caused names the scopes to grant and carries the channel's console link, which for Feishu is the usual case (receiving messages and downloading their attachments are separate scopes). Every other type still gets the bilingual "not supported" reply. Outbound, a finished run's reply is followed by the files it MENTIONED AND PRODUCED — path-like tokens that resolve inside the Workspace, exist, and were written at or after the run started, wherever in the reply they appear (the mention picks which output was the point; the mtime is what keeps a steerable reply from becoming a read primitive, since a reply that declines to paste a file still names it) — images as images and everything else as attachments, classified by the file the read actually reached rather than by the name the reply spelled, at most 5 per run and at most 10MB per image / 30MB per file (the tighter of each channel's own limits). Every way a mentioned file does not arrive is said in the chat — over a cap, past the count cap, no such file in the Workspace, or an upload the channel refused — except a file the run did not write, which is dropped silently because a reply naming the config it read is the ordinary case. Telegram connects by draining the backlog first: messages sent while no connection existed are skipped, matching Feishu, where missed events are simply gone. A binding's runtime status additionally reports what the live connection has SEEN — `lastInboundAt` (when a message last arrived; absent while none has since this connection opened), `lastDeliveryError` (`{at, stage, detail}`, where `stage` is `inbound` when the message arrived and its Task never started, or `send` when a reply never reached the chat, and which no later success clears) and `lastConnectionError` (`{at, detail}` for the last connection failure, kept after the connection recovers — unlike `lastError`, which belongs to the `error` state and is gone the moment the state leaves it). All three are in-process and reset on every (re)connect — a re-enable or a credential save opens a new one — so an absent `lastInboundAt` means "nothing since this connection opened", never "nothing ever". They exist because a channel that withholds messages produces `connected` with no error at all.
**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 `renderMarkdown` send the platform refuses spends a second slot on its plain-text retry. `finalReplyOnly` cuts both ways here: it spends the least budget a run can spend — one reply — but the passive-reply window is only a few minutes wide, and holding the reply until the run ends spends that window on the run, so a run that outlives it delivers nothing at all where an every-message relay would have sent whatever completed inside it. 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.
+**WeChat carries direct chats only, and the most media of the four.** The claw bot channel has no group inbound at all: a message addressed to the bot in a group never reaches this API, so a binding that answers a direct chat perfectly is silent in a group by design rather than by misconfiguration. In exchange it is the only channel here that carries text, images and files in BOTH directions — a reply's pictures and attachments are uploaded to the platform's CDN (AES-128-ECB under a per-file key) and arrive as real images and files rather than being refused. Two inbound kinds are folded: a voice message is relayed as WeChat's own transcription of it, and a video arrives as a file; a recording the platform could not transcribe reaches the chat as the shared not-supported notice.
-**Scan-to-connect never shows the browser the key.** The AES key that decrypts the App Secret is generated, held, used and dropped on the server; the client is given only a task handle, a URL to draw, and a status. Tasks live in memory, are scoped to the Session that started them, are bounded per Session so one caller's scans cannot evict another's, and are claimed by the poll that resolves them — so both a replay and a second concurrent poll of one task read as 404 rather than as a second bind. Every scan route is owner-only, because the flow ends in a stored credential however little of it the caller types.
+**Scan-to-connect never shows the browser the secret.** Whatever makes the flow safe stays on the server — the AES key that decrypts QQ's App Secret, and the poll handle that collects WeChat's bot token — generated, held, used and dropped there; the client is given only a task handle, a URL to draw, and a status. Tasks live in memory, are scoped to the Session that started them, are bounded per Session so one caller's scans cannot evict another's, and are claimed by the poll that resolves them, so a replay reads as 404 rather than as a second bind. On QQ a second concurrent poll of one task reads as 404 too; on WeChat it answers `pending`, because the upstream call is a long poll that spans several client intervals. Every scan route is owner-only, because the flow ends in a stored credential however little of it the caller types.
### Preview on a separate origin
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 927b10f3..d186d3e2 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -308,9 +308,9 @@ Workspace 文件可能由 Agent 生成,`GET /files/content` 一律按不可信
文件名始终以 `filename*=UTF-8''` 形式携带(百分号编码)。`preview=1` 是预览跳转在没有独立预览源时的回退目标:文档保留真实类型,可以正常渲染并执行脚本,但沙箱刻意不含 `allow-same-origin`,因此它落在一个不透明源里,既拿不到本源的 Cookie,也调不动 API。这份隔离也正是那里 `localStorage`、`document.cookie` 与第三方 embed 全都不可用的原因。
-### 消息绑定(飞书、Telegram、QQ)
+### 消息绑定(飞书、Telegram、QQ、微信)
-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` 前缀。
+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 网关连接,微信用 `ilink/bot/getupdates` 长轮询——四者都无需公网回调地址。保存与连接是两件事:PUT 只保存凭据,连接由独立的 state 接口开关。路径同上表,省略 `/api/sessions/:sessionId` 前缀。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
@@ -336,11 +336,22 @@ Session 可以接入消息软件机器人——目前的渠道是飞书、Telegr
| POST | /messaging/qq/scan/poll | `{taskId}` → `{status, appId?, binding?}`。`completed` 表示服务端已解密 App Secret 并**保存**了绑定(启用仍是独立动作);`expired` 表示需重新建任务。未知、属于其他 Session 或已完成的任务返回 404 `qq_scan_task_unknown` |
| POST | /messaging/qq/scan/cancel | `{taskId}`——用户中途离开时丢弃该任务,立即忘记其密钥,而不是等待过期清扫 |
| POST | /messaging/qq/test-message | 向最近一次收到消息的会话发送一条固定测试文本;在 QQ 里给机器人发过消息之前返回 409 `qq_no_chat`;没有可回复的近期消息时返回 502 `qq_send_failed`(见下) |
-
-没有已存密钥的配置(被清除过的)不返回掩码字段,也无法启用。`linePerMessage`、`finalReplyOnly` 与 `renderMarkdown` 是仅有的三个不属于凭据的已存字段。开启 `linePerMessage` 后,转发的助手回复中每个非空行各自作为一条消息发出(空行忽略,单行仍按长度上限分段,超出每条回复的消息条数上限的部分合并为最后一条)。开启 `finalReplyOnly` 后,一次运行只转发它**最后**完成的那条助手消息,并在运行结束时发送,而不是每完成一条就转发一条——运行过程中在工具调用之间写下的记录留在网页端;随回复发送的文件也只从这条最终消息中读取提及,因为聊天只收到了它。两者可叠加:同时开启时,被按行拆分的就是这条最终回复。两者默认均为 false,PUT 省略则保持已存值,且都不作用于通知与测试消息——审批提醒尤其不属于回复,无论 `finalReplyOnly` 如何都会立即到达。开启 `renderMarkdown` 后,转发回复中的 Markdown 按各渠道自身的标记语言渲染,而不是把字符原样发出;它**默认为 true**,PUT 省略同样保持已存值,同样不作用于通知与测试消息。各渠道各自渲染力所能及的部分,其余按既定方式降级而非泄漏源码:Telegram 使用 `parse_mode: "HTML"`,没有标题、列表和表格(标题渲染为一行粗体,列表符号作为文本保留,表格改用 `<pre>` 块);飞书发送携带 JSON 2.0 富文本组件的交互卡片,全部构件均可渲染,超长表格改为代码块以免整行被静默丢弃;QQ 使用 `msg_type: 2` 自定义 markdown,没有代码格式也没有表格(代码块按转义后的普通文本行发出,表格按其行发出)。分段随该设置改变:在块边界切分,跨消息的代码块会重新加围栏,因此任何一条消息都不会打开一个它没有闭合的构件。**渠道拒绝的格式化发送会退回为同一条消息的纯文本发送**,因此该设置只可能损失排版,绝不会损失回复。唯一的跨 Session 规则按渠道内机器人账号计,且只作用于连接:一个账号只有一条事件流,因此至多一个 Session 能将其启用。飞书的账号身份是 `app_id`,Telegram 是 Token 冒号前的数字机器人 id(换发 Token 也不会改变)。读取与两个测试接口对任意 Project 成员开放;PUT、state 开关与 DELETE 仅限所有者(与 Vault 同口径——绑定写操作携带或作用于密钥)。密钥永不回传。删除 Session 会连带删除其全部渠道配置。入站处理文本、图片与文件:图片按普通 `image_url` 输入部分送入,单张受服务端的内联图片上限约束,总量再受每个绑定一个滚动窗口的字节预算约束——内联图片会原样写入 Trace,而这条路径不像网页输入框,前面没有任何鉴权。文件按输入框的另一种附件形态送入——写进该 Session 的 Scratchpad,并以 `[attached file: <path>]` 行交给模型,其字节不进入对话——上限沿用管理员可设的单个文件与单条消息附件上限(与经过鉴权的上传同一组数值),并再取渠道自身更紧的那个上限(Telegram 不向机器人提供超过 20MB 的文件)。飞书取 `file` 消息类型,Telegram 取 `document` 字段:发送者主动**以文件形式**发出的那一个,也是 Telegram 各媒体字段中唯一携带发送者原始文件名的。视频、音频与语音有意不予送达——下游没有任何环节能解码或转写它们,而发送者真正想交给智能体的东西,只要按文件发送就会到达。附件**确实会被送达**的消息(图片、文件),其说明文字即该消息的文本;其他媒体类型的说明文字则不是——其字节并不会送达,仅凭说明文字运行只会让模型对一个它从未收到的文件侃侃而谈。图片超过单张上限、超出窗口预算与渠道拒绝下载分别回复三种不同的双语提示;文件超过单个上限、一条消息的文件总量超限与渠道拒绝下载同样各有其提示。它们都不会把半条消息交给模型;因机器人自身权限被拒时,提示会点名所需权限并带上渠道给出的授权链接——飞书通常正是此种情况(接收消息与下载其中的附件是两项独立权限)。其余类型仍收到双语的“暂不支持”回复。出站方向,一次运行结束后会在回复文本之后发送该回复**提及且由本次运行产出**的文件——回复中形如路径、能解析到 Workspace 之内、确实存在、且修改时间不早于本次运行开始的片段,出现在回复的任何位置皆可(「提及」挑出这次真正要交付的那个产物;「修改时间」则确保一条可被会话中任何人引导的回复不会变成读取原语——拒绝粘贴某个文件的回复同样会点到它的名字)——图片按图片发送、其余按文件发送,且按**读取时实际拿到的文件名**分类,而非回复中写下的那个名字;每次运行最多 5 个,单个图片上限 10MB、单个文件上限 30MB(取两个渠道各自限制中更紧的一个)。被提及的文件凡是没送到,都会在会话中说明原因——超过上限、超出数量上限、Workspace 内没有该文件、渠道拒绝上传——唯独「本次运行没有写过」是静默跳过的,因为回复中提到自己读过的配置文件属于常态。Telegram 建立连接时先清空积压:无连接期间发来的消息会被跳过,与飞书“错过的事件即消失”同口径。绑定的运行时状态另外报出该连接**实际见到**的情况——`lastInboundAt`(最近一条消息到达的时间;自本次连接建立以来还没有收到过时该字段缺席)、`lastDeliveryError`(`{at, stage, detail}`,`stage` 为 `inbound` 表示消息已到达但其 Task 没能开始,为 `send` 表示回复没能送达聊天;后续的成功不会把它清掉),以及 `lastConnectionError`(`{at, detail}`,最近一次连接失败,并在连接恢复之后依然保留——不同于属于 `error` 状态、状态一离开就被抹掉的 `lastError`)。三者都只存在于进程内,且每次(重新)建立连接都会清空——重新启用连接或再保存一次凭证,都会开启一条新连接——所以 `lastInboundAt` 缺席只意味着「本次连接以来没有收到过」,而不是「从来没有收到过」。它们的存在是因为一个扣着消息不投递的渠道,表现出来正是 `connected` 且毫无报错。
+| GET | /messaging/wechat | 同一形态下的微信配置(`botId`、`botTokenMasked`) |
+| PUT | /messaging/wechat | **只**保存投递偏好:`{clearBotToken?, linePerMessage?, finalReplyOnly?, renderMarkdown?}`。这是本组唯一不携带凭据的 PUT——微信机器人的 Bot Token 只能由扫码产生,没有可供复制的后台——因此它以已有绑定为前提,绑定不存在时返回 400 `wechat_token_required`。清除开关与其他渠道一致(启用中返回 409 `messaging_disable_before_clear`;被清除的配置保留行与机器人身份,只有重新扫码才能再次连接) |
+| POST | /messaging/wechat/state | 与其他开关同一契约(无已存 Token 时返回 400 `wechat_token_required`) |
+| DELETE | /messaging/wechat | 整体删除该渠道的配置(含 Bot Token)。仅为 API 完整性保留 |
+| POST | /messaging/wechat/test | 凭据探测(以扫码账号身份调用 `ilink/bot/getconfig`)→ `{ok, latencyMs?, error?}`。这是唯一**不接受请求体**的探测:本渠道没有可填写的字段,只能探测已存绑定(没有则返回 400 `wechat_token_required`)。不报出账号名——该探测既不识别机器人,也不识别人 |
+| POST | /messaging/wechat/scan | 发起扫码连接——在本渠道这是**唯一**的绑定方式 → `{taskId, qrUrl, pollMs}`。把 `qrUrl` 渲染成二维码;它由微信打开,服务端从不请求它。平台自身的轮询句柄——也就是能换取 Bot Token 的那个——留在服务端,`taskId` 是服务端另行签发的替代句柄。连接启用中返回 409 `messaging_disable_before_scan`;平台拒绝时返回 502 `wechat_scan_failed` |
+| POST | /messaging/wechat/scan/poll | `{taskId}` → `{status, botId?, binding?}`。`status` 取值为 `pending`、`scanned`、`need_verify_code`、`blocked`、`expired`、`already_bound`、`completed`。`completed` 表示服务端已**保存**绑定(启用仍是独立动作);`already_bound` 不是失败——该机器人已被绑定,没有签发新凭据。它并不说明绑定在**哪里**:本流程不向平台提供任何已持有的 token 列表,因此无法区分「绑定在本服务」与「绑定在别处」。任务未知、属于其他 Session 或已结算时返回 404 `wechat_scan_task_unknown`。与 QQ 不同,**重叠的**轮询返回 `pending` 而非 404:上游是长轮询,一次调用会跨越客户端的多个轮询间隔 |
+| POST | /messaging/wechat/scan/verify | `{taskId, verifyCode}` → 204。微信在手机上显示的配对码。平台把它作为状态查询的参数,因此它随**下一次**轮询携带而不单独发起请求,本接口只做记录——配对码错误会表现为下一次轮询再次返回 `need_verify_code` |
+| POST | /messaging/wechat/scan/cancel | `{taskId}`——用户中途离开时丢弃该任务,立即忘记其句柄,而不是等待过期清扫 |
+| POST | /messaging/wechat/test-message | 向最近一次收到消息的会话发送一条固定测试文本;在微信里给机器人发过消息之前返回 409 `wechat_no_chat` |
+
+没有已存密钥的配置(被清除过的)不返回掩码字段,也无法启用。`linePerMessage`、`finalReplyOnly` 与 `renderMarkdown` 是仅有的三个不属于凭据的已存字段。开启 `linePerMessage` 后,转发的助手回复中每个非空行各自作为一条消息发出(空行忽略,单行仍按长度上限分段,超出每条回复的消息条数上限的部分合并为最后一条)。开启 `finalReplyOnly` 后,一次运行只转发它**最后**完成的那条助手消息,并在运行结束时发送,而不是每完成一条就转发一条——运行过程中在工具调用之间写下的记录留在网页端;随回复发送的文件也只从这条最终消息中读取提及,因为聊天只收到了它。两者可叠加:同时开启时,被按行拆分的就是这条最终回复。两者默认均为 false,PUT 省略则保持已存值,且都不作用于通知与测试消息——审批提醒尤其不属于回复,无论 `finalReplyOnly` 如何都会立即到达。开启 `renderMarkdown` 后,转发回复中的 Markdown 按各渠道自身的标记语言渲染,而不是把字符原样发出;它**默认为 true**,PUT 省略同样保持已存值,同样不作用于通知与测试消息。各渠道各自渲染力所能及的部分,其余按既定方式降级而非泄漏源码:Telegram 使用 `parse_mode: "HTML"`,没有标题、列表和表格(标题渲染为一行粗体,列表符号作为文本保留,表格改用 `<pre>` 块);飞书发送携带 JSON 2.0 富文本组件的交互卡片,全部构件均可渲染,超长表格改为代码块以免整行被静默丢弃;QQ 使用 `msg_type: 2` 自定义 markdown,没有代码格式也没有表格(代码块按转义后的普通文本行发出,表格按其行发出);微信自己就读 Markdown,因此渲染是**做减法**而不是翻译——客户端不会呈现的部分保留文字、去掉标记(四级以上的标题、CJK 两侧的强调,以及内联图片,后者改为链接)。分段随该设置改变:在块边界切分,跨消息的代码块会重新加围栏,因此任何一条消息都不会打开一个它没有闭合的构件。**渠道拒绝的格式化发送会退回为同一条消息的纯文本发送**,因此该设置只可能损失排版,绝不会损失回复。唯一的跨 Session 规则按渠道内机器人账号计,且只作用于连接:一个账号只有一条事件流,因此至多一个 Session 能将其启用。飞书的账号身份是 `app_id`,Telegram 是 Token 冒号前的数字机器人 id(换发 Token 也不会改变),微信则是扫码返回的机器人 id。读取与两个测试接口对任意 Project 成员开放;PUT、state 开关与 DELETE 仅限所有者(与 Vault 同口径——绑定写操作携带或作用于密钥)。密钥永不回传。删除 Session 会连带删除其全部渠道配置。入站处理文本、图片与文件:图片按普通 `image_url` 输入部分送入,单张受服务端的内联图片上限约束,总量再受每个绑定一个滚动窗口的字节预算约束——内联图片会原样写入 Trace,而这条路径不像网页输入框,前面没有任何鉴权。文件按输入框的另一种附件形态送入——写进该 Session 的 Scratchpad,并以 `[attached file: <path>]` 行交给模型,其字节不进入对话——上限沿用管理员可设的单个文件与单条消息附件上限(与经过鉴权的上传同一组数值),并再取渠道自身更紧的那个上限(Telegram 不向机器人提供超过 20MB 的文件)。飞书取 `file` 消息类型,Telegram 取 `document` 字段:发送者主动**以文件形式**发出的那一个,也是 Telegram 各媒体字段中唯一携带发送者原始文件名的。在这两个渠道上,视频、音频与语音有意不予送达——下游没有任何环节能解码或转写它们,而发送者真正想交给智能体的东西,只要按文件发送就会到达。微信是例外,且仅仅因为解码由平台自己完成:语音消息随附它自己的转写文本,视频则作为普通文件到达。附件**确实会被送达**的消息(图片、文件),其说明文字即该消息的文本;其他媒体类型的说明文字则不是——其字节并不会送达,仅凭说明文字运行只会让模型对一个它从未收到的文件侃侃而谈。图片超过单张上限、超出窗口预算与渠道拒绝下载分别回复三种不同的双语提示;文件超过单个上限、一条消息的文件总量超限与渠道拒绝下载同样各有其提示。它们都不会把半条消息交给模型;因机器人自身权限被拒时,提示会点名所需权限并带上渠道给出的授权链接——飞书通常正是此种情况(接收消息与下载其中的附件是两项独立权限)。其余类型仍收到双语的“暂不支持”回复。出站方向,一次运行结束后会在回复文本之后发送该回复**提及且由本次运行产出**的文件——回复中形如路径、能解析到 Workspace 之内、确实存在、且修改时间不早于本次运行开始的片段,出现在回复的任何位置皆可(「提及」挑出这次真正要交付的那个产物;「修改时间」则确保一条可被会话中任何人引导的回复不会变成读取原语——拒绝粘贴某个文件的回复同样会点到它的名字)——图片按图片发送、其余按文件发送,且按**读取时实际拿到的文件名**分类,而非回复中写下的那个名字;每次运行最多 5 个,单个图片上限 10MB、单个文件上限 30MB(取两个渠道各自限制中更紧的一个)。被提及的文件凡是没送到,都会在会话中说明原因——超过上限、超出数量上限、Workspace 内没有该文件、渠道拒绝上传——唯独「本次运行没有写过」是静默跳过的,因为回复中提到自己读过的配置文件属于常态。Telegram 建立连接时先清空积压:无连接期间发来的消息会被跳过,与飞书“错过的事件即消失”同口径。绑定的运行时状态另外报出该连接**实际见到**的情况——`lastInboundAt`(最近一条消息到达的时间;自本次连接建立以来还没有收到过时该字段缺席)、`lastDeliveryError`(`{at, stage, detail}`,`stage` 为 `inbound` 表示消息已到达但其 Task 没能开始,为 `send` 表示回复没能送达聊天;后续的成功不会把它清掉),以及 `lastConnectionError`(`{at, detail}`,最近一次连接失败,并在连接恢复之后依然保留——不同于属于 `error` 状态、状态一离开就被抹掉的 `lastError`)。三者都只存在于进程内,且每次(重新)建立连接都会清空——重新启用连接或再保存一次凭证,都会开启一条新连接——所以 `lastInboundAt` 缺席只意味着「本次连接以来没有收到过」,而不是「从来没有收到过」。它们的存在是因为一个扣着消息不投递的渠道,表现出来正是 `connected` 且毫无报错。
**QQ 是只能被动回复的渠道,这改变了「送达」的含义。** 平台不提供本产品可用的主动推送:每一条外发消息都是携带入站 `msg_id` 的*被动回复*,有效期只有几分钟,且单聊对同一条消息最多 4 条回复(群聊 5 条)。由此有三点在 API 上可见。一次运行完成的助手消息超过该额度时会被**合并**——前 `budget - 1` 条随完成即时发出,其余合并为最后一条送达,内容不丢。`linePerMessage` 的拆分上限**收敛到该额度**,而不是渠道无关的 20;被平台拒绝的 `renderMarkdown` 发送,其纯文本重试会再占用一次额度。`finalReplyOnly` 在这里有利有弊:它把一次运行的额度消耗压到最低——只发一条;但被动回复的有效期只有几分钟,把回复扣到运行结束才发,等于把这个窗口花在了运行本身上,运行时长超过窗口时将什么都送不出去,而逐条转发至少能把窗口之内完成的部分发出去。而没有可回复对象的发送——在网页端发起的对话,或窗口关闭之后的回复——会被**拒绝而非主动推送**:测试接口上表现为 502 `qq_send_failed`,转发回复则记为一条 `messaging_send_failed` 错误记录。QQ 的账号身份是 App ID。该渠道拒绝外发文件:平台的富媒体接口要求为文件提供公网可达地址。
+**微信只承载单聊,但媒体能力是四个渠道里最全的。** 该机器人渠道完全不接收群消息:在群里 @机器人的消息根本不会到达本 API,因此单聊正常、群聊沉默是渠道形态而非配置错误。作为交换,它是这里唯一能**双向**传输文字、图片与文件的渠道——回复中的图片与附件会上传到平台 CDN(每个文件一把 AES-128-ECB 密钥),以真正的图片和文件到达,而不是被拒绝。两类入站消息被折叠处理:语音消息按微信自带的语音转文字结果进入对话,视频按文件到达;微信没能转写的语音则以共用的「不支持」提示回到聊天。
-**扫码连接不会把密钥交给浏览器。** 解密 App Secret 的 AES 密钥在服务端生成、持有、使用并丢弃;客户端只拿到任务句柄、待绘制的 URL 与状态。任务只存在于内存,归属发起它的 Session,按 Session 单独限量(一个调用方的扫码任务挤不掉另一个调用方的),并被「解决它的那一次轮询」认领掉,因此重放与对同一任务的并发轮询得到的都是 404,而不是第二次绑定。所有扫码路由都仅限 Project 所有者——无论调用方实际输入了多少内容,这个流程的终点都是一份存下来的凭据。
+**扫码连接不会把机密交给浏览器。** 让这套流程安全的东西都留在服务端——解密 QQ App Secret 的 AES 密钥,以及换取微信 Bot Token 的轮询句柄——在服务端生成、持有、使用并丢弃;客户端只拿到任务句柄、待绘制的 URL 与状态。任务只存在于内存,归属发起它的 Session,按 Session 单独限量(一个调用方的扫码任务挤不掉另一个调用方的),并被「解决它的那一次轮询」认领掉,因此重放得到的是 404 而不是第二次绑定。对同一任务的并发轮询在 QQ 上同样是 404;在微信上返回 `pending`,因为上游是一次跨越客户端多个轮询间隔的长轮询。所有扫码路由都仅限 Project 所有者——无论调用方实际输入了多少内容,这个流程的终点都是一份存下来的凭据。
### 独立源预览
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 7a7acfd3..ca62f286 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -1650,7 +1650,7 @@ export interface SessionProcessesResponse {
// ---------------------------------------------------------------------------
/** Messaging channels a Session can bind to. */
-export type MessagingChannel = "feishu" | "telegram" | "qq";
+export type MessagingChannel = "feishu" | "telegram" | "qq" | "wechat";
/** Event-connection runtime state of one binding (kept in memory, not persisted). */
export type MessagingRuntimeState = "disconnected" | "connecting" | "connected" | "error";
@@ -1745,7 +1745,8 @@ export interface MessagingBindingCommon {
/**
* Render a relayed reply's Markdown in this channel's own markup instead of sending its
* characters as written. ON by default. Each channel shows what it can — Telegram has no
- * headings, lists or tables, QQ has no code or tables, Feishu has all of them — and a
+ * headings, lists or tables, QQ has no code or tables, Feishu has all of them, and WeChat
+ * reads Markdown itself so the render is a subtraction rather than a translation — and a
* rendering the channel refuses falls back to the plain source, so this can cost
* formatting and never a message.
*/
@@ -1836,8 +1837,29 @@ export interface QQBindingInfo extends MessagingBindingCommon {
lastChatKnown: boolean;
}
+/**
+ * The stored WeChat config, token masked (plaintext never leaves the server).
+ *
+ * No preference field is re-declared. The three delivery preferences cost exactly what they
+ * cost on Feishu and Telegram here — this channel has no reply budget and no expiring reply
+ * window — and re-declaring a field to say nothing new about it would only invite the next
+ * reader to look for the difference.
+ */
+export interface WeChatBindingInfo extends MessagingBindingCommon {
+ channel: "wechat";
+ /** The bot id a scan issued — the channel-scoped account identity, never secret. */
+ botId: string;
+ /**
+ * Masked bot token (site-wide mask rule: `***`, or `first4…last4` for long values);
+ * absent when none is stored (cleared, or a scan that never completed) — the binding
+ * cannot be enabled until a scan saves one.
+ */
+ botTokenMasked?: string;
+}
+
/** A Session's saved config for one messaging channel (`channel` is the discriminant). */
-export type MessagingBindingInfo = FeishuBindingInfo | TelegramBindingInfo | QQBindingInfo;
+export type MessagingBindingInfo =
+ FeishuBindingInfo | TelegramBindingInfo | QQBindingInfo | WeChatBindingInfo;
/** One saved channel config with its event-connection runtime status. */
export interface MessagingChannelState {
@@ -1873,6 +1895,12 @@ export interface QQBindingResponse {
status: MessagingRuntimeStatus;
}
+/** GET / PUT …/messaging/wechat response (the WeChat narrowing of the same envelope). */
+export interface WeChatBindingResponse {
+ binding: WeChatBindingInfo | 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
@@ -1941,6 +1969,24 @@ export interface QQBindingPutRequest extends MessagingDeliveryPatch {
clearAppSecret?: boolean;
}
+/**
+ * PUT …/messaging/wechat — the delivery preferences ONLY.
+ *
+ * The one PUT on this router that carries no credential, because there is none to carry: a
+ * WeChat bot token exists only where a scan put it, and there is no console to copy one out
+ * of. Saving therefore presupposes a binding — a PUT before any scan answers 400
+ * `wechat_token_required` rather than creating an empty row — and the connection toggle
+ * stays POST …/state, as on every channel.
+ */
+export interface WeChatBindingPutRequest extends MessagingDeliveryPatch {
+ /**
+ * Drops the STORED token (the models-page clear idiom). Refused with 409
+ * `messaging_disable_before_clear` while the binding is enabled. The row and its bot
+ * identity stay; only a fresh scan can make it connectable again.
+ */
+ clearBotToken?: 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
@@ -2041,6 +2087,94 @@ export interface QQScanPollResponse {
binding?: QQBindingInfo;
}
+/**
+ * WeChat credential-test outcome. There is no request body and no draft to probe: this
+ * channel's credential exists only where a scan put it, so the test always probes the STORED
+ * binding. It answers 400 `wechat_token_required` when there is none.
+ *
+ * No account label, for the same reason QQ has none: the probe (`getconfig`) reports the
+ * bot's settings and names neither the bot nor the person.
+ */
+export interface WeChatTestResponse {
+ ok: boolean;
+ latencyMs?: number;
+ error?: string;
+}
+
+/**
+ * POST …/messaging/wechat/scan — starts a scan-to-connect flow, which on this channel is the
+ * ONLY way to bind: the bot token has no console to be copied out of.
+ *
+ * The server registers a code and answers with what the browser may know. The platform's own
+ * poll handle is absent from this type on purpose — it is what collects the bot token, so it
+ * never leaves the server, and `taskId` is a handle this server mints in its place.
+ */
+export interface WeChatScanStartResponse {
+ /** Opaque scan handle, passed back to the poll, verify and cancel endpoints. */
+ taskId: string;
+ /** The URL to ENCODE into a QR code. It is opened by WeChat, never fetched by the browser. */
+ qrUrl: string;
+ /** How often to poll, in milliseconds. */
+ pollMs: number;
+}
+
+/**
+ * Where a WeChat scan stands. Richer than QQ's four states because the flow is: WeChat
+ * separates scanning from confirming, and may interpose a pairing code shown on the phone.
+ *
+ * - `pending` — the code is up and nothing has happened; keep polling.
+ * - `scanned` — scanned; the phone is showing the confirmation prompt.
+ * - `need_verify_code` — the phone is showing digits that must be sent to the verify
+ * endpoint before the bind proceeds.
+ * - `blocked` — too many wrong pairing codes; the code is spent and a new scan is needed.
+ * - `expired` — the code lapsed before it was used; show a new one.
+ * - `already_bound` — this bot is already bound to this server, so no new credentials were
+ * issued and nothing was saved. Not a failure: the existing binding still works.
+ * - `completed` — the server has already SAVED the binding; `botId` names the bot.
+ */
+export type WeChatScanStatus =
+ | "pending"
+ | "scanned"
+ | "need_verify_code"
+ | "blocked"
+ | "expired"
+ | "already_bound"
+ | "completed";
+
+/**
+ * POST …/messaging/wechat/scan/poll — one step of the scan.
+ *
+ * `completed` means the server has decrypted nothing and stored everything: the credentials
+ * went from the platform into storage without passing through the browser. Saving is all it
+ * does — enabling the connection stays the separate, exclusive act it is on every channel. A
+ * task id that is unknown, belongs to another Session, or was already resolved answers 404
+ * `wechat_scan_task_unknown`.
+ *
+ * Unlike QQ's poll, an overlapping request answers `pending` rather than 404: the upstream
+ * call is a LONG poll, so one of them spans several of the client's intervals, and that
+ * overlap is the normal rhythm rather than a replay.
+ */
+export interface WeChatScanPollResponse {
+ status: WeChatScanStatus;
+ /** The bound bot's id; present only on `completed`. Never the token. */
+ botId?: string;
+ /** The saved binding, present on `completed` so the editor refreshes without a second GET. */
+ binding?: WeChatBindingInfo;
+}
+
+/**
+ * POST …/messaging/wechat/scan/verify — the digits WeChat showed on the phone.
+ *
+ * They ride the NEXT poll rather than a request of their own, because the platform takes the
+ * pairing code as a parameter of the status call: this endpoint records them and answers
+ * 204. A wrong code is not reported here — the next poll asks for one again, which is how
+ * the platform reports it.
+ */
+export interface WeChatScanVerifyRequest {
+ taskId: string;
+ verifyCode: string;
+}
+
/**
* POST …/messaging/<channel>/test-message — sent to the last known chat (409
* `feishu_no_chat` / `telegram_no_chat` / `qq_no_chat` before one exists). On QQ this can
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index df0827dc..3ced2e75 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -86,6 +86,11 @@ 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 { QQScanService, createQQScanTransport } from "./runtime/messaging/qq-scan.js";
+import { WeChatConnector } from "./runtime/messaging/wechat-connector.js";
+import { createWeChatTransport } from "./runtime/messaging/wechat-api.js";
+import type { WeChatTransport } from "./runtime/messaging/wechat-api.js";
+import { WeChatScanService, createWeChatScanTransport } from "./runtime/messaging/wechat-scan.js";
+import type { WeChatScanTransport } from "./runtime/messaging/wechat-scan.js";
import type { QQScanTransport } from "./runtime/messaging/qq-scan.js";
import { TitleGenerator, TitleNotifier } from "./runtime/title-generator.js";
import { AdminService } from "./services/admin-service.js";
@@ -191,6 +196,8 @@ export interface AppDeps {
messaging: MessagingBridge;
/** QQ scan-to-connect: the in-flight bind tasks and the AES keys that never leave the server. */
qqScan: QQScanService;
+ /** WeChat scan-to-connect: the in-flight codes and the poll handles that never leave the server. */
+ wechatScan: WeChatScanService;
scheduler: Scheduler;
channels: ChannelHub;
manager: SessionManager;
@@ -242,6 +249,12 @@ export interface BuildDepsOverrides {
messagingInboundImageBudgetBytes?: number;
/** Test double: the QQ scan-to-connect transport (avoids real q.qq.com requests). */
qqScanTransport?: QQScanTransport;
+ /** Test double: the WeChat connector's long-poll + CDN transport (avoids real WeChat network). */
+ wechatTransport?: WeChatTransport;
+ /** Test hook: the WeChat poll loop's backoff (tests collapse it to zero). */
+ wechatRetryDelayMs?: (failures: number) => number;
+ /** Test double: the WeChat scan-to-connect transport (avoids real ilinkai.weixin.qq.com requests). */
+ wechatScanTransport?: WeChatScanTransport;
/** Test double: machines service whose ssh effects are faked (the real one reads ~/.ssh/config and spawns ssh). */
machines?: MachinesService;
/**
@@ -864,6 +877,10 @@ export function buildAppDeps(
...(overrides.qqTailFlushMs !== undefined ? { tailFlushMs: overrides.qqTailFlushMs } : {}),
...(overrides.now ? { now: () => overrides.now!().getTime() } : {}),
}),
+ new WeChatConnector(
+ overrides.wechatTransport ?? createWeChatTransport(),
+ overrides.wechatRetryDelayMs ? { retryDelayMs: overrides.wechatRetryDelayMs } : {},
+ ),
],
errors,
log,
@@ -880,6 +897,12 @@ export function buildAppDeps(
const qqScan = new QQScanService(overrides.qqScanTransport ?? createQQScanTransport(), {
...(overrides.now ? { now: () => overrides.now!().getTime() } : {}),
});
+ // Same reasoning as above: what this one holds is the handle that collects a bot token
+ // rather than a key that decrypts a secret, and it is equally not worth persisting.
+ const wechatScan = new WeChatScanService(
+ overrides.wechatScanTransport ?? createWeChatScanTransport(),
+ { ...(overrides.now ? { now: () => overrides.now!().getTime() } : {}) },
+ );
const sessionService = new SessionService({
root: config.root,
sessions: sessionsRepo,
@@ -895,7 +918,10 @@ export function buildAppDeps(
messagingChannel: (sessionId) => {
const enabled = messagingRepo.findEnabled(sessionId);
return enabled !== null &&
- (enabled.channel === "feishu" || enabled.channel === "telegram" || enabled.channel === "qq")
+ (enabled.channel === "feishu" ||
+ enabled.channel === "telegram" ||
+ enabled.channel === "qq" ||
+ enabled.channel === "wechat")
? enabled.channel
: null;
},
@@ -945,6 +971,7 @@ export function buildAppDeps(
errorsRepo,
messagingRepo,
qqScan,
+ wechatScan,
messaging,
scheduler,
channels,
diff --git a/packages/server/src/db/repos/messaging-bindings.ts b/packages/server/src/db/repos/messaging-bindings.ts
index 6636b798..45c010ef 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, Telegram and QQ today).
+ * Repo for Session ↔ messaging-channel bot bindings (Feishu, Telegram, QQ and WeChat 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
@@ -31,11 +31,11 @@ import type { DatabaseSync } from "node:sqlite";
export interface MessagingBindingRow {
sessionId: string;
- /** Messaging channel discriminator (`feishu` | `telegram` | `qq`). */
+ /** Messaging channel discriminator (`feishu` | `telegram` | `qq` | `wechat`). */
channel: string;
- /** Channel-scoped bot/app identity (feishu: the app_id; telegram: the bot token's numeric id; qq: the App ID); never secret. */
+ /** Channel-scoped bot/app identity (feishu: the app_id; telegram: the bot token's numeric id; qq: the App ID; wechat: the scanned bot id); never secret. */
accountId: string;
- /** Channel-specific config document (feishu: appId/appSecret/baseDomain; telegram: botToken; qq: appId/appSecret). */
+ /** Channel-specific config document (feishu: appId/appSecret/baseDomain; telegram: botToken; qq: appId/appSecret; wechat: botId/botToken/baseUrl/userId). */
config: Record<string, unknown>;
/**
* INTENT state: whether the binding should hold a live connection (the connection's
diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.ts
index 978dc6e5..a2ac9520 100644
--- a/packages/server/src/db/schema.ts
+++ b/packages/server/src/db/schema.ts
@@ -132,13 +132,13 @@ 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' | '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)
+ channel TEXT NOT NULL, -- messaging channel discriminator ('feishu' | 'telegram' | 'qq' | 'wechat')
+ 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; wechat: the scanned bot 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; wechat: botId/botToken/baseUrl/userId); 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 does
line_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 owns
final_reply_only INTEGER NOT NULL DEFAULT 0, -- delivery preference: 1 = a run's intermediate assistant messages are held and only its LAST completed one is sent, at the run's end, 0 = every completed assistant message mirrors the moment it completes. Channel-agnostic like the column above and independent of it: with both set, that one final text is the one split per line
- render_markdown INTEGER NOT NULL DEFAULT 1, -- delivery preference: 1 = a relayed reply's Markdown is rendered in the channel's own markup (Telegram HTML, a Feishu card, QQ markdown), 0 = the reply's characters are sent as written. DEFAULT 1 because the model writes Markdown and showing it raw was the defect; the per-channel subsets and the plain-text fallback live in the connectors
+ render_markdown INTEGER NOT NULL DEFAULT 1, -- delivery preference: 1 = a relayed reply's Markdown is rendered in the channel's own markup (Telegram HTML, a Feishu card, QQ markdown, the subset WeChat itself reads), 0 = the reply's characters are sent as written. DEFAULT 1 because the model writes Markdown and showing it raw was the defect; the per-channel subsets and the plain-text fallback live in the connectors
last_chat_id TEXT, -- most recent inbound chat (NULL until the bot is messaged once; replies and test messages target it); CONNECTOR-OPAQUE, not necessarily a bare chat id — telegram appends the forum topic (see telegram-connector.ts chatRefOf), so only that channel's connector may interpret it
last_chat_is_direct INTEGER NOT NULL DEFAULT 1, -- 1 = direct chat (reply by chat id), 0 = group chat (prefer reply-to-message)
last_inbound_message_id TEXT, -- channel id of the most recently PROCESSED inbound message (NULL until one arrives); the durable half of the bridge's redelivery guard, so a channel replaying an event this server already turned into a Task after a restart does not run it twice
diff --git a/packages/server/src/http/routes/messaging.ts b/packages/server/src/http/routes/messaging.ts
index d9f3d1c4..87707cda 100644
--- a/packages/server/src/http/routes/messaging.ts
+++ b/packages/server/src/http/routes/messaging.ts
@@ -3,7 +3,8 @@
* editor's and the Messaging dock panel's shared surface. A Session keeps at most one
* 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.
+ * /feishu, /telegram, /qq and /wechat 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
@@ -20,11 +21,15 @@
* and run the two tests; the secret-mutating writes — PUT, the state toggle and DELETE —
* are Project-owner-only.
*
- * QQ additionally offers a scan-to-connect flow (`/qq/scan…`): the server holds the bind
- * task and the AES key that decrypts the App Secret, polls on the browser's behalf, and
- * stores the result. The browser only ever learns the task handle, the URL to render as a QR
- * code, and the App ID that came back — the same never-round-trip-the-secret rule the PUT
- * handlers follow, applied to a secret that arrives from outside instead of from the user.
+ * Two channels offer a scan-to-connect flow, and the server holds what makes it safe in both:
+ * QQ's (`/qq/scan…`) keeps the AES key that decrypts the App Secret, WeChat's
+ * (`/wechat/scan…`) keeps the poll handle that collects the bot token. Each polls on the
+ * browser's behalf and stores the result; the browser only ever learns a task handle, the URL
+ * to render as a QR code, and the non-secret account id that came back — the same
+ * never-round-trip-the-secret rule the PUT handlers follow, applied to a secret that arrives
+ * from outside instead of from the user. On WeChat the scan is not the convenient path but
+ * the ONLY one: there is no console to copy a token out of, so its PUT carries preferences
+ * alone.
*
* A PUT also carries the three saved fields that are not credentials: `linePerMessage`
* (whether a relayed reply is delivered one message per non-blank line), `finalReplyOnly`
@@ -60,6 +65,11 @@ import type {
TelegramBindingInfo,
TelegramBindingResponse,
TelegramTestResponse,
+ WeChatBindingInfo,
+ WeChatBindingResponse,
+ WeChatScanPollResponse,
+ WeChatScanStartResponse,
+ WeChatTestResponse,
} from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
import type { MessagingBindingRow } from "../../db/repos/messaging-bindings.js";
@@ -115,7 +125,22 @@ function qqFieldsOf(row: MessagingBindingRow): { appId: string; appSecret: strin
}
/**
- * The three channels, each saying only what it does not share (see messaging-channels.ts).
+ * The stored wechat config, tolerated loosely (a malformed document reads as blanks).
+ *
+ * `baseUrl` and `userId` are not projected anywhere: the first is an infrastructure detail a
+ * scan chose, and the second identifies the person who scanned. Neither is something the
+ * editor renders or a caller may set, so they stay inside the document the connector reads.
+ */
+function wechatFieldsOf(row: MessagingBindingRow): { botId: string; botToken: string } {
+ const { botId, botToken } = row.config;
+ return {
+ botId: typeof botId === "string" ? botId : row.accountId,
+ botToken: typeof botToken === "string" ? botToken : "",
+ };
+}
+
+/**
+ * The four channels, each saying only what it does not share (see messaging-channels.ts).
* Everything written against this table — the read, the state toggle, the delete, the test
* message, the enable gate's credential check — is written once.
*
@@ -169,6 +194,23 @@ const CHANNEL_SPECS: Readonly<Record<MessagingChannel, MessagingChannelSpec>> =
};
},
},
+ wechat: {
+ channel: "wechat",
+ label: "WeChat",
+ storedSecret: (row) => wechatFieldsOf(row).botToken,
+ secretRequiredCode: "wechat_token_required",
+ toInfo: (row) => {
+ const fields = wechatFieldsOf(row);
+ return {
+ channel: "wechat",
+ ...commonBindingFields(row),
+ // The bot id is the row's account identity as well as a config field: a cleared
+ // token leaves the row still knowing which bot it was bound to.
+ botId: fields.botId,
+ ...maskedSecretField("botTokenMasked", fields.botToken),
+ };
+ },
+ },
};
/** The spec for a stored row's channel, or null on an unknown discriminator (skipped defensively, like the bridge does). */
@@ -244,6 +286,8 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
bindingResponse(sessionId, CHANNEL_SPECS.telegram) as TelegramBindingResponse;
const qqResponse = (sessionId: string): QQBindingResponse =>
bindingResponse(sessionId, CHANNEL_SPECS.qq) as QQBindingResponse;
+ const wechatResponse = (sessionId: string): WeChatBindingResponse =>
+ bindingResponse(sessionId, CHANNEL_SPECS.wechat) as WeChatBindingResponse;
/**
* The one-connection-per-account rule, on its own because two paths need it: the enable,
@@ -301,6 +345,46 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
}
};
+ /**
+ * The disable-first rule both scan flows start with. A server rule rather than a greyed-out
+ * button: a scan rewrites the whole credential and would point a live connector at whatever
+ * account was scanned, which the PUT's account guard exists to prevent it doing silently.
+ */
+ const guardScanStart = (sessionId: string, channel: MessagingChannel): void => {
+ if (deps.messagingRepo.find(sessionId, channel)?.enabled === true) {
+ throw new HttpError(
+ 409,
+ "messaging_disable_before_scan",
+ "Disable the connection before rebinding it by scan.",
+ );
+ }
+ };
+
+ /**
+ * Storing what a completed scan produced — identical on both channels that have one, which
+ * is why it is here rather than written twice.
+ *
+ * It stores only: enabling stays the separate act it is everywhere, because enabling is
+ * what binds the account and is exclusive. The account guard runs because the start refused
+ * an enabled binding and this fires anyway when the connection was switched on WHILE the
+ * scan was in flight — an enabled binding re-pointed at an account another Session holds
+ * would stand two connections on one bot's single event stream without either passing the
+ * enable gate. The restart of an enabled connector is the same never-diverge rule the PUTs
+ * follow.
+ */
+ const saveScanResult = async (
+ sessionId: string,
+ channel: MessagingChannel,
+ accountId: string,
+ config: Record<string, unknown>,
+ ): Promise<MessagingBindingRow> => {
+ const bound = deps.messagingRepo.find(sessionId, channel);
+ if (bound !== null && bound.enabled) guardAccountFree(sessionId, channel, accountId);
+ const saved = deps.messagingRepo.upsert({ sessionId, channel, accountId, config });
+ if (saved.enabled) await deps.messaging.sync(sessionId);
+ return saved;
+ };
+
// The channel-agnostic read: every saved channel config with its runtime status. The
// channel-aware binding editor loads this one endpoint and renders both channel forms
// (and the at-most-one-enabled state) from it.
@@ -573,16 +657,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/:sessionId/messaging/qq/scan", async (c) => {
const row = resolveSession(c);
deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
- // Disable-first is a server rule, not just a greyed-out button: a scan rewrites BOTH
- // halves of the credential and would point a live connector at whatever account was
- // scanned, which the PUT's account guard exists to prevent it doing silently.
- if (deps.messagingRepo.find(row.sessionId, "qq")?.enabled === true) {
- throw new HttpError(
- 409,
- "messaging_disable_before_scan",
- "Disable the connection before rebinding it by scan.",
- );
- }
+ guardScanStart(row.sessionId, "qq");
let started: { taskId: string; qrUrl: string; pollMs: number };
try {
started = await deps.qqScan.start(row.sessionId);
@@ -615,23 +690,11 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
if (result.status !== "completed" || result.bot === undefined) {
return c.json({ status: result.status } satisfies QQScanPollResponse);
}
- // The scan landed: store it exactly as the PUT would, including the never-diverge
- // restart of an enabled connector. It stores only — enabling stays the separate act it
- // is on every channel, because enabling is what binds the account and is exclusive.
- //
- // The start refused an enabled binding, so this only fires when the connection was
- // switched on WHILE the scan was in flight. Same guard as the PUT then: an enabled
- // binding re-pointed at an account another Session holds would stand two connections on
- // one bot's single gateway without either passing the enable gate.
- const bound = deps.messagingRepo.find(row.sessionId, "qq");
- if (bound !== null && bound.enabled) guardAccountFree(row.sessionId, "qq", result.bot.appId);
- const saved = deps.messagingRepo.upsert({
- sessionId: row.sessionId,
- channel: "qq",
- accountId: result.bot.appId,
- config: { appId: result.bot.appId, appSecret: result.bot.appSecret },
+ // The scan landed: store it exactly as the PUT would (see saveScanResult).
+ const saved = await saveScanResult(row.sessionId, "qq", result.bot.appId, {
+ appId: result.bot.appId,
+ appSecret: result.bot.appSecret,
});
- if (saved.enabled) await deps.messaging.sync(row.sessionId);
return c.json({
status: "completed",
appId: result.bot.appId,
@@ -670,6 +733,178 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
...(result.error !== undefined ? { error: result.error } : {}),
} satisfies QQTestResponse);
});
+ // —— WeChat ————————————————————————————————————————————————————————————————
+ //
+ // The channel with no credential to type. A bot token exists only where a scan put it —
+ // there is no developer console for this channel and no pair of fields to fall back to —
+ // so the PUT below carries the delivery preferences and nothing else, and the scan routes
+ // are the whole of how a binding comes to exist.
+
+ /**
+ * Saves the delivery preferences. It presupposes a binding rather than creating one: with
+ * no credential in the request there is nothing a first PUT could store, and a row written
+ * without one could never be enabled.
+ */
+ app.put("/:sessionId/messaging/wechat", async (c) => {
+ const row = resolveSession(c);
+ deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ const body = await readJson(c);
+ const existing = deps.messagingRepo.find(row.sessionId, "wechat");
+ if (existing === null) {
+ throw new HttpError(
+ 400,
+ "wechat_token_required",
+ "Bind by scanning a QR code first: there is no saved WeChat config to update.",
+ );
+ }
+ // The same ladder every channel climbs, entered one rung down: there is no typed
+ // credential here, so it decides only between the clear flag and the stored token.
+ const { secret: botToken } = resolveSecret({
+ typed: undefined,
+ clear: (body as { clearBotToken?: unknown }).clearBotToken === true,
+ existing,
+ stored: wechatFieldsOf(existing).botToken,
+ requiredCode: "wechat_token_required",
+ requiredMessage: "Bind by scanning a QR code first.",
+ });
+ const saved = deps.messagingRepo.upsert({
+ sessionId: row.sessionId,
+ channel: "wechat",
+ accountId: existing.accountId,
+ // The stored document carried forward with only the token replaced: it also holds the
+ // API host the scan assigned and the id of the person who scanned, neither of which
+ // this request knows and both of which the connector needs.
+ config: { ...existing.config, botToken },
+ ...deliveryPatchOf(body),
+ });
+ // Same save/enable split as every other channel: only an enabled binding restarts its
+ // connector, so the stored config and the live connection never diverge.
+ if (saved.enabled) await deps.messaging.sync(row.sessionId);
+ return c.json(wechatResponse(row.sessionId));
+ });
+
+ // —— WeChat scan-to-connect ————————————————————————————————————————————————
+ //
+ // Four routes rather than QQ's three: WeChat may interpose a pairing code shown on the
+ // phone, and the digits need somewhere to arrive. They ride the next poll rather than a
+ // request of their own, because the platform takes the code as a parameter of its status
+ // call — so `verify` records them and answers 204.
+ //
+ // Owner-only throughout, like every other write here: the flow ends in a stored credential,
+ // so it is a credential write however little of it the caller types.
+
+ app.post("/:sessionId/messaging/wechat/scan", async (c) => {
+ const row = resolveSession(c);
+ deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ guardScanStart(row.sessionId, "wechat");
+ let started: { taskId: string; qrUrl: string; pollMs: number };
+ try {
+ started = await deps.wechatScan.start(row.sessionId);
+ } catch (err) {
+ throw new HttpError(
+ 502,
+ "wechat_scan_failed",
+ err instanceof Error ? err.message : String(err),
+ );
+ }
+ return c.json(started satisfies WeChatScanStartResponse);
+ });
+
+ app.post("/:sessionId/messaging/wechat/scan/poll", async (c) => {
+ const row = resolveSession(c);
+ deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ const body = await readJson(c);
+ const taskId = requireString(body, "taskId", { minLen: 1, maxLen: 500 });
+ let result: Awaited<ReturnType<typeof deps.wechatScan.poll>>;
+ try {
+ result = await deps.wechatScan.poll(row.sessionId, taskId);
+ } catch (err) {
+ throw new HttpError(
+ 502,
+ "wechat_scan_failed",
+ err instanceof Error ? err.message : String(err),
+ );
+ }
+ // Unknown, another Session's, or already resolved. An overlapping poll is NOT this — the
+ // upstream call is a long poll and the scan service answers those `pending` (see
+ // wechat-scan.ts), so a client whose interval outpaces the platform is not an error.
+ if (result === null) {
+ throw new HttpError(
+ 404,
+ "wechat_scan_task_unknown",
+ "This scan is no longer in progress: start a new one.",
+ );
+ }
+ if (result.status !== "completed" || result.bot === undefined) {
+ return c.json({ status: result.status } satisfies WeChatScanPollResponse);
+ }
+ const { botId, botToken, baseUrl, userId } = result.bot;
+ const saved = await saveScanResult(row.sessionId, "wechat", botId, {
+ botId,
+ botToken,
+ baseUrl,
+ userId,
+ });
+ return c.json({
+ status: "completed",
+ botId,
+ binding: CHANNEL_SPECS.wechat.toInfo(saved) as WeChatBindingInfo,
+ } satisfies WeChatScanPollResponse);
+ });
+
+ app.post("/:sessionId/messaging/wechat/scan/verify", async (c) => {
+ const row = resolveSession(c);
+ deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ const body = await readJson(c);
+ const taskId = requireString(body, "taskId", { minLen: 1, maxLen: 500 });
+ // The platform shows a short numeric code; the bound is generous rather than exact
+ // because the length is not documented and a rejected digit is the platform's answer to
+ // give, not this route's.
+ const verifyCode = requireString(body, "verifyCode", { minLen: 1, maxLen: 32 }).trim();
+ if (verifyCode === "") throw badRequest("verifyCode must not be blank.");
+ if (!deps.wechatScan.submitVerifyCode(row.sessionId, taskId, verifyCode)) {
+ throw new HttpError(
+ 404,
+ "wechat_scan_task_unknown",
+ "This scan is no longer in progress: start a new one.",
+ );
+ }
+ return c.body(null, 204);
+ });
+
+ app.post("/:sessionId/messaging/wechat/scan/cancel", async (c) => {
+ const row = resolveSession(c);
+ deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ const body = await readJson(c);
+ deps.wechatScan.cancel(
+ row.sessionId,
+ requireString(body, "taskId", { minLen: 1, maxLen: 500 }),
+ );
+ return c.body(null, 204);
+ });
+
+ /**
+ * Credential probe. The only test on this router that takes no draft values: nothing here
+ * is typed, so the stored binding is the only thing there is to probe.
+ */
+ app.post("/:sessionId/messaging/wechat/test", async (c) => {
+ const row = resolveSession(c);
+ const stored = deps.messagingRepo.find(row.sessionId, "wechat");
+ if (stored === null || wechatFieldsOf(stored).botToken === "") {
+ throw new HttpError(
+ 400,
+ "wechat_token_required",
+ "Bind by scanning a QR code first: there is no credential to test.",
+ );
+ }
+ const result = await deps.messaging.testCredentials("wechat", stored.config);
+ return c.json({
+ ok: result.ok,
+ ...(result.latencyMs !== undefined ? { latencyMs: result.latencyMs } : {}),
+ ...(result.error !== undefined ? { error: result.error } : {}),
+ } satisfies WeChatTestResponse);
+ });
+
return app;
}
diff --git a/packages/server/src/runtime/messaging/bridge.ts b/packages/server/src/runtime/messaging/bridge.ts
index 7fa5e71d..51b9a947 100644
--- a/packages/server/src/runtime/messaging/bridge.ts
+++ b/packages/server/src/runtime/messaging/bridge.ts
@@ -1,6 +1,6 @@
/**
* Messaging bridge: a Web server runtime component connecting Sessions to external chat
- * platforms through channel connectors (Feishu, Telegram and QQ today — see
+ * platforms through channel connectors (Feishu, Telegram, QQ and WeChat 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
diff --git a/packages/server/src/runtime/messaging/connector.ts b/packages/server/src/runtime/messaging/connector.ts
index ea1dc845..2eb4cd67 100644
--- a/packages/server/src/runtime/messaging/connector.ts
+++ b/packages/server/src/runtime/messaging/connector.ts
@@ -1,6 +1,6 @@
/**
* The messaging-channel connector seam: what the MessagingBridge needs from one chat
- * platform (Feishu, Telegram and QQ today; further channels implement the same interface
+ * platform (Feishu, Telegram, QQ and WeChat 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
@@ -13,7 +13,7 @@
*/
/** Known messaging channels (the DB stores the discriminator as text; unknown values are skipped defensively). */
-export type MessagingChannel = "feishu" | "telegram" | "qq";
+export type MessagingChannel = "feishu" | "telegram" | "qq" | "wechat";
/** One inbound image's bytes, once fetched, with the MIME type the bridge needs for its data URL. */
export interface MessagingInboundImageData {
diff --git a/packages/server/src/runtime/messaging/markdown.ts b/packages/server/src/runtime/messaging/markdown.ts
index 9d56eb2e..0eda2681 100644
--- a/packages/server/src/runtime/messaging/markdown.ts
+++ b/packages/server/src/runtime/messaging/markdown.ts
@@ -15,14 +15,16 @@
* sensitive, and a substitution pass mangles exactly the replies (code containing
* asterisks, nested emphasis, links with parentheses) that make the feature worth having.
*
- * The RENDER is deliberately not shared. Three channels accept three different subsets —
+ * The RENDER is deliberately not shared. Four channels accept four different subsets —
* Telegram has code and no headings, lists or tables; Feishu has all of them; QQ has
- * headings and lists but no code and no tables — over two different markups and three
- * different escaping rules. A printer parameterised over that would be a table of six
- * capability flags whose every branch belongs to exactly one channel, which is the
- * connector's own job under a name that hides it. So each channel renders this tree itself:
- * telegram-html.ts, feishu-card.ts and qq-markdown.ts, each beside the adapter that sends
- * its output. Nothing in this module knows any channel's markup.
+ * headings and lists but no code and no tables; WeChat reads Markdown itself, so its
+ * renderer subtracts what the client will not show rather than translating — over three
+ * different markups and four different escaping rules. A printer parameterised over that
+ * would be a table of capability flags whose every branch belongs to exactly one channel,
+ * which is the connector's own job under a name that hides it. So each channel renders this
+ * tree itself: telegram-html.ts, feishu-card.ts, qq-markdown.ts and wechat-markdown.ts, each
+ * beside the adapter that sends its output. Nothing in this module knows any channel's
+ * markup.
*/
import remarkGfm from "remark-gfm";
import remarkParse from "remark-parse";
diff --git a/packages/server/src/runtime/messaging/wechat-api.ts b/packages/server/src/runtime/messaging/wechat-api.ts
new file mode 100644
index 00000000..582869ec
--- /dev/null
+++ b/packages/server/src/runtime/messaging/wechat-api.ts
@@ -0,0 +1,832 @@
+/**
+ * The WeChat half of the WeChat connector: the wire protocol of the official claw bot
+ * channel, behind an injectable seam so tests substitute a fake and never open a socket
+ * (the shape qq-api.ts and telegram-api.ts share).
+ *
+ * ## What this protocol is, and why it is reimplemented here
+ *
+ * Tencent publishes the channel as an OpenClaw plugin
+ * (https://github.com/Tencent/openclaw-weixin, MIT) and there is an independent SDK derived
+ * from it (https://github.com/wong2/weixin-agent-sdk, MIT, npm `weixin-agent-sdk`). Both are
+ * readable, and both describe the SAME protocol: plain JSON over HTTPS, no proprietary
+ * binary, no obfuscated dist. Neither is taken as a dependency, and the reason is shape
+ * rather than licence: both own the process's message loop (`login()` then `start(agent)`),
+ * carry ONE account, render the login QR to a TTY with `qrcode-terminal`, and persist their
+ * state under `~/.openclaw`. This product needs many bindings side by side, each with its
+ * own stored config document, and a QR that reaches a browser. So the protocol is
+ * reimplemented against the same endpoints, the way qq-scan.ts reimplements Tencent's
+ * bind-task protocol rather than taking its npm package.
+ *
+ * ## Inbound is a long poll, which is why this channel is possible at all
+ *
+ * `getupdates` is held open by the server until a message arrives or the window closes, and
+ * the client passes back the opaque `get_updates_buf` cursor it was last given. There is no
+ * webhook and no public URL anywhere in the flow — the same property that made QQ's gateway
+ * usable and QQ's webhook mode not.
+ *
+ * ## Media rides a CDN, encrypted, and the encryption is not optional
+ *
+ * A picture or a file is never inline. Outbound: `getuploadurl` issues a pre-signed URL for
+ * bytes the caller has already AES-128-ECB encrypted under a key it generates, and the CDN
+ * answers with the `x-encrypted-param` handle that the message item then references.
+ * Inbound: the item carries a URL and the key, and the bytes are ciphertext until decrypted.
+ * ECB with a per-file random key is the platform's choice, not one made here — the framing
+ * is what it is, and the alternative to implementing it is not carrying media at all.
+ *
+ * ## `context_token`
+ *
+ * Every inbound message carries one, and it is echoed on every outbound send to the same
+ * user. It is a routing hint rather than an authorization anchor — the platform accepts a
+ * send without one, which is what a first send after a restart does — so it is threaded
+ * through where it is known and omitted where it is not, and never persisted: it is derived
+ * from traffic, and traffic is what re-derives it.
+ */
+import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
+import { MessagingMediaTooLargeError, collectUnderCap } from "./media.js";
+
+/** The platform's fixed entry host: the QR calls, and the default API base before a scan names one. */
+export const WECHAT_API_BASE = "https://ilinkai.weixin.qq.com";
+
+/**
+ * `iLink-App-Id`. Not a per-integration credential — it names the KIND of client, and every
+ * bot-channel client sends this same literal (it is the `ilink_appid` field of Tencent's own
+ * plugin manifest). There is nothing to register and nothing to keep secret.
+ */
+const ILINK_APP_ID = "bot";
+
+/**
+ * `iLink-App-ClientVersion`: `major<<16 | minor<<8 | patch` in a uint32, which is the
+ * encoding the header documents. Pinned rather than derived from the product version — this
+ * names the PROTOCOL client, and it moves when the protocol handling moves, not when the
+ * product ships a release.
+ */
+const ILINK_CLIENT_VERSION = (1 << 16) | (0 << 8) | 0;
+
+/**
+ * `base_info.bot_agent`: the self-declared identity, the protocol's own analogue of a
+ * `User-Agent`. Observability only — it authenticates and routes nothing — and the grammar
+ * is `Name/Version`, so a bare name would be dropped by the server's sanitizer.
+ */
+const BOT_AGENT = "PenguinHarness/1.0";
+
+/** Overall deadline for the short calls (send, upload handle, credential probe). */
+const CALL_TIMEOUT_MS = 15_000;
+
+/**
+ * How long ONE `getupdates` may be held. The protocol's own suggestion is 35s; this is
+ * shorter on purpose, because the poll loop cannot see a closed connection while it is
+ * parked in a request — a shorter window bounds how long a disable waits for its poll to
+ * come back. The abort signal is what actually ends it promptly; this is the backstop for
+ * a connection that is hung rather than closed.
+ */
+export const LONG_POLL_TIMEOUT_MS = 30_000;
+
+/**
+ * Deadline for a media transfer in either direction. Far longer than a method call: these
+ * move megabytes over whatever link the server has, and a 15s ceiling would fail a picture
+ * that was on its way perfectly well (the same number telegram-api.ts uses).
+ */
+const TRANSFER_TIMEOUT_MS = 60_000;
+
+/**
+ * How long the connection's FIRST poll may take. It is a drain, not a wait: it asks for
+ * whatever the platform is already holding, and anything that has not arrived by here is a
+ * live message the loop is about to read properly rather than backlog to discard. Parking it
+ * for the full long-poll window would drop the first message a user sends after enabling.
+ */
+export const DRAIN_TIMEOUT_MS = 5_000;
+
+/** The bot-channel `bot_type` the QR calls are made under. */
+export const WECHAT_BOT_TYPE = "3";
+
+// ---------------------------------------------------------------------------
+// The wire's own vocabulary
+// ---------------------------------------------------------------------------
+
+/** `MessageItem.type` — the item kinds this channel carries. */
+const ITEM_TEXT = 1;
+const ITEM_IMAGE = 2;
+const ITEM_VOICE = 3;
+const ITEM_FILE = 4;
+const ITEM_VIDEO = 5;
+
+/** `WeixinMessage.message_type`: a message this bot is SENDING. */
+const MESSAGE_TYPE_BOT = 2;
+
+/** `WeixinMessage.message_state`: the message is complete (nothing is streamed from here). */
+const MESSAGE_STATE_FINISH = 2;
+
+/** `GetUploadUrlReq.media_type`. VOICE (4) exists on the wire and is never sent from here. */
+const UPLOAD_MEDIA_IMAGE = 1;
+const UPLOAD_MEDIA_FILE = 3;
+
+/** AES-128 key length — what both the CDN framing and `getuploadurl`'s `aeskey` expect. */
+const AES_KEY_BYTES = 16;
+
+/** One file name for a video, which the wire never names (see the connector's inbound doc). */
+export const WECHAT_VIDEO_FILE_NAME = "video.mp4";
+
+// ---------------------------------------------------------------------------
+// The seam
+// ---------------------------------------------------------------------------
+
+export interface WeChatCredentials {
+ /** `ilink_bot_id` — the channel-scoped account identity. Never secret. */
+ botId: string;
+ /** The bot token a completed scan issued. This is the credential. */
+ botToken: string;
+ /**
+ * The API host this bot was assigned. A scan may hand back an IDC-specific one, and a bot
+ * polled against the wrong host reads as an authentication failure, so it is stored per
+ * binding rather than assumed.
+ */
+ baseUrl: string;
+ /**
+ * `ilink_user_id` of the person whose scan created the binding. It is what the credential
+ * probe names — `getconfig` is per-user — and it is not otherwise used: an inbound message
+ * carries its own sender.
+ */
+ userId: string;
+}
+
+/**
+ * One media object on the wire: where the bytes are, and the key that opens them.
+ *
+ * A handle, deliberately — nothing here has fetched anything. The connector turns it into
+ * the seam's lazy `fetch`, so a redelivered message costs no transfer at all.
+ */
+export interface WeChatMediaRef {
+ /**
+ * The ready-made download URL the server returns. Required: the alternative is rebuilding
+ * it from a CDN host this protocol does not document, and a guessed host that resolves
+ * would be worse than one that does not.
+ */
+ url: string;
+ /**
+ * The AES-128 key, in the wire's own base64. Absent for the one case the platform sends in
+ * the clear (an image with no key at all), which then needs no decryption.
+ */
+ aesKey?: string;
+}
+
+/** A non-image attachment on an inbound message. */
+export interface WeChatInboundFile {
+ /** The sender's own name for it, or a plain fallback where the wire carries none. */
+ fileName: string;
+ media: WeChatMediaRef;
+}
+
+/**
+ * One inbound message, reduced to what the connector consumes. Voice, video and quoted
+ * messages have already been folded into these three fields — see `normalizeMessage`.
+ */
+export interface WeChatInboundEvent {
+ /** `from_user_id`: the sender, the chat, and the send target, which are one id on this channel. */
+ userId: string;
+ /** `message_id`, as text. The dedupe key and the reply anchor. */
+ messageId: string;
+ /** The message's text, or `""` when it carries none. */
+ text: string;
+ /** Echoed on sends to this user while it is known (see the module doc). */
+ contextToken?: string;
+ images: WeChatMediaRef[];
+ files: WeChatInboundFile[];
+}
+
+/** One outbound attachment: the bytes, and the name the chat should show. */
+export interface WeChatOutboundFile {
+ fileName: string;
+ data: Buffer;
+}
+
+export interface WeChatSendArgs {
+ /** `to_user_id` — the chat, which on this channel is the person. */
+ userId: string;
+ text: string;
+ contextToken?: string;
+}
+
+/** What one `getupdates` returned: the messages, and the cursor for the next call. */
+export interface WeChatUpdates {
+ messages: WeChatInboundEvent[];
+ /** Opaque `get_updates_buf`; pass it back verbatim. */
+ cursor: string;
+ /**
+ * The window closed with nothing rather than the platform answering.
+ *
+ * Both come back as an empty list with the cursor unchanged, and for an ordinary poll they
+ * are the same thing. The drain is where they differ: it must not be spent on a window that
+ * closed without the platform saying where it stands, or the cursor stays at the beginning
+ * and the next poll relays a whole backlog as live traffic.
+ */
+ timedOut: boolean;
+}
+
+export interface WeChatBotClient {
+ /**
+ * Credential probe: resolves when the token AUTHENTICATES, and throws when it does not.
+ *
+ * What it deliberately does not prove is that the bot can deliver anything. No call on this
+ * platform can prove both: every authenticated endpoint shares one auth layer and then does
+ * something with a side condition a freshly-scanned binding cannot satisfy — `getconfig`
+ * wants a live conversation to mint a typing ticket for, `getuploadurl` wants a peer and a
+ * file, `sendtyping` wants a ticket, and `getupdates` is a long poll that would park for its
+ * whole window. So the probe reads the layer that has no side conditions and reports only
+ * that, which is the honest answer rather than a green light for something it did not test.
+ */
+ checkCredentials(): Promise<void>;
+ /**
+ * One poll. `signal` ends it at once, which is what a disable needs.
+ *
+ * A window that closes with nothing to report resolves EMPTY rather than throwing: on a long
+ * poll that is the ordinary quiet case, and treating it as a failure would flap the
+ * connection into `error` every time a conversation went quiet.
+ *
+ * `drain: true` asks for a short deadline instead of the long-poll window — see
+ * DRAIN_TIMEOUT_MS.
+ */
+ getUpdates(args: {
+ cursor: string;
+ signal: AbortSignal;
+ drain?: boolean;
+ }): Promise<WeChatUpdates>;
+ sendText(args: WeChatSendArgs): Promise<void>;
+ /** Uploads the bytes to the CDN, then sends the item that references them. */
+ sendImage(args: WeChatSendArgs & { file: WeChatOutboundFile }): Promise<void>;
+ sendFile(args: WeChatSendArgs & { file: WeChatOutboundFile }): Promise<void>;
+ /**
+ * Downloads and decrypts one media handle, refusing at the byte that crosses `maxBytes`.
+ * `what` names the transfer in a refusal and must never carry a URL: a CDN URL embeds the
+ * signed parameter that authorizes the read.
+ */
+ fetchMedia(ref: WeChatMediaRef, maxBytes: number, what: string): Promise<Buffer>;
+}
+
+/** Factory the connector is built over: the production adapter, or a test fake. */
+export interface WeChatTransport {
+ createClient(creds: WeChatCredentials): WeChatBotClient;
+}
+
+/**
+ * The code the platform answers with when the bot token is stale or revoked. It arrives with
+ * an HTTP 200 and a non-zero envelope, so it is the one business-level code that has to be
+ * read as an authentication failure rather than as one of the call behind it.
+ */
+export const WECHAT_STALE_TOKEN_CODE = -14;
+
+/**
+ * A call the platform answered with a failure of its own, as opposed to one that never
+ * arrived. `ret` is the protocol's numeric code where it returned one.
+ */
+export class WeChatApiError extends Error {
+ /**
+ * The request was ACCEPTED — it authenticated, and the failure came from the call behind
+ * the credential rather than from the credential.
+ *
+ * This distinction is the whole of the credential probe: every authenticated endpoint on
+ * this platform shares one auth layer and then does something that needs state a
+ * freshly-bound bot does not have, so the only thing a probe can honestly read is which of
+ * the two layers refused it (see checkCredentials).
+ */
+ readonly authenticated: boolean;
+ /**
+ * The request was given up on at a deadline rather than answered or refused. On a long poll
+ * that is the ordinary quiet case and not a failure at all, which is what `getUpdates` reads
+ * it for; nothing else here distinguishes it from a network fault.
+ */
+ readonly timedOut: boolean;
+
+ constructor(
+ readonly ret: number | undefined,
+ message: string,
+ flags: { authenticated?: boolean; timedOut?: boolean } = {},
+ ) {
+ super(message);
+ this.name = "WeChatApiError";
+ this.authenticated = flags.authenticated ?? false;
+ this.timedOut = flags.timedOut ?? false;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Production adapter over fetch
+// ---------------------------------------------------------------------------
+
+/** Whether a fetch rejection is a deadline or a cancellation rather than a transport fault. */
+function isAbortLike(err: unknown): boolean {
+ return err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError");
+}
+
+/** Readable failure text out of fetch's throw shapes. Never echoes a URL (see fetchMedia). */
+export function wechatFetchErrorText(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);
+}
+
+/**
+ * `X-WECHAT-UIN`: a random uint32, rendered as its decimal digits and then base64'd. It
+ * identifies nothing — the protocol wants the header present and the value fresh per
+ * request, which is exactly what a random one is.
+ */
+function randomUin(): string {
+ return Buffer.from(String(randomBytes(4).readUInt32BE(0)), "utf8").toString("base64");
+}
+
+function headersFor(token: string): Record<string, string> {
+ return {
+ "content-type": "application/json",
+ AuthorizationType: "ilink_bot_token",
+ Authorization: `Bearer ${token}`,
+ "X-WECHAT-UIN": randomUin(),
+ "iLink-App-Id": ILINK_APP_ID,
+ "iLink-App-ClientVersion": String(ILINK_CLIENT_VERSION),
+ };
+}
+
+/** The `base_info` every request carries. */
+function baseInfo(): Record<string, unknown> {
+ return { channel_version: "1.0.0", bot_agent: BOT_AGENT };
+}
+
+/** Joins an endpoint onto a base whose trailing slash the caller may or may not have kept. */
+function endpointUrl(baseUrl: string, path: string): string {
+ return `${baseUrl.replace(/\/+$/, "")}/${path}`;
+}
+
+/** The response envelope the JSON calls share; `ret` is 0 or absent on success. */
+interface WeChatEnvelope {
+ ret?: number;
+ errcode?: number;
+ errmsg?: string;
+}
+
+/** Raises the platform's own failure, or returns the parsed body. */
+function checkEnvelope(label: string, status: number, raw: string): Record<string, unknown> {
+ let body: Record<string, unknown>;
+ try {
+ body = JSON.parse(raw) as Record<string, unknown>;
+ } catch {
+ throw new WeChatApiError(undefined, `${label} failed: HTTP ${status} (unparseable response)`);
+ }
+ const env = body as WeChatEnvelope;
+ // `ret` and `errcode` are two spellings of the same thing across these endpoints; either
+ // being non-zero is a failure, and neither being present is a success.
+ const code = env.ret !== undefined && env.ret !== 0 ? env.ret : env.errcode;
+ if (code !== undefined && code !== 0) {
+ // The request reached the platform and got past its credential check — a stale token
+ // being the one code that says otherwise.
+ throw new WeChatApiError(code, `${label} failed: ${env.errmsg ?? `code ${code}`}`, {
+ authenticated: code !== WECHAT_STALE_TOKEN_CODE,
+ });
+ }
+ return body;
+}
+
+// ---------------------------------------------------------------------------
+// AES-128-ECB, which is the CDN's framing
+// ---------------------------------------------------------------------------
+
+/** PKCS#7 is node's default for this cipher, so the padded length is always a full block longer. */
+function paddedSize(plaintextSize: number): number {
+ return Math.ceil((plaintextSize + 1) / 16) * 16;
+}
+
+function encryptEcb(plaintext: Buffer, key: Buffer): Buffer {
+ const cipher = createCipheriv("aes-128-ecb", key, null);
+ return Buffer.concat([cipher.update(plaintext), cipher.final()]);
+}
+
+function decryptEcb(ciphertext: Buffer, key: Buffer): Buffer {
+ const decipher = createDecipheriv("aes-128-ecb", key, null);
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
+}
+
+/**
+ * Reads the wire's `aes_key` back to 16 raw bytes.
+ *
+ * Two encodings appear, and which one arrives depends on the item kind rather than on
+ * anything a reader can see: an image's key is base64 of the raw bytes, while a file's and a
+ * video's is base64 of the key's 32 HEX CHARACTERS. Both are accepted by length, because a
+ * 32-byte decode that is entirely hex digits cannot be a 16-byte key under any reading.
+ */
+export function parseWeChatAesKey(aesKey: string): Buffer {
+ const decoded = Buffer.from(aesKey, "base64");
+ if (decoded.length === AES_KEY_BYTES) return decoded;
+ const ascii = decoded.toString("ascii");
+ if (decoded.length === 32 && /^[0-9a-fA-F]{32}$/.test(ascii)) return Buffer.from(ascii, "hex");
+ throw new Error("wechat media key is neither 16 raw bytes nor 32 hex characters");
+}
+
+// ---------------------------------------------------------------------------
+// Inbound normalization
+// ---------------------------------------------------------------------------
+
+/** One `MessageItem`, in the wire's own field names (only the parts read here). */
+interface WireItem {
+ type?: number;
+ text_item?: { text?: string };
+ image_item?: { media?: WireMedia; aeskey?: string };
+ voice_item?: { media?: WireMedia; text?: string };
+ file_item?: { media?: WireMedia; file_name?: string };
+ video_item?: { media?: WireMedia };
+ ref_msg?: { title?: string; message_item?: WireItem };
+}
+
+interface WireMedia {
+ full_url?: string;
+ aes_key?: string;
+}
+
+interface WireMessage {
+ message_id?: number | string;
+ from_user_id?: string;
+ message_type?: number;
+ context_token?: string;
+ item_list?: WireItem[];
+}
+
+/** A media handle, or null when the item carries no usable URL. */
+function mediaRefOf(media: WireMedia | undefined, aesKeyOverride?: string): WeChatMediaRef | null {
+ const url = media?.full_url;
+ if (typeof url !== "string" || url === "") return null;
+ // `image_item.aeskey` is hex and takes precedence over `media.aes_key` where both are sent;
+ // it is the one the platform's own client prefers for images.
+ const aesKey =
+ typeof aesKeyOverride === "string" && aesKeyOverride !== ""
+ ? Buffer.from(aesKeyOverride, "hex").toString("base64")
+ : media?.aes_key;
+ return { url, ...(typeof aesKey === "string" && aesKey !== "" ? { aesKey } : {}) };
+}
+
+/**
+ * The text a message contributes.
+ *
+ * A VOICE item's `text` is the platform's OWN transcription of the recording, so a voice
+ * message that has one is a text message and is carried as one. There is no audio on the
+ * connector seam — an inbound recording has nowhere to go — and dropping a transcription
+ * that already exists would answer a spoken question with the not-supported notice.
+ *
+ * A quoted message contributes its summary in front of the reply, because the reply usually
+ * does not repeat what it is answering and the model would otherwise read a bare "yes".
+ */
+function textOf(items: readonly WireItem[]): string {
+ const parts: string[] = [];
+ for (const item of items) {
+ if (item.type === ITEM_TEXT && typeof item.text_item?.text === "string") {
+ const quoted = item.ref_msg;
+ const quotedText =
+ quoted === undefined
+ ? ""
+ : [quoted.title, quoted.message_item ? textOf([quoted.message_item]) : ""]
+ .filter((part): part is string => typeof part === "string" && part !== "")
+ .join(" | ");
+ parts.push(
+ quotedText === "" ? item.text_item.text : `[quote: ${quotedText}]\n${item.text_item.text}`,
+ );
+ continue;
+ }
+ if (item.type === ITEM_VOICE && typeof item.voice_item?.text === "string") {
+ parts.push(item.voice_item.text);
+ }
+ }
+ return parts.join("\n").trim();
+}
+
+/**
+ * One wire message as the connector's event, or null for anything it must not act on.
+ *
+ * The bot's OWN messages come back on this stream — `message_type` 2 is what this client
+ * sent — and relaying them would answer every reply with another reply.
+ */
+export function normalizeWeChatMessage(msg: WireMessage): WeChatInboundEvent | null {
+ const userId = msg.from_user_id;
+ if (typeof userId !== "string" || userId === "") return null;
+ if (msg.message_type === MESSAGE_TYPE_BOT) return null;
+ const items = Array.isArray(msg.item_list) ? msg.item_list : [];
+ const images: WeChatMediaRef[] = [];
+ const files: WeChatInboundFile[] = [];
+ for (const item of items) {
+ if (item.type === ITEM_IMAGE) {
+ const ref = mediaRefOf(item.image_item?.media, item.image_item?.aeskey);
+ if (ref !== null) images.push(ref);
+ } else if (item.type === ITEM_FILE) {
+ const ref = mediaRefOf(item.file_item?.media);
+ const name = item.file_item?.file_name;
+ // No name is a plain fallback rather than an invented extension: the name is the whole
+ // of what tells the model what the bytes are (see connector.ts MessagingInboundFile).
+ if (ref !== null)
+ files.push({ fileName: name !== undefined && name !== "" ? name : "file", media: ref });
+ } else if (item.type === ITEM_VIDEO) {
+ const ref = mediaRefOf(item.video_item?.media);
+ // `.mp4` is not a guess: the platform transcodes every video item to it, and its own
+ // client asserts the type unconditionally. The wire carries no name to prefer over it.
+ if (ref !== null) files.push({ fileName: WECHAT_VIDEO_FILE_NAME, media: ref });
+ }
+ }
+ const messageId = msg.message_id;
+ return {
+ userId,
+ messageId: messageId === undefined ? "" : String(messageId),
+ text: textOf(items),
+ ...(typeof msg.context_token === "string" && msg.context_token !== ""
+ ? { contextToken: msg.context_token }
+ : {}),
+ images,
+ files,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// The adapter
+// ---------------------------------------------------------------------------
+
+export function createWeChatTransport(): WeChatTransport {
+ return {
+ createClient(creds: WeChatCredentials): WeChatBotClient {
+ const post = async (
+ path: string,
+ payload: Record<string, unknown>,
+ opts: { timeoutMs: number; signal?: AbortSignal; label: string },
+ ): Promise<Record<string, unknown>> => {
+ const url = endpointUrl(creds.baseUrl, path);
+ let res: Response;
+ try {
+ res = await fetch(url, {
+ method: "POST",
+ headers: headersFor(creds.botToken),
+ body: JSON.stringify({ ...payload, base_info: baseInfo() }),
+ signal: opts.signal ?? AbortSignal.timeout(opts.timeoutMs),
+ });
+ } catch (err) {
+ throw new WeChatApiError(
+ undefined,
+ `${opts.label} failed: ${wechatFetchErrorText(err)}`,
+ {
+ timedOut: isAbortLike(err),
+ },
+ );
+ }
+ const raw = await res.text().catch(() => "");
+ if (!res.ok) {
+ // The body is the platform's own diagnosis and is the only thing that distinguishes
+ // a revoked token from a wrong host; it carries no credential of ours. Every status
+ // here leaves `authenticated` false: a 401/403 IS the credential being refused, and
+ // for anything else the request never got far enough to say the credential is good.
+ throw new WeChatApiError(
+ undefined,
+ `${opts.label} failed: HTTP ${res.status}${raw === "" ? "" : ` ${raw.slice(0, 300)}`}`,
+ );
+ }
+ return checkEnvelope(opts.label, res.status, raw);
+ };
+
+ /**
+ * One message item on its way out. Every send is its own request with exactly one item:
+ * the platform pairs a caption with its media as two consecutive messages rather than
+ * one message with two items, and a two-item list is not a shape it accepts.
+ */
+ const sendItem = async (
+ args: WeChatSendArgs,
+ item: Record<string, unknown>,
+ label: string,
+ ): Promise<void> => {
+ await post(
+ "ilink/bot/sendmessage",
+ {
+ msg: {
+ from_user_id: "",
+ to_user_id: args.userId,
+ client_id: randomBytes(16).toString("hex"),
+ message_type: MESSAGE_TYPE_BOT,
+ message_state: MESSAGE_STATE_FINISH,
+ item_list: [item],
+ ...(args.contextToken !== undefined ? { context_token: args.contextToken } : {}),
+ },
+ },
+ { timeoutMs: CALL_TIMEOUT_MS, label },
+ );
+ };
+
+ /**
+ * The upload half of an outbound attachment: a fresh key, a pre-signed URL for the
+ * ciphertext, and the CDN's handle for the message item to reference.
+ *
+ * `no_need_thumb` is set because nothing here has a thumbnail to make. The platform
+ * requires thumbnail sizes for IMAGE and VIDEO only when one is being uploaded, and a
+ * generated thumbnail would mean decoding every picture the Agent draws.
+ */
+ const upload = async (
+ userId: string,
+ file: WeChatOutboundFile,
+ mediaType: number,
+ label: string,
+ ): Promise<{ param: string; aesKey: Buffer; rawSize: number; cipherSize: number }> => {
+ const aesKey = randomBytes(AES_KEY_BYTES);
+ const rawSize = file.data.length;
+ const cipherSize = paddedSize(rawSize);
+ const filekey = randomBytes(AES_KEY_BYTES).toString("hex");
+ const handle = await post(
+ "ilink/bot/getuploadurl",
+ {
+ filekey,
+ media_type: mediaType,
+ to_user_id: userId,
+ rawsize: rawSize,
+ rawfilemd5: createHash("md5").update(file.data).digest("hex"),
+ filesize: cipherSize,
+ no_need_thumb: true,
+ aeskey: aesKey.toString("hex"),
+ },
+ { timeoutMs: CALL_TIMEOUT_MS, label: `${label} upload handle` },
+ );
+ const uploadUrl = handle.upload_full_url;
+ if (typeof uploadUrl !== "string" || uploadUrl.trim() === "") {
+ // The alternative is assembling a URL from a CDN host this protocol never
+ // documents. A guessed host that happened to resolve would be worse than none.
+ throw new WeChatApiError(undefined, `${label} failed: the upload URL was not returned`);
+ }
+ let res: Response;
+ try {
+ res = await fetch(uploadUrl.trim(), {
+ method: "POST",
+ headers: { "content-type": "application/octet-stream" },
+ body: new Uint8Array(encryptEcb(file.data, aesKey)),
+ signal: AbortSignal.timeout(TRANSFER_TIMEOUT_MS),
+ });
+ } catch (err) {
+ throw new WeChatApiError(undefined, `${label} failed: ${wechatFetchErrorText(err)}`);
+ }
+ if (!res.ok) {
+ const detail = res.headers.get("x-error-message") ?? `HTTP ${res.status}`;
+ throw new WeChatApiError(undefined, `${label} failed: ${detail}`);
+ }
+ const param = res.headers.get("x-encrypted-param");
+ if (param === null || param === "") {
+ throw new WeChatApiError(
+ undefined,
+ `${label} failed: the CDN returned no download handle`,
+ );
+ }
+ return { param, aesKey, rawSize, cipherSize };
+ };
+
+ return {
+ async checkCredentials(): Promise<void> {
+ try {
+ // The cheapest authenticated call that reads rather than writes, and the only one
+ // that consumes nothing: `getupdates` would park for its window, and a probe that
+ // advanced the cursor the poll loop is about to read would eat a user's message.
+ await post(
+ "ilink/bot/getconfig",
+ { ilink_user_id: creds.userId },
+ { timeoutMs: CALL_TIMEOUT_MS, label: "wechat credential check" },
+ );
+ } catch (err) {
+ // The call behind the credential failed, which says nothing about the credential:
+ // `getconfig` mints a typing ticket for a CONVERSATION, and a bot nobody has
+ // messaged yet has none — so a binding whose sends work perfectly answers
+ // "GetTypingTicket rpc failed" here. Reporting that as a bad credential sends the
+ // user to re-scan a token that was never the problem.
+ if (err instanceof WeChatApiError && err.authenticated) return;
+ throw err;
+ }
+ },
+
+ async getUpdates({ cursor, signal, drain = false }): Promise<WeChatUpdates> {
+ // Two deadlines, combined: the caller's (a disable, which must end the poll now)
+ // and this call's own window. Whichever fires first ends the request.
+ const windowMs = drain ? DRAIN_TIMEOUT_MS : LONG_POLL_TIMEOUT_MS;
+ let body: Record<string, unknown>;
+ try {
+ body = await post(
+ "ilink/bot/getupdates",
+ { get_updates_buf: cursor },
+ {
+ timeoutMs: windowMs,
+ signal: AbortSignal.any([signal, AbortSignal.timeout(windowMs)]),
+ label: "wechat getUpdates",
+ },
+ );
+ } catch (err) {
+ // A close is a close and must reach the loop; this window closing is not a
+ // failure at all. A long poll that has nothing to say holds the request until it
+ // expires, so treating that as an outage would put the connection into `error`
+ // every quiet minute — and the cursor is unchanged, so the next call simply asks
+ // again from where this one started.
+ if (signal.aborted) throw err;
+ if (err instanceof WeChatApiError && err.timedOut) {
+ return { messages: [], cursor, timedOut: true };
+ }
+ throw err;
+ }
+ const raw = Array.isArray(body.msgs) ? (body.msgs as WireMessage[]) : [];
+ const messages: WeChatInboundEvent[] = [];
+ for (const msg of raw) {
+ const evt = normalizeWeChatMessage(msg);
+ if (evt !== null) messages.push(evt);
+ }
+ // A response that carried no cursor leaves the old one in place: sending `""` back
+ // means "start over", which would replay everything this poll just consumed.
+ const next = body.get_updates_buf;
+ return {
+ messages,
+ cursor: typeof next === "string" && next !== "" ? next : cursor,
+ timedOut: false,
+ };
+ },
+
+ sendText(args: WeChatSendArgs): Promise<void> {
+ return sendItem(args, { type: ITEM_TEXT, text_item: { text: args.text } }, "wechat send");
+ },
+
+ async sendImage(args): Promise<void> {
+ const { param, aesKey, cipherSize } = await upload(
+ args.userId,
+ args.file,
+ UPLOAD_MEDIA_IMAGE,
+ "wechat image send",
+ );
+ if (args.text !== "") await this.sendText(args);
+ await sendItem(
+ args,
+ {
+ type: ITEM_IMAGE,
+ image_item: {
+ media: {
+ encrypt_query_param: param,
+ aes_key: aesKey.toString("base64"),
+ encrypt_type: 1,
+ },
+ mid_size: cipherSize,
+ },
+ },
+ "wechat image send",
+ );
+ },
+
+ async sendFile(args): Promise<void> {
+ const { param, aesKey, rawSize } = await upload(
+ args.userId,
+ args.file,
+ UPLOAD_MEDIA_FILE,
+ "wechat file send",
+ );
+ if (args.text !== "") await this.sendText(args);
+ await sendItem(
+ args,
+ {
+ type: ITEM_FILE,
+ file_item: {
+ media: {
+ encrypt_query_param: param,
+ aes_key: aesKey.toString("base64"),
+ encrypt_type: 1,
+ },
+ file_name: args.file.fileName,
+ // Plaintext length: the receiving client shows it, and the ciphertext is
+ // one padding block longer than what the user actually gets.
+ len: String(rawSize),
+ },
+ },
+ "wechat file send",
+ );
+ },
+
+ async fetchMedia(ref: WeChatMediaRef, maxBytes: number, what: string): Promise<Buffer> {
+ let res: Response;
+ try {
+ res = await fetch(ref.url, { signal: AbortSignal.timeout(TRANSFER_TIMEOUT_MS) });
+ } catch (err) {
+ // The URL never reaches this message: it carries the signed parameter that
+ // authorizes the read.
+ throw new Error(`${what} could not be downloaded: ${wechatFetchErrorText(err)}`);
+ }
+ if (!res.ok) throw new Error(`${what} could not be downloaded: HTTP ${res.status}`);
+ if (res.body === null) throw new Error(`${what} could not be downloaded: empty response`);
+ // The cap is applied to the CIPHERTEXT, which is within one 16-byte block of the
+ // plaintext — so it still refuses at the byte that crosses, rather than buffering
+ // a whole oversized transfer and measuring it afterwards.
+ const bytes = await collectUnderCap(
+ res.body as AsyncIterable<Uint8Array>,
+ maxBytes,
+ what,
+ );
+ if (ref.aesKey === undefined) return bytes;
+ try {
+ return decryptEcb(bytes, parseWeChatAesKey(ref.aesKey));
+ } catch (err) {
+ if (err instanceof MessagingMediaTooLargeError) throw err;
+ // The cause is a crypto failure over a key the chat has no control of; what the
+ // user can act on is that the transfer arrived and could not be opened.
+ throw new Error(`${what} arrived but could not be decrypted`);
+ }
+ },
+ };
+ },
+ };
+}
diff --git a/packages/server/src/runtime/messaging/wechat-connector.ts b/packages/server/src/runtime/messaging/wechat-connector.ts
new file mode 100644
index 00000000..f70a485f
--- /dev/null
+++ b/packages/server/src/runtime/messaging/wechat-connector.ts
@@ -0,0 +1,412 @@
+/**
+ * WeChat messaging connector — the fourth implementation of the MessagingChannelConnector
+ * seam, over the official claw bot channel. It owns everything WeChat-specific: the config
+ * document a scan produces, the transport behind it (injectable for tests — see
+ * wechat-api.ts), the long-poll loop that stands in for an event stream, and the context
+ * token that threads an outbound send back onto the conversation it answers.
+ *
+ * ## Inbound is a poll, and there is no webhook anywhere
+ *
+ * The platform holds `getupdates` open until a message arrives, and the client passes back
+ * the opaque cursor it was last given. Nothing in the flow wants a publicly reachable URL —
+ * the property that made Telegram's `getUpdates` and QQ's gateway usable here, and QQ's
+ * webhook mode not. The loop's lifecycle mirrors telegram-connector's: failures back off and
+ * report once per outage, and a recovery fires `onReady` again so the bridge's status tracks
+ * the outage.
+ *
+ * A window that closes with nothing to report is the ORDINARY case on a long poll, not a
+ * failure — the transport resolves it as an empty answer on an unchanged cursor, and a loop
+ * that treated it as an outage would flap the connection into `error` every quiet minute.
+ *
+ * ## Readiness is proven by the credential probe, never by a poll
+ *
+ * A poll is not an event that arrives: it is a request held open until one does. So a
+ * connection reported ready only when a poll came back would sit at `connecting` for the
+ * whole window on an idle bot — usable the entire time, and saying so nowhere, which is
+ * exactly the "works but reports nothing" failure the binding panel exists to kill.
+ *
+ * Each cycle therefore opens with `checkCredentials`, which answers at once and proves what
+ * `connected` means here: the host resolves, the transport works, and the stored token
+ * authenticates. Telegram takes the opposite choice for a reason that does not apply here —
+ * its one-poller-per-token conflict is visible only on `getUpdates`, so `getMe` cannot prove
+ * its connection. This platform has no such rule, and a second connection on one bot is
+ * already refused a binding away (409 `account_enabled_elsewhere`).
+ *
+ * ## The first poll is a DRAIN, and asks for a short deadline
+ *
+ * An empty cursor means "start from the beginning", so the first poll of a connection can
+ * return everything sent while nothing was connected. Its messages are dropped and only its
+ * cursor is kept — the same choice telegram-connector makes with `offset: -1`, for the same
+ * reason: a binding switched on after a week dark must not replay that week as a task flood.
+ * A blip is not affected, because a reconnect keeps the cursor it already had.
+ *
+ * The short deadline is what keeps that from eating a live message. A drain parked for the
+ * long-poll window returns not the backlog but the first thing a user sends AFTER enabling —
+ * and then discards it as backlog. Asking only for what the platform is already holding makes
+ * "before this connection" and "after it" the two different things they are meant to be.
+ *
+ * ## Direct chats only, because that is the whole channel
+ *
+ * This channel carries one-to-one conversations with the bot. A `group_id` exists in the
+ * protocol's message shape and the platform never populates it for a bot of this kind, so
+ * every inbound message is `direct` and `replyText` has nothing to thread onto — there is no
+ * quote relation to honour, so it resolves to the same send `sendText` does. The bridge's
+ * threading choice is invisible here rather than wrong.
+ *
+ * ## Media
+ *
+ * Text, images and files travel in BOTH directions, and nothing outbound is refused — the
+ * widest of the four channels here, where QQ refuses outbound media outright and the other
+ * two carry it at a permission's mercy.
+ *
+ * Two inbound kinds are folded rather than carried as themselves. A VOICE message is relayed
+ * as the platform's OWN transcription of it: there is no audio on this seam and nothing
+ * downstream would transcribe a recording, while WeChat has already done it — so the usual
+ * spoken message is answered rather than refused. A VIDEO arrives as a file. A recording the
+ * platform could not transcribe reaches the bridge carrying nothing at all, which is answered
+ * with its channel-neutral not-supported notice, the same way QQ's non-text messages are:
+ * inventing a channel-specific refusal for it would say no more than the shared one already
+ * does.
+ *
+ * ## The context token
+ *
+ * Every inbound message carries one, and echoing it on a send is what puts the reply in the
+ * right conversation. It is held per (bot, user) in memory only: it is derived from traffic,
+ * and the platform accepts a send without one, so persisting it would add a place for a
+ * conversation handle to sit at rest in exchange for nothing a fresh inbound message does
+ * not fix. A send before this connection has seen any message from that user goes without —
+ * which is exactly what "send test message" does after a restart.
+ */
+import { sniffImageMime } from "./media.js";
+import type {
+ MessagingChannelConnector,
+ MessagingClient,
+ MessagingConnection,
+ MessagingConnectorHandlers,
+ MessagingInboundFile,
+ MessagingInboundImage,
+ MessagingOutboundFile,
+ MessagingSendOptions,
+} from "./connector.js";
+import { wechatMarkdownOf } from "./wechat-markdown.js";
+import type {
+ WeChatBotClient,
+ WeChatCredentials,
+ WeChatInboundEvent,
+ WeChatTransport,
+} from "./wechat-api.js";
+import { WECHAT_API_BASE } from "./wechat-api.js";
+
+/** The WeChat binding's stored config document (`messaging_bindings.config_json`). */
+export interface WeChatBindingConfig extends Record<string, unknown> {
+ /** `ilink_bot_id` — the account identity. Never secret. */
+ botId: string;
+ /** The bot token the scan issued. The credential. */
+ botToken: string;
+ /** The API host this bot was assigned (see WeChatCredentials.baseUrl). */
+ baseUrl: string;
+ /** `ilink_user_id` of the person who scanned; what the credential probe names. */
+ userId: string;
+}
+
+/**
+ * How many drains a connection asks for before it proceeds regardless.
+ *
+ * A drain that closed on its own deadline said nothing about where the platform stands, so
+ * spending it there is what lets a whole backlog through later (see the poll loop). But an idle
+ * bot's long poll may park until the deadline every time, so the retry has to be bounded: the
+ * window in which an arriving message is read as backlog and dropped is already one drain long,
+ * and this widens it by one more rather than leaving it open.
+ */
+const DRAIN_ATTEMPTS = 2;
+
+/**
+ * How long the poll loop waits after a failure, doubling to a ceiling.
+ *
+ * The first step is short because the common failure is a single request lost to a network
+ * blip, and the ceiling is a minute because the uncommon one is a revoked token, which no
+ * amount of polling fixes and which should not be asked about every second until a person
+ * notices.
+ */
+export function wechatRetryDelayMs(failures: number): number {
+ return Math.min(2_000 * 2 ** Math.max(0, failures - 1), 60_000);
+}
+
+/** Narrows a stored config document; throws a readable error on a malformed one. */
+export function wechatConfigOf(config: Record<string, unknown>): WeChatBindingConfig {
+ const { botId, botToken, baseUrl, userId } = config;
+ if (
+ typeof botId !== "string" ||
+ botId === "" ||
+ typeof botToken !== "string" ||
+ botToken === ""
+ ) {
+ throw new Error("malformed wechat binding config (botId/botToken)");
+ }
+ return {
+ botId,
+ botToken,
+ // A document written before the platform named a host, or by a scan whose answer carried
+ // none, polls the default entry host — which is where a bot without an IDC assignment
+ // lives anyway.
+ baseUrl: typeof baseUrl === "string" && baseUrl !== "" ? baseUrl : WECHAT_API_BASE,
+ userId: typeof userId === "string" ? userId : "",
+ };
+}
+
+/** The credentials the transport takes, out of a stored document. */
+function credsOf(config: Record<string, unknown>): WeChatCredentials {
+ const { botId, botToken, baseUrl, userId } = wechatConfigOf(config);
+ return { botId, botToken, baseUrl, userId };
+}
+
+/**
+ * One inbound event as the bridge's normalized message, with media as HANDLES.
+ *
+ * Nothing is downloaded here on purpose (see connector.ts): a redelivery is dropped before
+ * anything else happens, and a channel that downloaded first would pay a full transfer for
+ * every replay.
+ */
+function inboundOf(
+ bot: WeChatBotClient,
+ evt: WeChatInboundEvent,
+): {
+ chatId: string;
+ chatKind: "direct";
+ messageId: string;
+ text: string | null;
+ images?: readonly MessagingInboundImage[];
+ files?: readonly MessagingInboundFile[];
+} {
+ const images: MessagingInboundImage[] = evt.images.map((ref) => ({
+ fetch: async (maxBytes: number) => {
+ const data = await bot.fetchMedia(ref, maxBytes, "The image");
+ // The wire names no type for an image, so the bytes are the only source — and they are
+ // conclusive. PNG is the fallback for a format the sniffer does not know rather than
+ // `application/octet-stream`, which no provider accepts in a data URL.
+ return { data, mimeType: sniffImageMime(data) ?? "image/png" };
+ },
+ }));
+ const files: MessagingInboundFile[] = evt.files.map((file) => ({
+ fileName: file.fileName,
+ fetch: (maxBytes: number) => bot.fetchMedia(file.media, maxBytes, "The file"),
+ }));
+ return {
+ // The sender IS the chat on this channel: a bot conversation is one-to-one, and the id
+ // that arrives is the one a send is addressed to.
+ chatId: evt.userId,
+ chatKind: "direct",
+ // The reply anchor carries the chat, as it does on every channel whose message ids are
+ // not globally unique — and the id must identify the MESSAGE rather than the delivery,
+ // because it is also the bridge's dedupe key.
+ messageId: evt.messageId === "" ? "" : `${evt.userId}:${evt.messageId}`,
+ text: evt.text !== "" ? evt.text : null,
+ ...(images.length > 0 ? { images } : {}),
+ ...(files.length > 0 ? { files } : {}),
+ };
+}
+
+/** Reads a reply anchor back to the chat it belongs to (see inboundOf). */
+export function chatOfWeChatReplyRef(ref: string): string {
+ const cut = ref.lastIndexOf(":");
+ if (cut <= 0) throw new Error(`malformed wechat reply ref "${ref}"`);
+ return ref.slice(0, cut);
+}
+
+export interface WeChatConnectorOpts {
+ /** Test hook: the poll loop's backoff (tests collapse it to zero). */
+ retryDelayMs?: (failures: number) => number;
+}
+
+export class WeChatConnector implements MessagingChannelConnector {
+ readonly channel = "wechat" as const;
+
+ /**
+ * The most recent context token per `(botId, userId)`.
+ *
+ * On the connector rather than on a client because the two halves that need it arrive
+ * separately: tokens come in through `connect`, and sends go out through the client
+ * `createClient` hands the bridge. The bot is part of the key so two bindings on different
+ * bots can never spend each other's conversation handles.
+ */
+ private readonly contextTokens = new Map<string, string>();
+ private readonly retryDelayMs: (failures: number) => number;
+
+ constructor(
+ private readonly transport: WeChatTransport,
+ opts: WeChatConnectorOpts = {},
+ ) {
+ this.retryDelayMs = opts.retryDelayMs ?? wechatRetryDelayMs;
+ }
+
+ async createClient(config: Record<string, unknown>): Promise<MessagingClient> {
+ const creds = credsOf(config);
+ const bot = this.transport.createClient(creds);
+ /** One send's arguments: the rendered body, and this conversation's token when known. */
+ const args = (userId: string, text: string, opts?: MessagingSendOptions) => {
+ const contextToken = this.contextTokens.get(this.tokenKey(creds.botId, userId));
+ return {
+ userId,
+ text: opts?.markdown === true ? wechatMarkdownOf(text) : text,
+ ...(contextToken !== undefined ? { contextToken } : {}),
+ };
+ };
+ return {
+ async checkCredentials(): Promise<null> {
+ await bot.checkCredentials();
+ // `getconfig` answers with a typing ticket and nothing that names the bot or the
+ // account, so there is no label to surface — the same shape as QQ's probe.
+ return null;
+ },
+ sendText: (chatId: string, text: string, opts?: MessagingSendOptions) =>
+ bot.sendText(args(chatId, text, opts)),
+ // The same operation as sendText: this channel has no quote relation to thread onto
+ // (see the module doc), so the anchor is read only for the chat it names.
+ replyText: (ref: string, text: string, opts?: MessagingSendOptions) =>
+ bot.sendText(args(chatOfWeChatReplyRef(ref), text, opts)),
+ sendImage: (chatId: string, file: MessagingOutboundFile) =>
+ // The caption is empty because the bridge sends a reply's text as its own message:
+ // a picture here is the picture, and pairing it would duplicate what already went.
+ bot.sendImage({ ...args(chatId, ""), file }),
+ sendFile: (chatId: string, file: MessagingOutboundFile) =>
+ bot.sendFile({ ...args(chatId, ""), file }),
+ };
+ }
+
+ async connect(
+ config: Record<string, unknown>,
+ handlers: MessagingConnectorHandlers,
+ ): Promise<MessagingConnection> {
+ const creds = credsOf(config);
+ const bot = this.transport.createClient(creds);
+ const abort = new AbortController();
+ let closed = false;
+ void this.poll(creds, bot, handlers, abort.signal, () => closed);
+ return {
+ close: () => {
+ closed = true;
+ abort.abort();
+ // A conversation handle may not outlive the binding that learned it: without this, a
+ // token from before a disable would be echoed onto the first send after a re-enable,
+ // addressing a conversation the user has since ended.
+ this.dropTokens(creds.botId);
+ },
+ };
+ }
+
+ private tokenKey(botId: string, userId: string): string {
+ return `${botId}:${userId}`;
+ }
+
+ /** Forgets every conversation handle of one bot — the connection's close (see connect). */
+ private dropTokens(botId: string): void {
+ const prefix = `${botId}:`;
+ for (const key of this.contextTokens.keys()) {
+ if (key.startsWith(prefix)) this.contextTokens.delete(key);
+ }
+ }
+
+ private async poll(
+ creds: WeChatCredentials,
+ bot: WeChatBotClient,
+ handlers: MessagingConnectorHandlers,
+ signal: AbortSignal,
+ isClosed: () => boolean,
+ ): Promise<void> {
+ /** The credential probe has answered since the last failure, and onReady fired for it. */
+ let ready = false;
+ /** The backlog drain runs once per connection, never again after an outage (see the module doc). */
+ let drained = false;
+ /** Drains that closed on their deadline without the platform answering. */
+ let drainAttempts = 0;
+ let failures = 0;
+ let cursor = "";
+ while (!isClosed()) {
+ try {
+ if (!ready) {
+ // Readiness is proven HERE and not by a poll, because a poll is not an event: a
+ // long poll with nothing to report holds its request open for the whole window, so
+ // a connection reported ready only once one came back would sit at `connecting` for
+ // half a minute on an idle bot while being perfectly usable. This call answers at
+ // once and proves what "connected" means on this channel — the host resolves, the
+ // transport works, and the stored token authenticates.
+ //
+ // It runs again ahead of every recovery attempt, like telegram-connector's, so a
+ // token revoked during an outage stops the loop with the right reason rather than
+ // as an endless poll failure.
+ await bot.checkCredentials();
+ if (isClosed()) return;
+ ready = true;
+ handlers.onReady?.();
+ }
+ // The first call of a connection is a DRAIN, and asks for a short deadline: it wants
+ // whatever the platform is already holding, not whatever arrives next. Parked for the
+ // long-poll window it would instead return the first message a user sends after
+ // enabling — and then drop it as backlog.
+ const {
+ messages,
+ cursor: next,
+ timedOut,
+ } = await bot.getUpdates({
+ cursor,
+ signal,
+ ...(drained ? {} : { drain: true }),
+ });
+ if (isClosed()) return;
+ cursor = next;
+ if (!drained) {
+ // The cursor above is kept; these messages are not. Everything from before the
+ // connection existed is confirmed rather than relayed.
+ //
+ // A drain that hit its short deadline said nothing about where the platform stands,
+ // and its cursor is the one it was given — so spending it there would leave the
+ // cursor at the beginning and let the next ordinary poll relay a whole backlog as
+ // live traffic, which is the flood this exists to prevent. Retried instead, a few
+ // times: a bounded retry, because an idle bot whose long poll simply parks would
+ // otherwise ask forever, and after the bound the old behaviour is the safer of the
+ // two remaining wrongs — replaying a backlog beats discarding the first message a
+ // user sends after enabling.
+ if (!timedOut || ++drainAttempts >= DRAIN_ATTEMPTS) drained = true;
+ continue;
+ }
+ // Cleared here rather than beside the probe: the probe and the poll are different
+ // endpoints, so a failure that only ever hits the poll would otherwise be zeroed by
+ // every recovery, never walk the backoff up, and write one error record per attempt.
+ failures = 0;
+ for (const evt of messages) {
+ if (isClosed()) return;
+ // The token is learned BEFORE the bridge is told, so the reply to this very
+ // message is already addressed to the right conversation.
+ if (evt.contextToken !== undefined) {
+ this.contextTokens.set(this.tokenKey(creds.botId, evt.userId), evt.contextToken);
+ }
+ await handlers.onMessage(inboundOf(bot, evt));
+ }
+ } catch (err) {
+ if (isClosed()) return;
+ ready = false;
+ failures += 1;
+ // Reported once per outage, not once per attempt: a token revoked overnight would
+ // otherwise write one error record per retry until somebody looked.
+ if (failures === 1) handlers.onError?.(err);
+ await this.sleep(this.retryDelayMs(failures), signal);
+ }
+ }
+ }
+
+ /** A backoff that a close ends immediately rather than after its full delay. */
+ private sleep(ms: number, signal: AbortSignal): Promise<void> {
+ if (ms <= 0 || signal.aborted) return Promise.resolve();
+ return new Promise<void>((resolve) => {
+ const timer = setTimeout(() => {
+ signal.removeEventListener("abort", onAbort);
+ resolve();
+ }, ms);
+ const onAbort = (): void => {
+ clearTimeout(timer);
+ resolve();
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ });
+ }
+}
diff --git a/packages/server/src/runtime/messaging/wechat-markdown.ts b/packages/server/src/runtime/messaging/wechat-markdown.ts
new file mode 100644
index 00000000..b27e0b52
--- /dev/null
+++ b/packages/server/src/runtime/messaging/wechat-markdown.ts
@@ -0,0 +1,294 @@
+/**
+ * Renders a parsed Markdown reply into the subset WeChat's own client displays.
+ *
+ * This channel is the odd one of the four, and the difference is worth stating before the
+ * code: Telegram, Feishu and QQ each take a DIFFERENT markup, so their renderers translate.
+ * WeChat reads Markdown itself — the same syntax the model wrote — so this renderer's job is
+ * not translation but SUBTRACTION: emit what the client renders, and strip the markers of
+ * what it does not, so an unsupported construct arrives as its own text instead of as
+ * literal punctuation.
+ *
+ * ## What renders, and what does not
+ *
+ * Renders: headings H1–H4, bold, strikethrough, links, ordered and unordered lists with
+ * nesting, blockquotes, horizontal rules, INLINE CODE, FENCED CODE and TABLES. That last
+ * trio makes this the widest of the four channels for the kind of reply this product
+ * actually writes — QQ has no code and no tables, Telegram has no lists, headings or tables.
+ *
+ * Does not render, and is therefore stripped to its content:
+ *
+ * - **H5 and H6.** The client's heading scale stops at four levels; a fifth arrives as
+ * five literal `#`. The text becomes an ordinary paragraph, which is what a heading too
+ * deep to show was already going to look like.
+ * - **Emphasis around CJK.** `*text*` needs the marker to sit against a word boundary, and
+ * CJK text has none, so `*中文*` renders as asterisks around Chinese. Latin emphasis is
+ * kept because it does render; a CJK run loses the markers and keeps the words. This is
+ * why emphasis is decided per node rather than once.
+ * - **Images.** The client has no inline image in a text message, and `![alt](url)` shows
+ * as its own characters. It becomes a LINK rather than being dropped: a link is a thing
+ * the reader can follow, and dropping the node would silently lose a URL the reply
+ * deliberately included. The reply's own pictures do not travel this way at all — they
+ * are sent as real images (see the connector's sendImage).
+ *
+ * ## Escaping
+ *
+ * Only literal TEXT is escaped, and only the characters that open a construct. Code — inline
+ * or fenced — is emitted verbatim inside its own markers, because those markers are exactly
+ * what makes the content literal on a channel that honours them. Escaping inside a fence
+ * would put backslashes into code the reader is meant to copy, which is the whole point of
+ * putting it in a chat.
+ */
+import { isSafeUrl, parseMarkdown } from "./markdown.js";
+import type {
+ BlockContent,
+ DefinitionContent,
+ Emphasis,
+ List,
+ ListItem,
+ PhrasingContent,
+ RootContent,
+ Table,
+} from "mdast";
+
+/** One indent level inside a list. Four spaces is what the client's parser nests on. */
+const LIST_INDENT = " ";
+
+/** The deepest heading level the client renders; below this the markers are dropped. */
+const MAX_HEADING_DEPTH = 4;
+
+/** Characters that open a construct wherever they appear. `\` leads, or it escapes the escapes. */
+const INLINE_SPECIALS = /[\\`*_~[\]]/g;
+
+/**
+ * Any CJK codepoint: the Unified ideographs and their extension A, plus the kana and Hangul
+ * blocks and CJK punctuation. Emphasis around any of these does not render (see the module
+ * doc), and the test is on the whole run rather than its edges because the client's rule is
+ * about word boundaries, which such a run has nowhere.
+ */
+const CJK = /[⺀-〿぀-ヿ㐀-䶿一-鿿가-힯豈-﫿＀-￯]/;
+
+function esc(text: string): string {
+ return text.replace(INLINE_SPECIALS, (ch) => `\\${ch}`);
+}
+
+/**
+ * Escapes a marker a line happens to START with. These mean nothing mid-line, and escaping
+ * them everywhere would put a backslash in every hyphenated word and every decimal number.
+ */
+function guardLineStarts(text: string): string {
+ return text
+ .split("\n")
+ .map((line) => line.replace(/^(\s*)([#>\-+])/, "$1\\$2").replace(/^(\s*\d+)([.)])/, "$1\\$2"))
+ .join("\n");
+}
+
+/** A link target, with the two characters that would close the `](…)` early made safe. */
+function href(url: string): string {
+ return url.replaceAll("(", "%28").replaceAll(")", "%29");
+}
+
+function inline(nodes: readonly PhrasingContent[]): string {
+ return nodes.map(phrasing).join("");
+}
+
+/**
+ * Emphasis renders only where its markers sit against a word boundary, which is why this is
+ * a decision and not a template: a run containing CJK keeps its words and loses the
+ * asterisks that would otherwise be shown as asterisks.
+ */
+function emphasis(node: Emphasis): string {
+ const body = inline(node.children);
+ return CJK.test(body) ? body : `*${body}*`;
+}
+
+/**
+ * The longest backtick run inside a value, so an inline span can be fenced by one longer.
+ * Code containing a backtick is ordinary in this product's replies, and a single-backtick
+ * span would end at the first one it contains.
+ */
+function longestBacktickRun(value: string): number {
+ let longest = 0;
+ for (const run of value.matchAll(/`+/g)) longest = Math.max(longest, run[0].length);
+ return longest;
+}
+
+function phrasing(node: PhrasingContent): string {
+ switch (node.type) {
+ case "text":
+ return esc(node.value);
+ case "strong":
+ return `**${inline(node.children)}**`;
+ case "emphasis":
+ return emphasis(node);
+ case "delete":
+ return `~~${inline(node.children)}~~`;
+ case "inlineCode": {
+ // Verbatim inside a fence long enough to contain it, and padded when the value starts
+ // or ends with a backtick — both are CommonMark's own rules for the case.
+ const fence = "`".repeat(longestBacktickRun(node.value) + 1);
+ const pad = node.value.startsWith("`") || node.value.endsWith("`") ? " " : "";
+ return `${fence}${pad}${node.value}${pad}${fence}`;
+ }
+ case "link": {
+ const label = inline(node.children);
+ return isSafeUrl(node.url) ? `[${label}](${href(node.url)})` : label;
+ }
+ case "image": {
+ // A link rather than a dropped node — see the module doc.
+ const alt = node.alt ?? "";
+ const label = esc(alt !== "" ? alt : node.url);
+ return isSafeUrl(node.url) ? `[${label}](${href(node.url)})` : label;
+ }
+ case "break":
+ return "\n";
+ case "html":
+ return esc(node.value);
+ case "footnoteReference":
+ return esc(`[^${node.identifier}]`);
+ case "linkReference":
+ case "imageReference":
+ return "children" in node ? inline(node.children) : esc(node.label ?? node.identifier);
+ default:
+ return "";
+ }
+}
+
+/**
+ * Inline content as unformatted text, for a table cell (whose content may not be a block).
+ *
+ * Escaped like any other literal text: a cell is still markdown to the client, so a `*` or a
+ * backtick that arrived as content would open a construct inside the table rather than being
+ * shown. Only `|` was escaped here before, which closed the column hazard and left that one.
+ */
+function plainText(nodes: readonly PhrasingContent[]): string {
+ return nodes
+ .map((node) => {
+ if (node.type === "text" || node.type === "inlineCode" || node.type === "html") {
+ return esc(node.value);
+ }
+ if (node.type === "break") return " ";
+ if (node.type === "image") return node.alt ?? "";
+ return "children" in node ? plainText(node.children) : "";
+ })
+ .join("");
+}
+
+/**
+ * A GFM table, kept as a table. The client renders one, so the delimiter row is emitted and
+ * a cell's own pipes are escaped rather than allowed to open a column that is not there.
+ */
+function renderTable(node: Table): string {
+ const rows = node.children.map(
+ (row) =>
+ `| ${row.children.map((cell) => plainText(cell.children).replaceAll("|", "\\|")).join(" | ")} |`,
+ );
+ const header = rows[0];
+ if (header === undefined) return "";
+ const columns = node.children[0]?.children.length ?? 0;
+ return [header, `|${" --- |".repeat(columns)}`, ...rows.slice(1)].join("\n");
+}
+
+function itemMarker(list: List, index: number): string {
+ return list.ordered === true ? `${(list.start ?? 1) + index}. ` : "- ";
+}
+
+/** A GFM task item's box. The client draws no checkbox, so the glyph is the checkbox. */
+function itemCheckbox(item: ListItem): string {
+ if (item.checked === true) return "☑ ";
+ if (item.checked === false) return "☐ ";
+ return "";
+}
+
+function renderList(list: List, indent: string): string {
+ return list.children
+ .map((item, i) => {
+ const head = `${indent}${itemMarker(list, i)}${itemCheckbox(item)}`;
+ const parts: string[] = [];
+ for (const [j, child] of item.children.entries()) {
+ if (j === 0 && child.type === "paragraph") {
+ parts.push(head + inline(child.children));
+ continue;
+ }
+ if (child.type === "list") {
+ parts.push(renderList(child, indent + LIST_INDENT));
+ continue;
+ }
+ const rendered = block(child, indent + LIST_INDENT);
+ if (rendered !== "") {
+ parts.push(
+ rendered
+ .split("\n")
+ .map((line) => indent + LIST_INDENT + line)
+ .join("\n"),
+ );
+ }
+ }
+ return parts.filter((part) => part !== "").join("\n");
+ })
+ .filter((line) => line !== "")
+ .join("\n");
+}
+
+/** A fence long enough to contain the block's own backticks (CommonMark's rule). */
+function codeFence(value: string): string {
+ return "`".repeat(Math.max(3, longestBacktickRun(value) + 1));
+}
+
+function block(node: BlockContent | DefinitionContent | RootContent, indent: string): string {
+ switch (node.type) {
+ case "paragraph":
+ return guardLineStarts(inline(node.children));
+ case "heading": {
+ const text = inline(node.children);
+ // Past the client's scale the markers would show as characters, so the heading becomes
+ // the paragraph it was already going to look like.
+ return node.depth > MAX_HEADING_DEPTH
+ ? guardLineStarts(text)
+ : `${"#".repeat(node.depth)} ${text}`;
+ }
+ case "code": {
+ const fence = codeFence(node.value);
+ // The language tag is kept: the client highlights by it, and it costs nothing where
+ // the client does not.
+ return `${fence}${node.lang ?? ""}\n${node.value}\n${fence}`;
+ }
+ case "blockquote":
+ return node.children
+ .map((child) => block(child, indent))
+ .filter((rendered) => rendered !== "")
+ .join("\n\n")
+ .split("\n")
+ .map((line) => `> ${line}`)
+ .join("\n");
+ case "list":
+ return renderList(node, indent);
+ case "table":
+ return renderTable(node);
+ case "thematicBreak":
+ return "---";
+ case "html":
+ return guardLineStarts(esc(node.value));
+ case "footnoteDefinition":
+ return `**${esc(`[^${node.identifier}]`)}** ${node.children.map((child) => block(child, indent)).join("\n\n")}`;
+ case "definition":
+ return "";
+ default:
+ return "";
+ }
+}
+
+/**
+ * One relayed message as the Markdown WeChat renders.
+ *
+ * Blocks are separated by a blank line throughout: a list or a fence that follows ordinary
+ * text without one is not recognized as a block at all, which is the failure that shows a
+ * reader raw `-` bullets.
+ */
+export function wechatMarkdownOf(markdown: string): string {
+ const root = parseMarkdown(markdown);
+ return root.children
+ .map((node) => block(node, ""))
+ .filter((rendered) => rendered !== "")
+ .join("\n\n")
+ .trim();
+}
diff --git a/packages/server/src/runtime/messaging/wechat-scan.ts b/packages/server/src/runtime/messaging/wechat-scan.ts
new file mode 100644
index 00000000..b8939bb3
--- /dev/null
+++ b/packages/server/src/runtime/messaging/wechat-scan.ts
@@ -0,0 +1,467 @@
+/**
+ * WeChat scan-to-connect: binding the official claw bot by scanning a QR code in WeChat.
+ *
+ * Unlike QQ, this is not the convenient alternative to typing credentials — it is the ONLY
+ * way to obtain them. The bot token this flow issues exists nowhere a person can copy it
+ * from: there is no developer console for this channel and no pair of fields to fall back
+ * to, so the editor offers a scan and nothing else.
+ *
+ * The protocol is two calls against `ilinkai.weixin.qq.com`:
+ *
+ * 1. `get_bot_qrcode` returns a `qrcode` handle and a URL. The URL is ENCODED INTO A QR
+ * CODE and never fetched by this server — WeChat resolves it when the code is scanned.
+ * 2. `get_qrcode_status` is LONG-POLLED with the handle until it reports the scan
+ * confirmed, at which point it returns the bot token, the bot id, the id of the person
+ * who scanned, and the API host this bot is to be polled against.
+ *
+ * ## The `qrcode` handle is the whole security model
+ *
+ * There is no encrypted payload here as there is on QQ, and so no key to protect: the
+ * handle IS the thing that turns into a bot token, and anyone holding it can poll the token
+ * out. It is therefore generated here, held here, used here, and dropped here — the browser
+ * is given a task id this module mints instead, plus the URL and a status. The QR's URL is
+ * safe to render because scanning it authorizes nothing on its own; only the paired handle
+ * can collect the result.
+ *
+ * ## Why the poll is shaped differently from QQ's
+ *
+ * `get_qrcode_status` is a LONG poll: the platform holds it open until the state changes.
+ * That gives the browser its state changes within a second of them happening, but it also
+ * means one upstream call outlives several of the browser's polling intervals. QQ answers an
+ * overlapping poll with a 404 because there a second poll could bind a second time; here it
+ * answers `pending`, because the overlap is the normal case rather than a replay. The
+ * once-only guarantee is unchanged and comes from the same place it does on QQ: a resolved
+ * task is deleted, so nothing can resolve it twice.
+ */
+import { randomBytes } from "node:crypto";
+import { WECHAT_API_BASE, WECHAT_BOT_TYPE, wechatFetchErrorText } from "./wechat-api.js";
+
+/** Overall deadline for `get_bot_qrcode`, which answers immediately. */
+const CREATE_TIMEOUT_MS = 15_000;
+
+/**
+ * How long ONE upstream status poll may be held. The platform's own window is 35s; this is
+ * shorter so the browser's request — which is parked on it — returns promptly and its own
+ * interval keeps a steady rhythm. A window that closes with nothing to report is `pending`,
+ * exactly as the protocol intends.
+ */
+const POLL_TIMEOUT_MS = 8_000;
+
+/** How often the browser should poll (see the module doc on why overlaps are expected). */
+export const WECHAT_SCAN_POLL_MS = 2000;
+
+/**
+ * Where the scan stands, in the vocabulary the browser renders.
+ *
+ * Richer than QQ's four states because the flow is: WeChat separates SCANNING from
+ * confirming, and may interpose a pairing code shown on the phone that the person types
+ * here. Each state below is one the user has to be told something different about.
+ */
+export type WeChatScanStatus =
+ /** The code is on screen and nothing has happened yet. */
+ | "pending"
+ /** Scanned; the phone is showing the confirmation prompt. */
+ | "scanned"
+ /** The phone is showing digits that must be typed here before the bind proceeds. */
+ | "need_verify_code"
+ /** Too many wrong pairing codes: the platform has stopped accepting them for now. */
+ | "blocked"
+ /** The code lapsed before it was used; a new one is needed. */
+ | "expired"
+ /** This bot is already bound to this server, so no new credentials were issued. */
+ | "already_bound"
+ | "completed";
+
+/** The credentials a confirmed scan produced. */
+export interface WeChatScanResult {
+ botId: string;
+ botToken: string;
+ /** The API host this bot is assigned; the platform's default host when it named none. */
+ baseUrl: string;
+ /** The person who scanned — what the credential probe is made on behalf of. */
+ userId: string;
+}
+
+/** One upstream poll's outcome, normalized. */
+export interface WeChatScanPollResult {
+ status: WeChatScanStatus;
+ /** Present only on `completed`. */
+ bot?: WeChatScanResult;
+ /**
+ * A host the platform redirected polling to. Internal: the caller switches to it and keeps
+ * polling, and the browser only ever sees the status that rode along with it.
+ */
+ redirectHost?: string;
+}
+
+/** The two calls, behind a seam so tests substitute a fake and never open a socket. */
+export interface WeChatScanTransport {
+ /** Registers a code; resolves the poll handle and the URL to encode into the QR. */
+ createQrCode(): Promise<{ qrcode: string; qrUrl: string }>;
+ /**
+ * One long poll of a code's status. `verifyCode` carries the digits the person read off
+ * their phone, when the previous poll asked for them.
+ */
+ pollQrStatus(args: {
+ baseUrl: string;
+ qrcode: string;
+ verifyCode?: string;
+ }): Promise<WeChatScanPollResult>;
+}
+
+/** The status strings the wire uses, mapped onto the ones above. */
+function statusOf(raw: unknown): WeChatScanStatus {
+ switch (raw) {
+ case "confirmed":
+ return "completed";
+ case "scaned":
+ // A redirect is a scan that must continue against another host: the person has scanned,
+ // which is what they need told, and the host switch is the caller's business.
+ case "scaned_but_redirect":
+ return "scanned";
+ case "need_verifycode":
+ return "need_verify_code";
+ case "verify_code_blocked":
+ return "blocked";
+ case "expired":
+ return "expired";
+ case "binded_redirect":
+ return "already_bound";
+ default:
+ // An unknown value reads as "keep waiting" rather than as a failure: a state this
+ // build has not heard of is not a reason to take a live code off the user's screen.
+ return "pending";
+ }
+}
+
+/** The production factory: plain HTTPS against the platform's fixed entry host. */
+export function createWeChatScanTransport(base = WECHAT_API_BASE): WeChatScanTransport {
+ /**
+ * The headers these two calls take. There is no `Authorization` on either — they are what
+ * ISSUES the token, so there is none to send.
+ */
+ const headers = (): Record<string, string> => ({
+ "iLink-App-Id": "bot",
+ "iLink-App-ClientVersion": String((1 << 16) | 0),
+ });
+
+ return {
+ async createQrCode(): Promise<{ qrcode: string; qrUrl: string }> {
+ let res: Response;
+ try {
+ res = await fetch(
+ `${base}/ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(WECHAT_BOT_TYPE)}`,
+ {
+ method: "POST",
+ headers: { ...headers(), "content-type": "application/json" },
+ // The platform takes the tokens this client already holds so it can recognize a
+ // rebind of a bot it has already issued one for. Nothing here offers them: a
+ // stored token is another Session's credential, and the `already_bound` answer
+ // this would enable is not worth handing one binding's secret to another's flow.
+ body: JSON.stringify({ local_token_list: [] }),
+ signal: AbortSignal.timeout(CREATE_TIMEOUT_MS),
+ },
+ );
+ } catch (err) {
+ throw new Error(`WeChat scan request failed: ${wechatFetchErrorText(err)}`);
+ }
+ if (!res.ok) throw new Error(`WeChat scan request failed: HTTP ${res.status}`);
+ const body = (await res.json().catch(() => null)) as {
+ qrcode?: string;
+ qrcode_img_content?: string;
+ } | null;
+ const qrcode = body?.qrcode;
+ const qrUrl = body?.qrcode_img_content;
+ if (
+ typeof qrcode !== "string" ||
+ qrcode === "" ||
+ typeof qrUrl !== "string" ||
+ qrUrl === ""
+ ) {
+ throw new Error("WeChat scan request failed: no QR code was returned");
+ }
+ return { qrcode, qrUrl };
+ },
+
+ async pollQrStatus({ baseUrl, qrcode, verifyCode }): Promise<WeChatScanPollResult> {
+ const query = new URLSearchParams({ qrcode });
+ if (verifyCode !== undefined && verifyCode !== "") query.set("verify_code", verifyCode);
+ let res: Response;
+ try {
+ res = await fetch(`${baseUrl}/ilink/bot/get_qrcode_status?${query.toString()}`, {
+ headers: headers(),
+ signal: AbortSignal.timeout(POLL_TIMEOUT_MS),
+ });
+ } catch (err) {
+ // A long poll that closed with nothing to say is indistinguishable from one this
+ // client timed out, and both mean the same thing: nothing changed, ask again. A
+ // gateway's own timeout (a 504 from an edge that got bored) lands here too.
+ if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
+ return { status: "pending" };
+ }
+ throw new Error(`WeChat scan request failed: ${wechatFetchErrorText(err)}`);
+ }
+ if (!res.ok) throw new Error(`WeChat scan request failed: HTTP ${res.status}`);
+ const body = (await res.json().catch(() => null)) as {
+ status?: string;
+ bot_token?: string;
+ ilink_bot_id?: string;
+ ilink_user_id?: string;
+ baseurl?: string;
+ redirect_host?: string;
+ } | null;
+ const status = statusOf(body?.status);
+ const redirect =
+ typeof body?.redirect_host === "string" && body.redirect_host !== ""
+ ? { redirectHost: body.redirect_host }
+ : {};
+ if (status !== "completed") return { status, ...redirect };
+ const botId = body?.ilink_bot_id;
+ const botToken = body?.bot_token;
+ if (
+ typeof botId !== "string" ||
+ botId === "" ||
+ typeof botToken !== "string" ||
+ botToken === ""
+ ) {
+ throw new Error("WeChat reported the scan confirmed but returned no credentials");
+ }
+ return {
+ status: "completed",
+ bot: {
+ botId,
+ botToken,
+ baseUrl:
+ typeof body?.baseurl === "string" && body.baseurl !== ""
+ ? body.baseurl
+ : WECHAT_API_BASE,
+ userId: typeof body?.ilink_user_id === "string" ? body.ilink_user_id : "",
+ },
+ };
+ },
+ };
+}
+
+// ---------------------------------------------------------------------------
+// The in-flight task table
+// ---------------------------------------------------------------------------
+
+/**
+ * How long a code is kept. The platform expires codes on its own and reports it, so this is
+ * only the bound on remembering a handle for a flow nobody finished — a browser tab closed
+ * mid-scan leaves a task that will otherwise never be polled again.
+ */
+export const WECHAT_SCAN_TASK_TTL_MS = 10 * 60_000;
+
+/**
+ * How many codes ONE Session may keep in flight. Per-Session rather than process-wide for
+ * the reason qq-scan.ts is: starting a scan is reachable by anyone who owns a Project, so a
+ * table bounded only across all callers lets one of them in a loop evict everybody else's
+ * code. Eviction here can only ever drop the caller's OWN oldest task.
+ */
+const WECHAT_SCAN_MAX_TASKS_PER_SESSION = 4;
+
+/** Absolute bound across every Session — a memory backstop, far above any real concurrency. */
+const WECHAT_SCAN_MAX_TASKS = 4096;
+
+/** One in-flight scan. `qrcode` is the reason this table exists at all (see the module doc). */
+interface WeChatScanTask {
+ /** The platform's poll handle. NEVER leaves this process. */
+ qrcode: string;
+ /** The Session that started the scan; another Session's poll is not this task's business. */
+ sessionId: string;
+ createdAt: number;
+ /** An upstream poll is in flight; a second one would only wait behind it. */
+ polling: boolean;
+ /** The host polling has been redirected to, once the platform names one. */
+ baseUrl: string;
+ /**
+ * The digits the person typed, held until the next poll carries them. Kept rather than
+ * sent immediately because the poll that asks for them is the one that has just returned:
+ * there is no request in flight to put them on.
+ */
+ verifyCode?: string;
+}
+
+/** What a poll tells the caller: where the scan stands, and the credentials once it landed. */
+export interface WeChatScanPoll {
+ status: WeChatScanStatus;
+ /** Present only on `completed` — for the caller to store. */
+ bot?: WeChatScanResult;
+}
+
+export interface WeChatScanServiceOpts {
+ now?: () => number;
+}
+
+/**
+ * Holds the in-flight codes and their poll handles.
+ *
+ * Deliberately in memory, for the reason QQScanService is: a task is alive for the couple of
+ * minutes a person spends scanning, and persisting a handle that collects a bot token would
+ * buy nothing except a second place for it to leak from. A server restart mid-scan loses the
+ * task and the user starts another, which is a strictly better failure than a handle at rest.
+ */
+export class WeChatScanService {
+ private readonly tasks = new Map<string, WeChatScanTask>();
+ private readonly now: () => number;
+ /** The self-re-arming sweep, alive only while a task is remembered (see `armSweep`). */
+ private sweepTimer: ReturnType<typeof setTimeout> | null = null;
+
+ constructor(
+ private readonly transport: WeChatScanTransport,
+ opts: WeChatScanServiceOpts = {},
+ ) {
+ this.now = opts.now ?? (() => Date.now());
+ }
+
+ /** Starts a scan: a fresh code, a task registered under a handle of this module's own. */
+ async start(sessionId: string): Promise<{ taskId: string; qrUrl: string; pollMs: number }> {
+ this.sweep();
+ const { qrcode, qrUrl } = await this.transport.createQrCode();
+ // Evicted after the create rather than before it: a create that failed must not have
+ // cost the caller a live code.
+ this.evictOwn(sessionId);
+ // The task id is minted here rather than being the platform's `qrcode`, which is the
+ // whole point: the browser polls with a handle that collects nothing on its own.
+ const taskId = randomBytes(16).toString("hex");
+ this.tasks.set(taskId, {
+ qrcode,
+ sessionId,
+ createdAt: this.now(),
+ polling: false,
+ baseUrl: WECHAT_API_BASE,
+ });
+ this.armSweep();
+ return { taskId, qrUrl, pollMs: WECHAT_SCAN_POLL_MS };
+ }
+
+ /**
+ * Records the pairing code the person read off their phone. It rides the NEXT poll rather
+ * than a request of its own: the platform takes it as a parameter of the status call, and
+ * there is no separate submit.
+ *
+ * Returns false for a task this Session did not start, which the caller answers with the
+ * same 404 an unknown poll gets.
+ */
+ submitVerifyCode(sessionId: string, taskId: string, verifyCode: string): boolean {
+ const task = this.tasks.get(taskId);
+ if (task === undefined || task.sessionId !== sessionId) return false;
+ task.verifyCode = verifyCode;
+ return true;
+ }
+
+ /**
+ * Polls one task. Returns null when the task id is not one this Session started — an
+ * unknown id, another Session's, or one already resolved — which the caller answers 404,
+ * and which is also what a replay gets.
+ */
+ async poll(sessionId: string, taskId: string): Promise<WeChatScanPoll | null> {
+ const task = this.tasks.get(taskId);
+ if (task === undefined || task.sessionId !== sessionId) return null;
+ if (this.now() - task.createdAt > WECHAT_SCAN_TASK_TTL_MS) {
+ this.tasks.delete(taskId);
+ return { status: "expired" };
+ }
+ // An upstream poll is long, so the browser's interval fires several times inside one.
+ // Those overlaps are the normal rhythm here rather than a replay to refuse: they answer
+ // "nothing yet" and the one real call keeps running (see the module doc).
+ if (task.polling) return { status: "pending" };
+ task.polling = true;
+ let result: WeChatScanPollResult;
+ try {
+ result = await this.transport.pollQrStatus({
+ baseUrl: task.baseUrl,
+ qrcode: task.qrcode,
+ ...(task.verifyCode !== undefined ? { verifyCode: task.verifyCode } : {}),
+ });
+ } catch (err) {
+ // A request that failed resolved nothing: the task stays pollable, which is what lets
+ // the client ride out a transient platform error without dropping the user's code.
+ task.polling = false;
+ throw err;
+ } finally {
+ // The task may already be gone by here (a cancel landed mid-poll); writing to the
+ // object it held is harmless, and the map no longer points at it.
+ task.polling = false;
+ }
+ // The platform hands polling to another host mid-flow. It is not a state of its own for
+ // the browser — the scan is simply still in progress — so the switch is made here and
+ // the status that rode along with it is what is reported.
+ if (result.redirectHost !== undefined) task.baseUrl = `https://${result.redirectHost}`;
+ if (result.status === "scanned" && task.verifyCode !== undefined) {
+ // A pairing code the platform accepted takes the flow past `need_verify_code`. Holding
+ // it would resubmit it on every later poll, and a stale one would be rejected as wrong.
+ task.verifyCode = undefined;
+ }
+ if (
+ result.status === "expired" ||
+ result.status === "blocked" ||
+ result.status === "already_bound"
+ ) {
+ // All three are ends: nothing further can come of this code. `blocked` and
+ // `already_bound` are the platform declining rather than a lapse, and neither is
+ // recoverable by polling the same handle again.
+ this.tasks.delete(taskId);
+ return { status: result.status };
+ }
+ if (result.status !== "completed") return { status: result.status };
+ // Past here the task is spent whatever happens.
+ this.tasks.delete(taskId);
+ if (result.bot === undefined) {
+ throw new Error("WeChat reported the scan confirmed but returned no credentials");
+ }
+ return { status: "completed", bot: result.bot };
+ }
+
+ /** Drops a task the user walked away from (the editor's cancel, and its unmount). */
+ cancel(sessionId: string, taskId: string): void {
+ if (this.tasks.get(taskId)?.sessionId === sessionId) this.tasks.delete(taskId);
+ }
+
+ /** Session-delete cascade and bind removal: forget anything this Session had in flight. */
+ cancelSession(sessionId: string): void {
+ for (const [taskId, task] of this.tasks) {
+ if (task.sessionId === sessionId) this.tasks.delete(taskId);
+ }
+ }
+
+ /** Drops this Session's oldest tasks until one more fits under its own ceiling. */
+ private evictOwn(sessionId: string): void {
+ const own = [...this.tasks].filter(([, task]) => task.sessionId === sessionId);
+ if (own.length < WECHAT_SCAN_MAX_TASKS_PER_SESSION) return;
+ own.sort((a, b) => a[1].createdAt - b[1].createdAt);
+ for (const [taskId] of own.slice(0, own.length - WECHAT_SCAN_MAX_TASKS_PER_SESSION + 1)) {
+ this.tasks.delete(taskId);
+ }
+ }
+
+ /** Drops expired tasks, then the oldest ones if the table is still over its backstop. */
+ private sweep(): void {
+ const cutoff = this.now() - WECHAT_SCAN_TASK_TTL_MS;
+ for (const [taskId, task] of this.tasks) {
+ if (task.createdAt <= cutoff) this.tasks.delete(taskId);
+ }
+ if (this.tasks.size < WECHAT_SCAN_MAX_TASKS) return;
+ const byAge = [...this.tasks].sort((a, b) => a[1].createdAt - b[1].createdAt);
+ for (const [taskId] of byAge.slice(0, this.tasks.size - WECHAT_SCAN_MAX_TASKS + 1)) {
+ this.tasks.delete(taskId);
+ }
+ }
+
+ /**
+ * Keeps one unref'd timer alive while any task is remembered, so a scan the user walked
+ * away from stops holding its handle roughly at the TTL instead of at whenever somebody
+ * happens to start the next scan — which may be never.
+ */
+ private armSweep(): void {
+ if (this.sweepTimer !== null || this.tasks.size === 0) return;
+ const timer = setTimeout(() => {
+ this.sweepTimer = null;
+ this.sweep();
+ this.armSweep();
+ }, WECHAT_SCAN_TASK_TTL_MS);
+ timer.unref();
+ this.sweepTimer = timer;
+ }
+}
diff --git a/packages/server/test/messaging-markdown.test.ts b/packages/server/test/messaging-markdown.test.ts
index 2f2e6577..a424a5a1 100644
--- a/packages/server/test/messaging-markdown.test.ts
+++ b/packages/server/test/messaging-markdown.test.ts
@@ -1,8 +1,8 @@
/**
- * The Markdown conversion the three messaging channels relay a reply through: the shared
+ * The Markdown conversion the four messaging channels relay a reply through: the shared
* parse and chunking (markdown.ts), and each channel's own renderer.
*
- * Three renderers rather than one because the three platforms accept three different
+ * Four renderers rather than one because the four platforms accept four different
* subsets, and the tests are organized to say so: every construct the model actually writes
* is asserted per channel, including the ones a channel CANNOT show, because how a missing
* construct degrades is the part a reader of a chat notices. The escaping cases are grouped
@@ -11,8 +11,8 @@
*
* Delivery — that a rendered send actually goes out with the right `parse_mode` / `msg_type`,
* and that a refused one falls back to plain text — is proven against each channel's own
- * wire fake in messaging.test.ts, messaging-telegram.test.ts, messaging-qq.test.ts and
- * messaging-wire.test.ts. Nothing here sends anything.
+ * wire fake in messaging.test.ts, messaging-telegram.test.ts, messaging-qq.test.ts,
+ * messaging-wechat.test.ts and messaging-wire.test.ts. Nothing here sends anything.
*/
import { describe, expect, it } from "vitest";
import { attachedFileLine } from "@prismshadow/penguin-core";
@@ -21,6 +21,7 @@ import { chunkMarkdown, isSafeUrl, parseMarkdown } from "../src/runtime/messagin
import { feishuCardOf, feishuMarkdownOf } from "../src/runtime/messaging/feishu-card.js";
import { qqMarkdownOf } from "../src/runtime/messaging/qq-markdown.js";
import { telegramHtmlOf } from "../src/runtime/messaging/telegram-html.js";
+import { wechatMarkdownOf } from "../src/runtime/messaging/wechat-markdown.js";
describe("parseMarkdown", () => {
it("reads GFM, so tables and task lists are constructs rather than punctuation", () => {
@@ -247,6 +248,99 @@ describe("qqMarkdownOf", () => {
});
});
+// ---------------------------------------------------------------------------
+
+describe("wechatMarkdownOf", () => {
+ it("escapes a table cell's literal markers so it cannot open a construct inside the table", () => {
+ // A cell's formatting is flattened, but its LITERAL characters are still markdown to the
+ // client: only `|` was escaped before, so a lone `*` in one cell could pair with one in
+ // another and open emphasis straight through the table.
+ const out = wechatMarkdownOf("| a | b |\n| --- | --- |\n| 2*3 | 4*5 |");
+ expect(out).toContain("2\\*3");
+ expect(out).toContain("4\\*5");
+ // The flattening itself is unchanged: a cell's own emphasis still loses its markers.
+ expect(wechatMarkdownOf("| a |\n| --- |\n| *x* |")).toContain("| x |");
+ });
+
+ it("keeps the constructs WeChat reads, which is the most of the four", () => {
+ expect(wechatMarkdownOf("## Two")).toBe("## Two");
+ expect(wechatMarkdownOf("**b** ~~s~~")).toBe("**b** ~~s~~");
+ expect(wechatMarkdownOf("- a\n - b")).toBe("- a\n - b");
+ expect(wechatMarkdownOf("1. one\n2. two")).toBe("1. one\n2. two");
+ expect(wechatMarkdownOf("> quoted")).toBe("> quoted");
+ expect(wechatMarkdownOf("[l](https://x.com)")).toBe("[l](https://x.com)");
+ expect(wechatMarkdownOf("---")).toBe("---");
+ });
+
+ it("keeps code as code, fence and language and all — the reason this channel is the widest", () => {
+ // The renderer here subtracts rather than translates: what WeChat reads is emitted as
+ // the model wrote it, and only what it cannot read loses its markers.
+ expect(wechatMarkdownOf("```python\n# a comment\nx = a ** b\n```")).toBe(
+ "```python\n# a comment\nx = a ** b\n```",
+ );
+ expect(wechatMarkdownOf("use `read_file` first")).toBe("use `read_file` first");
+ });
+
+ it("widens a fence past the backticks its own content holds", () => {
+ // A three-backtick fence around content containing three would close at the content.
+ expect(wechatMarkdownOf("````\n```\n````")).toBe("````\n```\n````");
+ // A span whose CONTENT holds a backtick: one delimiter would close at it.
+ expect(wechatMarkdownOf("use `` a`b `` here")).toBe("use ``a`b`` here");
+ });
+
+ it("keeps a table as a table, delimiter row included", () => {
+ expect(wechatMarkdownOf("| a | b |\n| - | - |\n| 1 | 2 |")).toBe(
+ "| a | b |\n| --- | --- |\n| 1 | 2 |",
+ );
+ // A pipe inside a cell would open a column that is not there.
+ expect(wechatMarkdownOf("| a |\n| - |\n| x \\| y |")).toContain("| x \\| y |");
+ });
+
+ it("drops the markers of a heading deeper than the client's scale", () => {
+ // Five `#` would arrive as five literal characters; the text becomes the paragraph it
+ // was already going to look like.
+ expect(wechatMarkdownOf("#### Four")).toBe("#### Four");
+ expect(wechatMarkdownOf("##### Five")).toBe("Five");
+ expect(wechatMarkdownOf("###### Six")).toBe("Six");
+ });
+
+ it("keeps Latin emphasis and drops the asterisks around CJK, which do not render", () => {
+ // The markers need a word boundary, and a CJK run has none — `*中文*` would arrive as
+ // asterisks around Chinese.
+ expect(wechatMarkdownOf("*stress*")).toBe("*stress*");
+ expect(wechatMarkdownOf("*重要*")).toBe("重要");
+ expect(wechatMarkdownOf("*mixed 中文*")).toBe("mixed 中文");
+ // Bold is unaffected: `**` renders on both sides of the boundary question.
+ expect(wechatMarkdownOf("**重要**")).toBe("**重要**");
+ });
+
+ it("turns an inline image into a link rather than dropping the URL it named", () => {
+ expect(wechatMarkdownOf("![a chart](https://x.com/c.png)")).toBe(
+ "[a chart](https://x.com/c.png)",
+ );
+ // Nameless: the URL is its own label, which is better than an empty one.
+ expect(wechatMarkdownOf("![](https://x.com/c.png)")).toBe(
+ "[https://x.com/c.png](https://x.com/c.png)",
+ );
+ });
+
+ it("escapes literal markup outside code, and never inside it", () => {
+ expect(wechatMarkdownOf("literal * and _ and ~ and [x]")).toBe(
+ "literal \\* and \\_ and \\~ and \\[x\\]",
+ );
+ // `#` means something only at the head of a line.
+ expect(wechatMarkdownOf("issue \\#12 and a > b")).toBe("issue #12 and a > b");
+ expect(wechatMarkdownOf("\\# not a heading")).toBe("\\# not a heading");
+ // Inside a fence the markers ARE what makes the content literal: a backslash there
+ // would land in code the reader is meant to copy.
+ expect(wechatMarkdownOf("```\nrm -rf *_[x]\n```")).toBe("```\nrm -rf *_[x]\n```");
+ });
+
+ it("keeps an unopenable link's label and drops only its clickability", () => {
+ expect(wechatMarkdownOf("[click](javascript:alert(1))")).toBe("click");
+ });
+});
+
// ---------------------------------------------------------------------------
// Inbound file paths quoted back out
// ---------------------------------------------------------------------------
@@ -389,6 +483,7 @@ describe("chunkMarkdown", () => {
expect(() => telegramHtmlOf(chunk)).not.toThrow();
expect(() => feishuMarkdownOf(chunk)).not.toThrow();
expect(() => qqMarkdownOf(chunk)).not.toThrow();
+ expect(() => wechatMarkdownOf(chunk)).not.toThrow();
}
});
});
diff --git a/packages/server/test/messaging-wechat-scan.test.ts b/packages/server/test/messaging-wechat-scan.test.ts
new file mode 100644
index 00000000..5b8d9336
--- /dev/null
+++ b/packages/server/test/messaging-wechat-scan.test.ts
@@ -0,0 +1,571 @@
+/**
+ * WeChat scan-to-connect — the only way this channel is ever bound, so these tests cover
+ * more than QQ's equivalent: there is no typed fallback behind them.
+ *
+ * Three layers, each fake at a different depth on purpose. The protocol layer drives the
+ * real transport against a stubbed `globalThis.fetch`, because the request shape and the
+ * status vocabulary are exactly what a seam fake would stop testing. The service layer uses
+ * a fake transport, because what it owns is a state machine — claims, the pairing code, the
+ * IDC redirect, the TTL — that no wire can express. The route layer uses the same fake, and
+ * asserts the one invariant that spans all three: the platform's poll handle, which is what
+ * collects a bot token, never appears in anything the browser is given.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { WeChatScanPollResponse, WeChatScanStartResponse } from "../src/api/types.js";
+import type { SessionRow } from "../src/db/repos/sessions.js";
+import { WECHAT_API_BASE } from "../src/runtime/messaging/wechat-api.js";
+import type {
+ WeChatScanPollResult,
+ WeChatScanTransport,
+} from "../src/runtime/messaging/wechat-scan.js";
+import {
+ WECHAT_SCAN_TASK_TTL_MS,
+ WeChatScanService,
+ createWeChatScanTransport,
+} from "../src/runtime/messaging/wechat-scan.js";
+import type {
+ WeChatBotClient,
+ WeChatCredentials,
+ WeChatTransport,
+} from "../src/runtime/messaging/wechat-api.js";
+import { apiClient, createTestApp, provisionUser } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+const SID = "session-2026-08-28-10-00-00-w9000001";
+const SID2 = "session-2026-08-28-10-00-01-w9000002";
+const PROJECT = "birder-default_project";
+const SCAN = (sid: string) => `/api/sessions/${sid}/messaging/wechat/scan`;
+
+const BOT_ID = "bot_9001";
+const BOT_TOKEN = "scan-issued-token-XYZ";
+const SCANNER = "ilink_user_aaa";
+/** The platform's poll handle. It turns into a bot token, so no response may carry it. */
+const QRCODE = "qrcode-handle-SECRET";
+
+function sessionRowOf(sessionId: string, projectId: string): SessionRow {
+ return {
+ sessionId,
+ projectId,
+ agentId: "default_agent",
+ provider: "custom",
+ modelId: "m1",
+ workspace: "/tmp/w",
+ approvalMode: "allow-all",
+ title: null,
+ createdAt: new Date().toISOString(),
+ lastActiveAt: new Date().toISOString(),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// The protocol, against a stubbed fetch
+// ---------------------------------------------------------------------------
+
+function jsonResponse(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "content-type": "application/json" },
+ });
+}
+
+async function withFetch<T>(
+ answer: (url: string, init: RequestInit | undefined) => Response,
+ body: (urls: string[]) => Promise<T>,
+): Promise<T> {
+ const urls: string[] = [];
+ const original = globalThis.fetch;
+ globalThis.fetch = (async (input: unknown, init?: RequestInit) => {
+ urls.push(String(input));
+ return answer(String(input), init);
+ }) as typeof fetch;
+ try {
+ return await body(urls);
+ } finally {
+ globalThis.fetch = original;
+ }
+}
+
+describe("the WeChat scan protocol", () => {
+ it("asks for a code under the bot type and offers no local tokens", async () => {
+ let sentBody = "";
+ await withFetch(
+ (_url, init) => {
+ sentBody = String(init?.body ?? "");
+ return jsonResponse({ qrcode: QRCODE, qrcode_img_content: "https://weixin.qq.com/q/abc" });
+ },
+ async (urls) => {
+ const res = await createWeChatScanTransport().createQrCode();
+ expect(urls[0]).toBe(`${WECHAT_API_BASE}/ilink/bot/get_bot_qrcode?bot_type=3`);
+ // Offering the tokens this server already holds would hand one binding's credential
+ // to another binding's flow.
+ expect(JSON.parse(sentBody)).toEqual({ local_token_list: [] });
+ // The handle and the URL are different things: the URL goes into the QR, the handle
+ // collects the token.
+ expect(res.qrcode).toBe(QRCODE);
+ expect(res.qrUrl).toBe("https://weixin.qq.com/q/abc");
+ },
+ );
+ });
+
+ it("maps every status the platform reports onto one the browser can render", async () => {
+ const cases: Array<[string, WeChatScanPollResult["status"]]> = [
+ ["wait", "pending"],
+ ["scaned", "scanned"],
+ ["scaned_but_redirect", "scanned"],
+ ["need_verifycode", "need_verify_code"],
+ ["verify_code_blocked", "blocked"],
+ ["expired", "expired"],
+ ["binded_redirect", "already_bound"],
+ // A state this build has not heard of is not a reason to take a live code down.
+ ["something_new_from_tencent", "pending"],
+ ];
+ for (const [wire, expected] of cases) {
+ await withFetch(
+ () => jsonResponse({ status: wire }),
+ async () => {
+ const res = await createWeChatScanTransport().pollQrStatus({
+ baseUrl: WECHAT_API_BASE,
+ qrcode: QRCODE,
+ });
+ expect(res.status).toBe(expected);
+ },
+ );
+ }
+ });
+
+ it("puts the pairing code on the status query, which is where the platform takes it", async () => {
+ await withFetch(
+ () => jsonResponse({ status: "scaned" }),
+ async (urls) => {
+ await createWeChatScanTransport().pollQrStatus({
+ baseUrl: WECHAT_API_BASE,
+ qrcode: QRCODE,
+ verifyCode: "8421",
+ });
+ expect(urls[0]).toContain("verify_code=8421");
+ expect(urls[0]).toContain(`qrcode=${encodeURIComponent(QRCODE)}`);
+ },
+ );
+ });
+
+ it("reads a confirmed scan's credentials, and the API host it assigned", async () => {
+ await withFetch(
+ () =>
+ jsonResponse({
+ status: "confirmed",
+ bot_token: BOT_TOKEN,
+ ilink_bot_id: BOT_ID,
+ ilink_user_id: SCANNER,
+ baseurl: "https://idc-7.ilinkai.weixin.qq.com",
+ }),
+ async () => {
+ const res = await createWeChatScanTransport().pollQrStatus({
+ baseUrl: WECHAT_API_BASE,
+ qrcode: QRCODE,
+ });
+ expect(res.bot).toEqual({
+ botId: BOT_ID,
+ botToken: BOT_TOKEN,
+ baseUrl: "https://idc-7.ilinkai.weixin.qq.com",
+ userId: SCANNER,
+ });
+ },
+ );
+ });
+
+ it("falls back to the entry host when a confirmed scan names none", async () => {
+ await withFetch(
+ () => jsonResponse({ status: "confirmed", bot_token: BOT_TOKEN, ilink_bot_id: BOT_ID }),
+ async () => {
+ const res = await createWeChatScanTransport().pollQrStatus({
+ baseUrl: WECHAT_API_BASE,
+ qrcode: QRCODE,
+ });
+ expect(res.bot?.baseUrl).toBe(WECHAT_API_BASE);
+ },
+ );
+ });
+
+ it("refuses a confirmation that carried no credentials rather than storing a blank one", async () => {
+ await withFetch(
+ () => jsonResponse({ status: "confirmed", ilink_bot_id: BOT_ID }),
+ async () => {
+ await expect(
+ createWeChatScanTransport().pollQrStatus({ baseUrl: WECHAT_API_BASE, qrcode: QRCODE }),
+ ).rejects.toThrow(/no credentials/);
+ },
+ );
+ });
+
+ it("reads a long poll that closed with nothing to say as pending, not as a failure", async () => {
+ // A window that expires and a client-side timeout are the same thing here: nothing
+ // changed, ask again. Only that keeps a transient close from taking the code down.
+ const original = globalThis.fetch;
+ globalThis.fetch = (async () => {
+ const err = new Error("aborted");
+ err.name = "TimeoutError";
+ throw err;
+ }) as typeof fetch;
+ try {
+ const res = await createWeChatScanTransport().pollQrStatus({
+ baseUrl: WECHAT_API_BASE,
+ qrcode: QRCODE,
+ });
+ expect(res).toEqual({ status: "pending" });
+ } finally {
+ globalThis.fetch = original;
+ }
+ });
+});
+
+// ---------------------------------------------------------------------------
+// The service, over a fake transport
+// ---------------------------------------------------------------------------
+
+/** Records what the service asked for, and answers whatever the test set. */
+class FakeScanTransport implements WeChatScanTransport {
+ /** The handles handed out, newest last. */
+ readonly handles: string[] = [];
+ /** Every poll the service made, in order. */
+ readonly polls: Array<{ baseUrl: string; qrcode: string; verifyCode?: string }> = [];
+ /** What the next poll answers. */
+ next: WeChatScanPollResult = { status: "pending" };
+ /** Resolves each poll only when the test says so, for the overlapping-poll case. */
+ gate: (() => void) | null = null;
+ createFailure: Error | null = null;
+
+ async createQrCode(): Promise<{ qrcode: string; qrUrl: string }> {
+ if (this.createFailure !== null) throw this.createFailure;
+ const qrcode = `${QRCODE}-${this.handles.length}`;
+ this.handles.push(qrcode);
+ return { qrcode, qrUrl: `https://weixin.qq.com/q/${this.handles.length}` };
+ }
+
+ async pollQrStatus(args: {
+ baseUrl: string;
+ qrcode: string;
+ verifyCode?: string;
+ }): Promise<WeChatScanPollResult> {
+ this.polls.push({ ...args });
+ if (this.gate !== null) {
+ await new Promise<void>((resolve) => {
+ this.gate = resolve;
+ });
+ }
+ return this.next;
+ }
+
+ lastHandle(): string {
+ const handle = this.handles.at(-1);
+ if (handle === undefined) throw new Error("no fake wechat code was created");
+ return handle;
+ }
+}
+
+const completed: WeChatScanPollResult = {
+ status: "completed",
+ bot: { botId: BOT_ID, botToken: BOT_TOKEN, baseUrl: WECHAT_API_BASE, userId: SCANNER },
+};
+
+describe("the WeChat scan service", () => {
+ it("hands out a handle of its own, never the one that collects the token", async () => {
+ const transport = new FakeScanTransport();
+ const service = new WeChatScanService(transport);
+ const started = await service.start(SID);
+ expect(started.taskId).not.toBe(transport.lastHandle());
+ expect(started.qrUrl).toContain("https://weixin.qq.com/q/");
+ expect(started.pollMs).toBeGreaterThan(0);
+ });
+
+ it("answers an overlapping poll `pending` instead of refusing it, the poll being long", async () => {
+ // QQ's fast poll refuses an overlap because a second one could bind twice; here one
+ // upstream call spans several of the client's intervals, and refusing would surface the
+ // normal rhythm as an error.
+ const transport = new FakeScanTransport();
+ const service = new WeChatScanService(transport);
+ const started = await service.start(SID);
+ transport.gate = () => {};
+ const inFlight = service.poll(SID, started.taskId);
+ expect(await service.poll(SID, started.taskId)).toEqual({ status: "pending" });
+ // Exactly one upstream call was made for the two client polls.
+ expect(transport.polls).toHaveLength(1);
+ transport.gate!();
+ await inFlight;
+ });
+
+ it("holds a pairing code for the next poll, then stops resending it once it is accepted", async () => {
+ const transport = new FakeScanTransport();
+ const service = new WeChatScanService(transport);
+ const started = await service.start(SID);
+ transport.next = { status: "need_verify_code" };
+ expect(await service.poll(SID, started.taskId)).toEqual({ status: "need_verify_code" });
+ expect(transport.polls[0]!.verifyCode).toBeUndefined();
+
+ expect(service.submitVerifyCode(SID, started.taskId, "8421")).toBe(true);
+ transport.next = { status: "scanned" };
+ expect(await service.poll(SID, started.taskId)).toEqual({ status: "scanned" });
+ expect(transport.polls[1]!.verifyCode).toBe("8421");
+ // Accepted: resubmitting it would be rejected as a stale code on every later poll.
+ await service.poll(SID, started.taskId);
+ expect(transport.polls[2]!.verifyCode).toBeUndefined();
+ });
+
+ it("refuses a pairing code for a task this Session did not start", async () => {
+ const service = new WeChatScanService(new FakeScanTransport());
+ const started = await service.start(SID);
+ expect(service.submitVerifyCode(SID2, started.taskId, "8421")).toBe(false);
+ expect(service.submitVerifyCode(SID, "not-a-task", "8421")).toBe(false);
+ });
+
+ it("follows an IDC redirect without reporting it as a state of its own", async () => {
+ const transport = new FakeScanTransport();
+ const service = new WeChatScanService(transport);
+ const started = await service.start(SID);
+ transport.next = { status: "scanned", redirectHost: "idc-7.ilinkai.weixin.qq.com" };
+ // What the browser hears is that the code was scanned; the host switch is internal.
+ expect(await service.poll(SID, started.taskId)).toEqual({ status: "scanned" });
+ transport.next = { status: "pending" };
+ await service.poll(SID, started.taskId);
+ expect(transport.polls[0]!.baseUrl).toBe(WECHAT_API_BASE);
+ expect(transport.polls[1]!.baseUrl).toBe("https://idc-7.ilinkai.weixin.qq.com");
+ });
+
+ it("spends the task on a completed scan, so a replay binds nothing", async () => {
+ const transport = new FakeScanTransport();
+ const service = new WeChatScanService(transport);
+ const started = await service.start(SID);
+ transport.next = completed;
+ expect(await service.poll(SID, started.taskId)).toEqual({
+ status: "completed",
+ bot: completed.bot,
+ });
+ expect(await service.poll(SID, started.taskId)).toBeNull();
+ });
+
+ it("spends the task on every end the platform declares, not only on success", async () => {
+ for (const status of ["expired", "blocked", "already_bound"] as const) {
+ const transport = new FakeScanTransport();
+ const service = new WeChatScanService(transport);
+ const started = await service.start(SID);
+ transport.next = { status };
+ expect(await service.poll(SID, started.taskId)).toEqual({ status });
+ // Nothing further can come of this handle: polling it again is not a way back.
+ expect(await service.poll(SID, started.taskId)).toBeNull();
+ }
+ });
+
+ it("keeps a task pollable when the request itself failed", async () => {
+ const transport = new FakeScanTransport();
+ const service = new WeChatScanService(transport);
+ const started = await service.start(SID);
+ transport.pollQrStatus = async () => {
+ throw new Error("platform hiccup");
+ };
+ await expect(service.poll(SID, started.taskId)).rejects.toThrow("platform hiccup");
+ // A failed request resolved nothing; the user's code is still on screen.
+ transport.pollQrStatus = async () => ({ status: "pending" });
+ expect(await service.poll(SID, started.taskId)).toEqual({ status: "pending" });
+ });
+
+ it("keeps one Session's tasks out of another's reach", async () => {
+ const service = new WeChatScanService(new FakeScanTransport());
+ const started = await service.start(SID);
+ expect(await service.poll(SID2, started.taskId)).toBeNull();
+ service.cancel(SID2, started.taskId);
+ expect(await service.poll(SID, started.taskId)).toEqual({ status: "pending" });
+ service.cancel(SID, started.taskId);
+ expect(await service.poll(SID, started.taskId)).toBeNull();
+ });
+
+ it("evicts only the caller's own oldest tasks when it fills its ceiling", async () => {
+ const service = new WeChatScanService(new FakeScanTransport());
+ const victim = await service.start(SID2);
+ const own: string[] = [];
+ for (let i = 0; i < 6; i += 1) own.push((await service.start(SID)).taskId);
+ expect(await service.poll(SID, own[0]!)).toBeNull();
+ expect(await service.poll(SID, own.at(-1)!)).toEqual({ status: "pending" });
+ // Filling one Session's ceiling takes a code away from nobody else.
+ expect(await service.poll(SID2, victim.taskId)).toEqual({ status: "pending" });
+ });
+
+ it("sweeps a task nobody came back for without waiting for the next scan", async () => {
+ vi.useFakeTimers();
+ try {
+ let now = 1_000_000;
+ const service = new WeChatScanService(new FakeScanTransport(), { now: () => now });
+ const abandoned = await service.start(SID);
+ now += WECHAT_SCAN_TASK_TTL_MS + 1;
+ await vi.advanceTimersByTimeAsync(WECHAT_SCAN_TASK_TTL_MS + 1);
+ // Gone, not merely lapsed: only a task the sweep already dropped reads as unknown.
+ expect(await service.poll(SID, abandoned.taskId)).toBeNull();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("forgets a Session's tasks wholesale", async () => {
+ const service = new WeChatScanService(new FakeScanTransport());
+ const started = await service.start(SID);
+ service.cancelSession(SID);
+ expect(await service.poll(SID, started.taskId)).toBeNull();
+ });
+});
+
+// ---------------------------------------------------------------------------
+// The routes
+// ---------------------------------------------------------------------------
+
+/**
+ * A connector transport whose poll never returns: the scan-route suite enables a connection
+ * once, and what it is testing is the enable's REFUSAL of a scan, not anything inbound.
+ */
+function silentTransport(): WeChatTransport {
+ const client: WeChatBotClient = {
+ checkCredentials: async () => {},
+ getUpdates: ({ signal }) =>
+ new Promise((_resolve, reject) => {
+ signal.addEventListener("abort", () => reject(new Error("closed")), { once: true });
+ }),
+ sendText: async () => {},
+ sendImage: async () => {},
+ sendFile: async () => {},
+ fetchMedia: async () => Buffer.alloc(0),
+ };
+ return { createClient: (_creds: WeChatCredentials) => client };
+}
+
+describe("wechat scan routes", () => {
+ let t: TestApp;
+ let api: ReturnType<typeof apiClient>;
+ let transport: FakeScanTransport;
+
+ beforeEach(async () => {
+ transport = new FakeScanTransport();
+ // A fake connector transport too: one test enables the connection, and the poll loop
+ // behind it would otherwise open a real request to the platform.
+ t = await createTestApp({
+ wechatScanTransport: transport,
+ wechatTransport: silentTransport(),
+ wechatRetryDelayMs: () => 0,
+ });
+ const { cookie } = await provisionUser(t.app, "birder");
+ api = apiClient(t.app, cookie);
+ t.deps.sessionsRepo.insert(sessionRowOf(SID, PROJECT));
+ });
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ it("hands the browser a task, a URL and an interval — never the handle behind them", async () => {
+ const res = await api.post(SCAN(SID), {});
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as WeChatScanStartResponse;
+ expect(body.qrUrl).toContain("https://weixin.qq.com/q/");
+ expect(body.pollMs).toBeGreaterThan(0);
+ // The handle polls a bot token out: nothing in this response may carry it.
+ expect(JSON.stringify(body)).not.toContain(transport.lastHandle());
+ expect(body.taskId).not.toBe(transport.lastHandle());
+ });
+
+ it("a completed poll saves the binding with the bot id as the account, and returns no token", async () => {
+ const start = (await (await api.post(SCAN(SID), {})).json()) as WeChatScanStartResponse;
+ const pending = (await (
+ await api.post(`${SCAN(SID)}/poll`, { taskId: start.taskId })
+ ).json()) as WeChatScanPollResponse;
+ expect(pending).toEqual({ status: "pending" });
+
+ transport.next = completed;
+ const res = await api.post(`${SCAN(SID)}/poll`, { taskId: start.taskId });
+ expect(res.status).toBe(200);
+ const done = (await res.json()) as WeChatScanPollResponse;
+ expect(done.status).toBe("completed");
+ expect(done.botId).toBe(BOT_ID);
+ expect(done.binding?.channel).toBe("wechat");
+ expect(done.binding?.botTokenMasked).toBe("scan…-XYZ");
+ // The plaintext went to storage without passing back through the browser.
+ expect(JSON.stringify(done)).not.toContain(BOT_TOKEN);
+
+ const stored = t.deps.messagingRepo.find(SID, "wechat")!;
+ expect(stored.accountId).toBe(BOT_ID);
+ expect(stored.config).toEqual({
+ botId: BOT_ID,
+ botToken: BOT_TOKEN,
+ baseUrl: WECHAT_API_BASE,
+ // The scanner's id is stored too: the credential probe is made on its behalf.
+ userId: SCANNER,
+ });
+ // Saving is all it does: enabling stays the separate, exclusive act.
+ expect(stored.enabled).toBe(false);
+
+ // The task is spent — a replay is a 404, not a second bind.
+ const replay = await api.post(`${SCAN(SID)}/poll`, { taskId: start.taskId });
+ expect(replay.status).toBe(404);
+ expect(((await replay.json()) as { error: { code: string } }).error.code).toBe(
+ "wechat_scan_task_unknown",
+ );
+ });
+
+ it("reports a pairing code, takes it, and 404s one for a task that is gone", async () => {
+ const start = (await (await api.post(SCAN(SID), {})).json()) as WeChatScanStartResponse;
+ transport.next = { status: "need_verify_code" };
+ const asked = (await (
+ await api.post(`${SCAN(SID)}/poll`, { taskId: start.taskId })
+ ).json()) as WeChatScanPollResponse;
+ expect(asked.status).toBe("need_verify_code");
+
+ const ok = await api.post(`${SCAN(SID)}/verify`, { taskId: start.taskId, verifyCode: "8421" });
+ expect(ok.status).toBe(204);
+ transport.next = { status: "pending" };
+ await api.post(`${SCAN(SID)}/poll`, { taskId: start.taskId });
+ expect(transport.polls.at(-1)!.verifyCode).toBe("8421");
+
+ const gone = await api.post(`${SCAN(SID)}/verify`, { taskId: "nope", verifyCode: "1111" });
+ expect(gone.status).toBe(404);
+ const blank = await api.post(`${SCAN(SID)}/verify`, { taskId: start.taskId, verifyCode: " " });
+ expect(blank.status).toBe(400);
+ });
+
+ it("refuses to start a scan while the connection is live", async () => {
+ const start = (await (await api.post(SCAN(SID), {})).json()) as WeChatScanStartResponse;
+ transport.next = completed;
+ await api.post(`${SCAN(SID)}/poll`, { taskId: start.taskId });
+ expect(
+ (await api.post(`/api/sessions/${SID}/messaging/wechat/state`, { enabled: true })).status,
+ ).toBe(200);
+
+ // A scan rewrites the whole credential and would point a live connector at whatever was
+ // scanned: a server rule, not just a greyed-out button.
+ const refused = await api.post(SCAN(SID), {});
+ expect(refused.status).toBe(409);
+ expect(((await refused.json()) as { error: { code: string } }).error.code).toBe(
+ "messaging_disable_before_scan",
+ );
+ });
+
+ it("surfaces a platform failure as a 502 rather than an empty panel", async () => {
+ transport.createFailure = new Error("WeChat scan request failed: HTTP 503");
+ const res = await api.post(SCAN(SID), {});
+ expect(res.status).toBe(502);
+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe(
+ "wechat_scan_failed",
+ );
+ });
+
+ it("cancels a scan the user walked away from", async () => {
+ const start = (await (await api.post(SCAN(SID), {})).json()) as WeChatScanStartResponse;
+ expect((await api.post(`${SCAN(SID)}/cancel`, { taskId: start.taskId })).status).toBe(204);
+ expect((await api.post(`${SCAN(SID)}/poll`, { taskId: start.taskId })).status).toBe(404);
+ });
+
+ it("is owner-only throughout: the flow ends in a stored credential", async () => {
+ const { cookie } = await provisionUser(t.app, "guest");
+ const guest = apiClient(t.app, cookie);
+ // A non-member cannot even see the Session, so the refusal is the 404 that leaks nothing.
+ expect((await guest.post(SCAN(SID), {})).status).toBe(404);
+ expect((await guest.post(`${SCAN(SID)}/poll`, { taskId: "x" })).status).toBe(404);
+ expect((await guest.post(`${SCAN(SID)}/verify`, { taskId: "x", verifyCode: "1" })).status).toBe(
+ 404,
+ );
+ expect((await guest.post(`${SCAN(SID)}/cancel`, { taskId: "x" })).status).toBe(404);
+ });
+});
diff --git a/packages/server/test/messaging-wechat-transport.test.ts b/packages/server/test/messaging-wechat-transport.test.ts
new file mode 100644
index 00000000..5794bfec
--- /dev/null
+++ b/packages/server/test/messaging-wechat-transport.test.ts
@@ -0,0 +1,707 @@
+/**
+ * The WeChat production adapter — the half of the channel that talks to Tencent.
+ *
+ * messaging-wechat.test.ts drives the connector and its routes over a fake transport, which
+ * leaves everything under that seam unexercised: the request envelope and its headers, the
+ * long poll's cursor, the reduction of the wire's message shape to the connector's event, and
+ * the whole CDN media path — a pre-signed upload of AES-128-ECB ciphertext in one direction
+ * and a decrypt in the other. Those are where a platform failure actually reaches this
+ * product, so they get their own file (the split messaging-qq-transport.test.ts makes).
+ *
+ * Nothing here opens a socket. `globalThis.fetch` is stubbed the way that suite stubs it —
+ * a test hook rather than a module mock, because this suite shares one module registry
+ * across files and `vi.mock` would leak into every later one (see vitest.config.ts).
+ */
+import { describe, expect, it } from "vitest";
+import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
+import { MessagingMediaTooLargeError } from "../src/runtime/messaging/media.js";
+import type { WeChatCredentials } from "../src/runtime/messaging/wechat-api.js";
+import {
+ DRAIN_TIMEOUT_MS,
+ LONG_POLL_TIMEOUT_MS,
+ WECHAT_API_BASE,
+ WECHAT_STALE_TOKEN_CODE,
+ WECHAT_VIDEO_FILE_NAME,
+ WeChatApiError,
+ createWeChatTransport,
+ normalizeWeChatMessage,
+ parseWeChatAesKey,
+} from "../src/runtime/messaging/wechat-api.js";
+
+const CREDS: WeChatCredentials = {
+ botId: "bot_9001",
+ botToken: "wx-bot-token-ABCD-1234",
+ baseUrl: WECHAT_API_BASE,
+ userId: "ilink_user_aaa",
+};
+
+const USER = "ilink_user_aaa";
+
+/** One recorded request against the stubbed fetch. */
+interface Call {
+ url: string;
+ method: string;
+ body: string;
+ headers: Headers;
+}
+
+function jsonResponse(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "content-type": "application/json" },
+ });
+}
+
+/**
+ * Installs a fetch stub for the run of `body`, and hands it the calls it recorded.
+ *
+ * `answer` returns the response for one call; returning null means "the default", which is
+ * an empty success — enough for the calls a test makes on its way to the one it is about.
+ */
+async function withFetch<T>(
+ answer: (call: Call, index: number) => Response | null,
+ body: (calls: Call[]) => Promise<T>,
+): Promise<T> {
+ const calls: Call[] = [];
+ const original = globalThis.fetch;
+ globalThis.fetch = (async (input: unknown, init?: RequestInit) => {
+ const call: Call = {
+ url: String(input),
+ method: init?.method ?? "GET",
+ body: typeof init?.body === "string" ? init.body : "",
+ headers: new Headers(init?.headers),
+ };
+ // The CDN upload sends bytes rather than a string; recorded separately below.
+ if (init?.body instanceof Uint8Array) uploads.push(Buffer.from(init.body));
+ calls.push(call);
+ const answered = answer(call, calls.length - 1);
+ if (answered !== null) return answered;
+ return jsonResponse({ ret: 0 });
+ }) as typeof fetch;
+ try {
+ return await body(calls);
+ } finally {
+ globalThis.fetch = original;
+ }
+}
+
+/** Bytes POSTed to a CDN upload URL during the current `withFetch`. */
+let uploads: Buffer[] = [];
+
+const defaults = (): null => null;
+
+/** The abort signal a poll takes; every test that is not about cancellation passes a live one. */
+const live = (): AbortSignal => new AbortController().signal;
+
+function client() {
+ return createWeChatTransport().createClient(CREDS);
+}
+
+describe("the WeChat request envelope", () => {
+ it("authenticates every call the same way and identifies the client", async () => {
+ await withFetch(defaults, async (calls) => {
+ await client().checkCredentials();
+ const call = calls[0]!;
+ expect(call.url).toBe(`${WECHAT_API_BASE}/ilink/bot/getconfig`);
+ expect(call.method).toBe("POST");
+ expect(call.headers.get("authorization")).toBe(`Bearer ${CREDS.botToken}`);
+ // The protocol's own auth-scheme name, not a bearer convention this server invented.
+ expect(call.headers.get("authorizationtype")).toBe("ilink_bot_token");
+ expect(call.headers.get("ilink-app-id")).toBe("bot");
+ // A fresh random uint32, base64 of its decimal digits — present and decodable.
+ const uin = call.headers.get("x-wechat-uin");
+ expect(uin).not.toBeNull();
+ expect(Buffer.from(uin!, "base64").toString("utf8")).toMatch(/^\d+$/);
+ // The probe is `getconfig`, which reads: polling would advance the cursor the poll
+ // loop is about to read, and a probe that eats a message is not a probe.
+ expect(JSON.parse(call.body)).toMatchObject({ ilink_user_id: USER });
+ expect(JSON.parse(call.body).base_info.bot_agent).toContain("PenguinHarness");
+ });
+ });
+
+ it("raises the platform's own failure code, and never the credential with it", async () => {
+ await withFetch(
+ () => jsonResponse({ ret: -14, errmsg: "session timeout" }),
+ async () => {
+ const err = await client()
+ .checkCredentials()
+ .catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(WeChatApiError);
+ expect((err as WeChatApiError).ret).toBe(-14);
+ expect((err as Error).message).toContain("session timeout");
+ expect((err as Error).message).not.toContain(CREDS.botToken);
+ },
+ );
+ });
+
+ it("carries an HTTP failure's body through, which is what tells a revoked token from a wrong host", async () => {
+ await withFetch(
+ () => new Response("invalid bot token", { status: 401 }),
+ async () => {
+ const err = await client()
+ .checkCredentials()
+ .catch((e: unknown) => e);
+ expect((err as Error).message).toContain("401");
+ expect((err as Error).message).toContain("invalid bot token");
+ },
+ );
+ });
+
+ it("probes even without a scanned user identity: the auth layer is what it reads", async () => {
+ // The user id belongs to the call BEHIND the credential, and that call's outcome is not
+ // what this probe reports (see the credential-probe suite below).
+ await withFetch(defaults, async (calls) => {
+ const bare = createWeChatTransport().createClient({ ...CREDS, userId: "" });
+ await expect(bare.checkCredentials()).resolves.toBeUndefined();
+ expect(calls).toHaveLength(1);
+ });
+ });
+});
+
+describe("the credential probe", () => {
+ it("passes on a good token whose typing-ticket call has no conversation to work with", async () => {
+ // The reported bug. `getconfig` mints a typing ticket for a CONVERSATION, so a bot nobody
+ // has messaged yet answers this even though its token is fine and its sends work. Reading
+ // that as a bad credential sent the user to re-scan a token that was never the problem.
+ await withFetch(
+ () => jsonResponse({ ret: 1, errmsg: "GetTypingTicket rpc failed" }),
+ async () => {
+ await expect(client().checkCredentials()).resolves.toBeUndefined();
+ },
+ );
+ });
+
+ it("fails when the credential itself is refused", async () => {
+ for (const status of [401, 403]) {
+ await withFetch(
+ () => new Response("invalid bot token", { status }),
+ async () => {
+ const err = await client()
+ .checkCredentials()
+ .catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(WeChatApiError);
+ expect((err as WeChatApiError).authenticated).toBe(false);
+ expect((err as Error).message).toContain(String(status));
+ },
+ );
+ }
+ });
+
+ it("fails on a stale token, which arrives as a business code rather than a status", async () => {
+ // The one non-zero envelope code that IS about the credential: everything else means the
+ // request got past it.
+ await withFetch(
+ () => jsonResponse({ errcode: WECHAT_STALE_TOKEN_CODE, errmsg: "session timeout" }),
+ async () => {
+ const err = await client()
+ .checkCredentials()
+ .catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(WeChatApiError);
+ expect((err as WeChatApiError).authenticated).toBe(false);
+ },
+ );
+ });
+
+ it("fails when the request never arrived, which proves nothing either way", async () => {
+ const original = globalThis.fetch;
+ globalThis.fetch = (async () => {
+ throw new Error("getaddrinfo ENOTFOUND");
+ }) as typeof fetch;
+ try {
+ await expect(client().checkCredentials()).rejects.toThrow(/ENOTFOUND/);
+ } finally {
+ globalThis.fetch = original;
+ }
+ });
+
+ it("never probes with the update poll, which would eat a message", async () => {
+ // `getupdates` would prove the credential too, and advance the cursor the connector is
+ // about to read — so the messages it returned would be dropped and never delivered.
+ await withFetch(defaults, async (calls) => {
+ await client().checkCredentials();
+ expect(calls).toHaveLength(1);
+ expect(calls[0]!.url).toContain("/getconfig");
+ expect(calls.some((c) => c.url.includes("getupdates"))).toBe(false);
+ });
+ });
+});
+
+describe("the long poll", () => {
+ const textMessage = (id: number, text: string) => ({
+ message_id: id,
+ from_user_id: USER,
+ message_type: 1,
+ context_token: "ctx-1",
+ item_list: [{ type: 1, text_item: { text } }],
+ });
+
+ it("sends the cursor it was given and reports the one it got back", async () => {
+ await withFetch(
+ (call) =>
+ call.url.endsWith("/getupdates")
+ ? jsonResponse({ msgs: [textMessage(7, "hello")], get_updates_buf: "cursor-2" })
+ : null,
+ async (calls) => {
+ const res = await client().getUpdates({ cursor: "cursor-1", signal: live() });
+ expect(JSON.parse(calls[0]!.body).get_updates_buf).toBe("cursor-1");
+ expect(res.cursor).toBe("cursor-2");
+ expect(res.messages).toEqual([
+ {
+ userId: USER,
+ messageId: "7",
+ text: "hello",
+ contextToken: "ctx-1",
+ images: [],
+ files: [],
+ },
+ ]);
+ },
+ );
+ });
+
+ it("resolves a quiet window as empty rather than as an outage", async () => {
+ // A long poll with nothing to report holds its request until the window closes. Treating
+ // that as a failure would put the connection into `error` every quiet minute — and the
+ // cursor is unchanged, so the next call simply asks again from where this one started.
+ const original = globalThis.fetch;
+ // The window closing, as fetch reports it — no real timer is waited on here.
+ globalThis.fetch = (async () => {
+ const err = new Error("The operation was aborted due to timeout");
+ err.name = "TimeoutError";
+ throw err;
+ }) as typeof fetch;
+ try {
+ const res = await client().getUpdates({ cursor: "cursor-7", signal: live() });
+ expect(res).toEqual({ messages: [], cursor: "cursor-7", timedOut: true });
+ } finally {
+ globalThis.fetch = original;
+ }
+ });
+
+ it("still reports a transport fault, which is not a quiet window", async () => {
+ const original = globalThis.fetch;
+ globalThis.fetch = (async () => {
+ throw new Error("getaddrinfo ENOTFOUND");
+ }) as typeof fetch;
+ try {
+ await expect(client().getUpdates({ cursor: "c", signal: live() })).rejects.toThrow(
+ /ENOTFOUND/,
+ );
+ } finally {
+ globalThis.fetch = original;
+ }
+ });
+
+ it("rethrows when the CALLER closed the connection, which is not a quiet window", async () => {
+ // A disable aborts the same way a deadline does, and must reach the poll loop as the end
+ // of the connection rather than as one more empty answer.
+ const controller = new AbortController();
+ const original = globalThis.fetch;
+ globalThis.fetch = (async (_input: unknown, init?: RequestInit) => {
+ controller.abort();
+ const err = new Error("aborted");
+ err.name = "AbortError";
+ void init;
+ throw err;
+ }) as typeof fetch;
+ try {
+ await expect(
+ client().getUpdates({ cursor: "c", signal: controller.signal }),
+ ).rejects.toThrow();
+ } finally {
+ globalThis.fetch = original;
+ }
+ });
+
+ it("gives the drain a shorter deadline than a long poll, so it cannot swallow a live message", async () => {
+ // A drain asks for what the platform is already HOLDING. Parked for the long-poll window
+ // it would instead return the first message a user sends after enabling — which the
+ // connector then discards as backlog.
+ expect(DRAIN_TIMEOUT_MS).toBeLessThan(LONG_POLL_TIMEOUT_MS);
+ });
+
+ it("keeps the old cursor when the response carries none, rather than starting over", async () => {
+ // An empty `get_updates_buf` means "from the beginning" on the next call, which would
+ // replay everything this poll just consumed.
+ await withFetch(
+ () => jsonResponse({ msgs: [] }),
+ async () => {
+ const res = await client().getUpdates({ cursor: "cursor-9", signal: live() });
+ expect(res.cursor).toBe("cursor-9");
+ },
+ );
+ });
+});
+
+describe("inbound normalization", () => {
+ it("drops this bot's own messages, which the stream also carries", async () => {
+ // Relaying them would answer every reply with another reply.
+ expect(
+ normalizeWeChatMessage({
+ message_id: 1,
+ from_user_id: USER,
+ message_type: 2,
+ item_list: [{ type: 1, text_item: { text: "a reply this bot sent" } }],
+ }),
+ ).toBeNull();
+ });
+
+ it("reads a voice message's own transcription as the message's text", async () => {
+ // There is no audio on the connector seam, and WeChat has already done the transcription:
+ // dropping it would answer a spoken question with the not-supported notice.
+ const evt = normalizeWeChatMessage({
+ message_id: 2,
+ from_user_id: USER,
+ message_type: 1,
+ item_list: [
+ { type: 3, voice_item: { media: { full_url: "https://cdn/v" }, text: "read this back" } },
+ ],
+ });
+ expect(evt?.text).toBe("read this back");
+ // The recording itself is not carried anywhere: it is not a file, and nothing decodes it.
+ expect(evt?.files).toEqual([]);
+ });
+
+ it("carries a recording with no transcription as nothing at all", async () => {
+ const evt = normalizeWeChatMessage({
+ message_id: 3,
+ from_user_id: USER,
+ message_type: 1,
+ item_list: [{ type: 3, voice_item: { media: { full_url: "https://cdn/v" } } }],
+ });
+ expect(evt?.text).toBe("");
+ expect(evt?.images).toEqual([]);
+ expect(evt?.files).toEqual([]);
+ });
+
+ it("puts a quoted message in front of the reply that answers it", async () => {
+ // A reply rarely repeats what it is answering, and the model would otherwise read a
+ // bare "yes".
+ const evt = normalizeWeChatMessage({
+ message_id: 4,
+ from_user_id: USER,
+ message_type: 1,
+ item_list: [
+ {
+ type: 1,
+ text_item: { text: "yes, do that" },
+ ref_msg: {
+ title: "Ada",
+ message_item: { type: 1, text_item: { text: "shall I deploy?" } },
+ },
+ },
+ ],
+ });
+ expect(evt?.text).toBe("[quote: Ada | shall I deploy?]\nyes, do that");
+ });
+
+ it("normalizes images, files and videos, preferring the hex key an image item carries", async () => {
+ const hexKey = "00112233445566778899aabbccddeeff";
+ const evt = normalizeWeChatMessage({
+ message_id: 5,
+ from_user_id: USER,
+ message_type: 1,
+ item_list: [
+ {
+ type: 2,
+ // Both keys present: the item's own hex one wins, being the one the platform's
+ // client prefers for images.
+ image_item: {
+ media: { full_url: "https://cdn/i", aes_key: "d3Jvbmcta2V5" },
+ aeskey: hexKey,
+ },
+ },
+ {
+ type: 4,
+ file_item: {
+ media: { full_url: "https://cdn/f", aes_key: "a2V5" },
+ file_name: "report.pdf",
+ },
+ },
+ { type: 5, video_item: { media: { full_url: "https://cdn/v", aes_key: "a2V5" } } },
+ ],
+ });
+ expect(evt?.images).toEqual([
+ { url: "https://cdn/i", aesKey: Buffer.from(hexKey, "hex").toString("base64") },
+ ]);
+ expect(evt?.files).toEqual([
+ { fileName: "report.pdf", media: { url: "https://cdn/f", aesKey: "a2V5" } },
+ // The wire names no file for a video, and `.mp4` is the platform's own answer rather
+ // than a guessed extension.
+ { fileName: WECHAT_VIDEO_FILE_NAME, media: { url: "https://cdn/v", aesKey: "a2V5" } },
+ ]);
+ });
+
+ it("names an unnamed file plainly rather than inventing an extension for it", async () => {
+ const evt = normalizeWeChatMessage({
+ message_id: 6,
+ from_user_id: USER,
+ message_type: 1,
+ item_list: [{ type: 4, file_item: { media: { full_url: "https://cdn/f" } } }],
+ });
+ expect(evt?.files[0]!.fileName).toBe("file");
+ });
+
+ it("skips a media item with no URL rather than minting a handle that cannot be fetched", async () => {
+ const evt = normalizeWeChatMessage({
+ message_id: 7,
+ from_user_id: USER,
+ message_type: 1,
+ item_list: [{ type: 2, image_item: { media: {} } }],
+ });
+ expect(evt?.images).toEqual([]);
+ });
+});
+
+describe("outbound sends", () => {
+ it("sends one item per request and echoes the conversation token", async () => {
+ await withFetch(defaults, async (calls) => {
+ await client().sendText({ userId: USER, text: "hi", contextToken: "ctx-7" });
+ const body = JSON.parse(calls[0]!.body);
+ expect(calls[0]!.url).toBe(`${WECHAT_API_BASE}/ilink/bot/sendmessage`);
+ expect(body.msg.to_user_id).toBe(USER);
+ expect(body.msg.context_token).toBe("ctx-7");
+ expect(body.msg.message_type).toBe(2);
+ expect(body.msg.message_state).toBe(2);
+ // Exactly one item: the platform does not take a two-item list.
+ expect(body.msg.item_list).toEqual([{ type: 1, text_item: { text: "hi" } }]);
+ });
+ });
+
+ it("omits the token entirely when none is known, rather than sending a blank one", async () => {
+ await withFetch(defaults, async (calls) => {
+ await client().sendText({ userId: USER, text: "hi" });
+ expect("context_token" in JSON.parse(calls[0]!.body).msg).toBe(false);
+ });
+ });
+
+ it("uploads an image as ciphertext under a fresh key, then references the CDN's handle", async () => {
+ uploads = [];
+ const plaintext = Buffer.from("PNG-ish bytes, long enough to need padding");
+ await withFetch(
+ (call) => {
+ if (call.url.endsWith("/getuploadurl")) {
+ return jsonResponse({ ret: 0, upload_full_url: "https://cdn.example/upload?sig=abc" });
+ }
+ if (call.url.startsWith("https://cdn.example/upload")) {
+ return new Response(null, {
+ status: 200,
+ headers: { "x-encrypted-param": "dl-param-1" },
+ });
+ }
+ return null;
+ },
+ async (calls) => {
+ await client().sendImage({
+ userId: USER,
+ text: "",
+ file: { fileName: "chart.png", data: plaintext },
+ });
+ const handle = JSON.parse(calls[0]!.body);
+ expect(handle.media_type).toBe(1);
+ expect(handle.to_user_id).toBe(USER);
+ expect(handle.rawsize).toBe(plaintext.length);
+ expect(handle.rawfilemd5).toBe(createHash("md5").update(plaintext).digest("hex"));
+ // PKCS#7 pads to the next full block, always adding at least one byte.
+ expect(handle.filesize).toBe(Math.ceil((plaintext.length + 1) / 16) * 16);
+ // Nothing here has a thumbnail to make, and the platform only demands sizes for one
+ // that is being uploaded.
+ expect(handle.no_need_thumb).toBe(true);
+
+ // The bytes on the wire are ciphertext, and the key the handle declared opens them:
+ // this is the pairing that fails silently if either half drifts.
+ const key = Buffer.from(handle.aeskey as string, "hex");
+ expect(key).toHaveLength(16);
+ const decipher = createDecipheriv("aes-128-ecb", key, null);
+ const round = Buffer.concat([decipher.update(uploads[0]!), decipher.final()]);
+ expect(round.equals(plaintext)).toBe(true);
+ expect(uploads[0]!.equals(plaintext)).toBe(false);
+
+ const item = JSON.parse(calls[2]!.body).msg.item_list[0];
+ expect(item.type).toBe(2);
+ expect(item.image_item.media.encrypt_query_param).toBe("dl-param-1");
+ expect(Buffer.from(item.image_item.media.aes_key as string, "base64").equals(key)).toBe(
+ true,
+ );
+ },
+ );
+ });
+
+ it("sends a file under the FILE media type, with its name and its PLAINTEXT length", async () => {
+ uploads = [];
+ const bytes = Buffer.from("%PDF-1.7 ...");
+ await withFetch(
+ (call) => {
+ if (call.url.endsWith("/getuploadurl")) {
+ return jsonResponse({ upload_full_url: "https://cdn.example/upload" });
+ }
+ if (call.url.startsWith("https://cdn.example/upload")) {
+ return new Response(null, { status: 200, headers: { "x-encrypted-param": "dl-2" } });
+ }
+ return null;
+ },
+ async (calls) => {
+ await client().sendFile({
+ userId: USER,
+ text: "",
+ file: { fileName: "report.pdf", data: bytes },
+ });
+ expect(JSON.parse(calls[0]!.body).media_type).toBe(3);
+ const item = JSON.parse(calls[2]!.body).msg.item_list[0];
+ expect(item.type).toBe(4);
+ expect(item.file_item.file_name).toBe("report.pdf");
+ // The receiving client shows this number, and the ciphertext is a padding block
+ // longer than what the reader actually gets.
+ expect(item.file_item.len).toBe(String(bytes.length));
+ },
+ );
+ });
+
+ it("sends a caption as its own message ahead of the picture", async () => {
+ uploads = [];
+ await withFetch(
+ (call) => {
+ if (call.url.endsWith("/getuploadurl")) {
+ return jsonResponse({ upload_full_url: "https://cdn.example/upload" });
+ }
+ if (call.url.startsWith("https://cdn.example/upload")) {
+ return new Response(null, { status: 200, headers: { "x-encrypted-param": "dl-3" } });
+ }
+ return null;
+ },
+ async (calls) => {
+ await client().sendImage({
+ userId: USER,
+ text: "here is the chart",
+ file: { fileName: "c.png", data: Buffer.from("x") },
+ });
+ // upload handle, CDN, caption, picture — the caption is a message of its own because
+ // one request carries one item.
+ expect(calls).toHaveLength(4);
+ expect(JSON.parse(calls[2]!.body).msg.item_list[0].text_item.text).toBe(
+ "here is the chart",
+ );
+ expect(JSON.parse(calls[3]!.body).msg.item_list[0].type).toBe(2);
+ },
+ );
+ });
+
+ it("fails readably when the platform returns no upload URL, rather than guessing a CDN host", async () => {
+ await withFetch(
+ (call) => (call.url.endsWith("/getuploadurl") ? jsonResponse({ ret: 0 }) : null),
+ async () => {
+ await expect(
+ client().sendFile({
+ userId: USER,
+ text: "",
+ file: { fileName: "a.bin", data: Buffer.from("x") },
+ }),
+ ).rejects.toThrow(/upload URL was not returned/);
+ },
+ );
+ });
+});
+
+describe("inbound media transfers", () => {
+ const KEY = randomBytes(16);
+ const PLAIN = Buffer.from("a picture's worth of bytes, padded on the way out");
+
+ /** The ciphertext the CDN would serve for PLAIN under KEY. */
+ function encrypted(): Buffer {
+ const cipher = createCipheriv("aes-128-ecb", KEY, null);
+ return Buffer.concat([cipher.update(PLAIN), cipher.final()]);
+ }
+
+ it("decrypts a download whose key arrived as raw base64", async () => {
+ await withFetch(
+ () => new Response(encrypted(), { status: 200 }),
+ async () => {
+ const bytes = await client().fetchMedia(
+ { url: "https://cdn/i?sig=secret", aesKey: KEY.toString("base64") },
+ 1_000_000,
+ "The image",
+ );
+ expect(bytes.equals(PLAIN)).toBe(true);
+ },
+ );
+ });
+
+ it("decrypts one whose key arrived as base64 of its hex digits, which files and videos send", async () => {
+ await withFetch(
+ () => new Response(encrypted(), { status: 200 }),
+ async () => {
+ const bytes = await client().fetchMedia(
+ {
+ url: "https://cdn/f",
+ aesKey: Buffer.from(KEY.toString("hex"), "utf8").toString("base64"),
+ },
+ 1_000_000,
+ "The file",
+ );
+ expect(bytes.equals(PLAIN)).toBe(true);
+ },
+ );
+ });
+
+ it("passes an unencrypted download through untouched", async () => {
+ await withFetch(
+ () => new Response(PLAIN, { status: 200 }),
+ async () => {
+ const bytes = await client().fetchMedia({ url: "https://cdn/i" }, 1_000_000, "The image");
+ expect(bytes.equals(PLAIN)).toBe(true);
+ },
+ );
+ });
+
+ it("refuses a transfer past the cap as a size problem, not a failure", async () => {
+ await withFetch(
+ () => new Response(Buffer.alloc(4096), { status: 200 }),
+ async () => {
+ const err = await client()
+ .fetchMedia({ url: "https://cdn/i" }, 1024, "The image")
+ .catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(MessagingMediaTooLargeError);
+ },
+ );
+ });
+
+ it("never puts the signed CDN URL into a failure the chat will read", async () => {
+ // The URL embeds the parameter that authorizes the read.
+ await withFetch(
+ () => new Response("nope", { status: 403 }),
+ async () => {
+ const err = await client()
+ .fetchMedia({ url: "https://cdn/i?sig=SECRET-PARAM" }, 1_000_000, "The image")
+ .catch((e: unknown) => e);
+ expect((err as Error).message).toContain("The image");
+ expect((err as Error).message).not.toContain("SECRET-PARAM");
+ },
+ );
+ });
+
+ it("reports a payload that will not decrypt as arrived-but-unreadable", async () => {
+ await withFetch(
+ () => new Response(Buffer.from("not a multiple of the block size at all"), { status: 200 }),
+ async () => {
+ const err = await client()
+ .fetchMedia(
+ { url: "https://cdn/i", aesKey: KEY.toString("base64") },
+ 1_000_000,
+ "The image",
+ )
+ .catch((e: unknown) => e);
+ expect((err as Error).message).toBe("The image arrived but could not be decrypted");
+ },
+ );
+ });
+});
+
+describe("parseWeChatAesKey", () => {
+ it("accepts both encodings the platform uses and rejects anything else", () => {
+ const raw = randomBytes(16);
+ expect(parseWeChatAesKey(raw.toString("base64")).equals(raw)).toBe(true);
+ const hexEncoded = Buffer.from(raw.toString("hex"), "utf8").toString("base64");
+ expect(parseWeChatAesKey(hexEncoded).equals(raw)).toBe(true);
+ expect(() => parseWeChatAesKey(Buffer.from("short").toString("base64"))).toThrow();
+ });
+});
diff --git a/packages/server/test/messaging-wechat.test.ts b/packages/server/test/messaging-wechat.test.ts
new file mode 100644
index 00000000..cf27b04a
--- /dev/null
+++ b/packages/server/test/messaging-wechat.test.ts
@@ -0,0 +1,745 @@
+/**
+ * WeChat messaging tests — the fourth channel's mirror of messaging.test.ts, over a fake
+ * transport (the wire itself is messaging-wechat-transport.test.ts's).
+ *
+ * Two halves. The ordinary one repeats what the other channels already pin, because the
+ * route wiring is per-channel even where the behaviour is not: token masking, the bot id as
+ * the account identity and the enable-time 409 it collides on, the save/enable split, the
+ * channel-agnostic GET, the credential probe.
+ *
+ * The half that only exists here follows from this channel having NO typed credential. Its
+ * PUT carries preferences alone and refuses to create a binding; its test endpoint takes no
+ * body; and its inbound side is a long poll whose FIRST answer is a drain, so a binding
+ * switched on after a week dark does not replay that week as a task flood. Media is the
+ * other difference worth its own tests: pictures and files travel in both directions here,
+ * which no other channel in this product manages.
+ *
+ * No test opens a socket.
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { assistantText } from "@prismshadow/penguin-core";
+import type { OmniMessage } from "@prismshadow/penguin-core";
+import type {
+ MessagingBindingsResponse,
+ WeChatBindingResponse,
+ WeChatTestResponse,
+} from "../src/api/types.js";
+import type { SessionRow } from "../src/db/repos/sessions.js";
+import type { RuntimeSession } from "../src/runtime/session-manager.js";
+import {
+ MESSAGING_TEST_MESSAGE,
+ MESSAGING_UNSUPPORTED_NOTICE,
+} from "../src/runtime/messaging/bridge.js";
+import { MessagingMediaTooLargeError } from "../src/runtime/messaging/media.js";
+import type {
+ WeChatBotClient,
+ WeChatCredentials,
+ WeChatInboundEvent,
+ WeChatMediaRef,
+ WeChatOutboundFile,
+ WeChatSendArgs,
+ WeChatTransport,
+ WeChatUpdates,
+} from "../src/runtime/messaging/wechat-api.js";
+import { WECHAT_API_BASE } from "../src/runtime/messaging/wechat-api.js";
+import {
+ WeChatConnector,
+ chatOfWeChatReplyRef,
+ wechatConfigOf,
+ wechatRetryDelayMs,
+} from "../src/runtime/messaging/wechat-connector.js";
+import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+const SID = "session-2026-08-28-11-00-00-w9100001";
+const SID2 = "session-2026-08-28-11-00-01-w9100002";
+const BASE = (sid: string) => `/api/sessions/${sid}/messaging/wechat`;
+const PROJECT = "birder-default_project";
+
+const BOT_ID = "bot_9001";
+const BOT_TOKEN = "scan-issued-token-XYZ";
+const SCANNER = "ilink_user_aaa";
+const USER = "ilink_user_bbb";
+
+/** A stored config exactly as a completed scan writes one. */
+const SCANNED_CONFIG = {
+ botId: BOT_ID,
+ botToken: BOT_TOKEN,
+ baseUrl: WECHAT_API_BASE,
+ userId: SCANNER,
+};
+
+/** PNG magic bytes, so the connector's sniff answers `image/png` from the bytes alone. */
+const IMAGE_BYTES = Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ Buffer.from("pretend this is a chart"),
+]);
+const FILE_BYTES = Buffer.from("%PDF-1.7 a report");
+
+// ---------------------------------------------------------------------------
+// Fake transport: answers polls the test feeds it, and records every send.
+// ---------------------------------------------------------------------------
+
+type Send =
+ | { kind: "text"; args: WeChatSendArgs }
+ | { kind: "image"; args: WeChatSendArgs; file: WeChatOutboundFile }
+ | { kind: "file"; args: WeChatSendArgs; file: WeChatOutboundFile };
+
+class FakeWeChatClient implements WeChatBotClient {
+ readonly sends: Send[] = [];
+ readonly cursors: string[] = [];
+ readonly fetches: Array<{ ref: WeChatMediaRef; maxBytes: number; what: string }> = [];
+ /** Whether each poll asked for a drain, in order — the first should and no later one may. */
+ readonly drains: boolean[] = [];
+ credentialChecks = 0;
+ polls = 0;
+ /** Batches waiting to be served, oldest first. */
+ private readonly queue: WeChatInboundEvent[][] = [];
+ private wake: (() => void) | null = null;
+
+ constructor(
+ readonly creds: WeChatCredentials,
+ private readonly t: FakeWeChatTransport,
+ ) {}
+
+ async checkCredentials(): Promise<void> {
+ this.credentialChecks += 1;
+ if (this.t.failAuth !== null) throw new Error(this.t.failAuth);
+ }
+
+ async getUpdates({
+ cursor,
+ signal,
+ drain = false,
+ }: {
+ cursor: string;
+ signal: AbortSignal;
+ drain?: boolean;
+ }): Promise<WeChatUpdates> {
+ this.polls += 1;
+ this.cursors.push(cursor);
+ this.drains.push(drain);
+ if (this.t.failPoll !== null) throw new Error(this.t.failPoll);
+ const queued = this.queue.shift();
+ if (queued !== undefined) {
+ return { messages: queued, cursor: `cursor-${this.polls}`, timedOut: false };
+ }
+ // A drain asks only for what the platform is already holding, so it comes back at once.
+ // With nothing to hand over the production adapter's window CLOSES instead: an empty list,
+ // the cursor it was given, and `timedOut` — never an advanced cursor, which would tell the
+ // loop the platform had answered when it had not. A long poll PARKS, which is what
+ // production does and what makes the readiness test below meaningful.
+ if (drain && !this.t.stallPolls) return { messages: [], cursor, timedOut: true };
+ await new Promise<void>((resolve) => {
+ this.wake = resolve;
+ signal.addEventListener("abort", () => resolve(), { once: true });
+ });
+ if (signal.aborted) throw new Error("connection closed");
+ return { messages: this.queue.shift() ?? [], cursor: `cursor-${this.polls}`, timedOut: false };
+ }
+
+ async sendText(args: WeChatSendArgs): Promise<void> {
+ if (this.t.failSend !== null) throw new Error(this.t.failSend);
+ this.sends.push({ kind: "text", args });
+ }
+ async sendImage(args: WeChatSendArgs & { file: WeChatOutboundFile }): Promise<void> {
+ const { file, ...rest } = args;
+ this.sends.push({ kind: "image", args: rest, file });
+ }
+ async sendFile(args: WeChatSendArgs & { file: WeChatOutboundFile }): Promise<void> {
+ const { file, ...rest } = args;
+ this.sends.push({ kind: "file", args: rest, file });
+ }
+
+ async fetchMedia(ref: WeChatMediaRef, maxBytes: number, what: string): Promise<Buffer> {
+ this.fetches.push({ ref, maxBytes, what });
+ if (this.t.oversizedMedia) throw new MessagingMediaTooLargeError(what, maxBytes);
+ return what === "The image" ? IMAGE_BYTES : FILE_BYTES;
+ }
+
+ /**
+ * Feeds one batch to the poll loop. With no arguments it queues an EMPTY batch, which is
+ * how a test makes a parked poll return without delivering anything — the shape the
+ * recovery half of the outage test needs.
+ */
+ push(...events: WeChatInboundEvent[]): void {
+ this.queue.push(events);
+ this.wake?.();
+ this.wake = null;
+ }
+}
+
+class FakeWeChatTransport implements WeChatTransport {
+ readonly clients: FakeWeChatClient[] = [];
+ failAuth: string | null = null;
+ failSend: string | null = null;
+ failPoll: string | null = null;
+ /** Every poll parks, the drain included — an idle bot, which is the readiness case. */
+ stallPolls = false;
+ oversizedMedia = false;
+
+ createClient(creds: WeChatCredentials): FakeWeChatClient {
+ const client = new FakeWeChatClient(creds, this);
+ this.clients.push(client);
+ return client;
+ }
+
+ /** The client the poll loop is running on (the connection's, not a send's). */
+ poller(): FakeWeChatClient {
+ const client = this.clients.find((c) => c.polls > 0);
+ if (client === undefined) throw new Error("no fake wechat poll started");
+ return client;
+ }
+
+ allSends(): Send[] {
+ return this.clients.flatMap((c) => c.sends);
+ }
+ texts(): WeChatSendArgs[] {
+ return this.allSends()
+ .filter((s) => s.kind === "text")
+ .map((s) => s.args);
+ }
+}
+
+/**
+ * One input part as the fake Session records it. Deliberately a loose shape rather than
+ * core's payload union: a run's input mixes composer text with `image_url` parts, and the
+ * assertions read one field of whichever arrived (the shape messaging-telegram.test.ts uses).
+ */
+interface InputPayload {
+ type?: string;
+ role?: string;
+ text?: string;
+ image_url?: string;
+}
+
+/** A plain inbound text message from a fixed user. */
+function inboundText(text: string, messageId: string, contextToken = "ctx-1"): WeChatInboundEvent {
+ return { userId: USER, messageId, text, contextToken, images: [], files: [] };
+}
+
+/** Fake Session: records each run's input payloads and replies with a fixed assistant text. */
+function echoFakeSession(
+ sessionId: string,
+ runs: InputPayload[][],
+ 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 InputPayload));
+ yield assistantText(reply);
+ },
+ async *compact() {},
+ };
+}
+
+function sessionRowOf(sessionId: string, projectId: string): SessionRow {
+ return {
+ sessionId,
+ projectId,
+ agentId: "default_agent",
+ provider: "custom",
+ modelId: "m1",
+ workspace: "/tmp/w",
+ approvalMode: "allow-all",
+ title: null,
+ createdAt: new Date().toISOString(),
+ lastActiveAt: new Date().toISOString(),
+ };
+}
+
+// ---------------------------------------------------------------------------
+
+describe("wechat config and reply refs", () => {
+ it("narrows a stored document and rejects one missing a credential", () => {
+ expect(wechatConfigOf({ ...SCANNED_CONFIG })).toEqual(SCANNED_CONFIG);
+ expect(() => wechatConfigOf({ botId: BOT_ID })).toThrow(/malformed wechat binding config/);
+ expect(() => wechatConfigOf({ botId: "", botToken: BOT_TOKEN })).toThrow();
+ });
+
+ it("polls the entry host for a document that names none", () => {
+ // A bot with no IDC assignment lives there anyway, so this is the platform's own answer
+ // rather than a guess.
+ const cfg = wechatConfigOf({ botId: BOT_ID, botToken: BOT_TOKEN });
+ expect(cfg.baseUrl).toBe(WECHAT_API_BASE);
+ expect(cfg.userId).toBe("");
+ });
+
+ it("reads a reply anchor back to the chat it names", () => {
+ expect(chatOfWeChatReplyRef(`${USER}:12345`)).toBe(USER);
+ expect(() => chatOfWeChatReplyRef("nocolon")).toThrow(/malformed wechat reply ref/);
+ });
+
+ it("backs off further after each failure, up to a ceiling", () => {
+ expect(wechatRetryDelayMs(1)).toBe(2_000);
+ expect(wechatRetryDelayMs(2)).toBe(4_000);
+ expect(wechatRetryDelayMs(20)).toBe(60_000);
+ });
+});
+
+describe("the wechat connector's own seam", () => {
+ it("carries text, images and files with no download until the bridge asks", async () => {
+ // Handles, not bytes: a redelivery is dropped before anything is transferred.
+ const transport = new FakeWeChatTransport();
+ const connector = new WeChatConnector(transport, { retryDelayMs: () => 0 });
+ const received: Array<{ chatId: string; text: string | null; images: number; files: number }> =
+ [];
+ const conn = await connector.connect(SCANNED_CONFIG, {
+ onMessage: (msg) => {
+ received.push({
+ chatId: msg.chatId,
+ text: msg.text,
+ images: msg.images?.length ?? 0,
+ files: msg.files?.length ?? 0,
+ });
+ },
+ });
+ const client = await waitForPoller(transport);
+ client.push({
+ userId: USER,
+ messageId: "1",
+ text: "look at this",
+ images: [{ url: "https://cdn/i", aesKey: "a2V5" }],
+ files: [{ fileName: "report.pdf", media: { url: "https://cdn/f" } }],
+ });
+ await waitFor(() => received.length === 1);
+ expect(received[0]).toEqual({ chatId: USER, text: "look at this", images: 1, files: 1 });
+ expect(client.fetches).toHaveLength(0);
+ conn.close();
+ });
+});
+
+/** Waits for the connector's poll loop to have made its first call. */
+async function waitForPoller(transport: FakeWeChatTransport): Promise<FakeWeChatClient> {
+ await waitFor(() => transport.clients.some((c) => c.polls > 0));
+ return transport.poller();
+}
+
+describe("wechat binding routes and the long poll", () => {
+ let t: TestApp;
+ let api: ReturnType<typeof apiClient>;
+ let fake: FakeWeChatTransport;
+ let runs: InputPayload[][];
+
+ /** Store a scanned config as the scan route would, then flip the toggle on. */
+ const bindEnabled = async (sid: string, config: Record<string, unknown> = SCANNED_CONFIG) => {
+ t.deps.messagingRepo.upsert({
+ sessionId: sid,
+ channel: "wechat",
+ accountId: String(config.botId),
+ config,
+ });
+ expect((await api.post(`${BASE(sid)}/state`, { enabled: true })).status).toBe(200);
+ await waitFor(() => t.deps.messaging.statusOf(sid, "wechat").state === "connected");
+ };
+
+ beforeEach(async () => {
+ fake = new FakeWeChatTransport();
+ runs = [];
+ // A small non-zero backoff rather than zero: the loop retries in a tight cycle during
+ // the outage test, and a zero delay would spin without yielding.
+ t = await createTestApp({ wechatTransport: fake, wechatRetryDelayMs: () => 5 });
+ const { cookie } = await provisionUser(t.app, "birder");
+ api = apiClient(t.app, cookie);
+ const row = sessionRowOf(SID, PROJECT);
+ t.deps.sessionsRepo.insert(row);
+ t.deps.manager.adopt(row, echoFakeSession(SID, runs));
+ });
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ // —— Routes ——————————————————————————————————————————————————————————————
+
+ it("the GET masks the token and names the bot id as the account", async () => {
+ t.deps.messagingRepo.upsert({
+ sessionId: SID,
+ channel: "wechat",
+ accountId: BOT_ID,
+ config: SCANNED_CONFIG,
+ });
+ const body = (await (await api.get(BASE(SID))).json()) as WeChatBindingResponse;
+ expect(body.binding?.channel).toBe("wechat");
+ expect(body.binding?.botId).toBe(BOT_ID);
+ expect(body.binding?.botTokenMasked).toBe("scan…-XYZ");
+ expect(JSON.stringify(body)).not.toContain(BOT_TOKEN);
+ // Neither the API host nor the scanner's id is projected: one is infrastructure, the
+ // other identifies a person, and the editor renders neither.
+ expect(JSON.stringify(body)).not.toContain(SCANNER);
+ expect(body.binding?.enabled).toBe(false);
+ });
+
+ it("the PUT saves preferences only, and refuses to create a binding at all", async () => {
+ // There is no credential to carry, so a PUT before a scan has nothing it could store.
+ const bare = await api.put(BASE(SID), { renderMarkdown: false });
+ expect(bare.status).toBe(400);
+ expect(((await bare.json()) as { error: { code: string } }).error.code).toBe(
+ "wechat_token_required",
+ );
+
+ t.deps.messagingRepo.upsert({
+ sessionId: SID,
+ channel: "wechat",
+ accountId: BOT_ID,
+ config: SCANNED_CONFIG,
+ });
+ const res = await api.put(BASE(SID), { renderMarkdown: false, linePerMessage: true });
+ expect(res.status).toBe(200);
+ const saved = t.deps.messagingRepo.find(SID, "wechat")!;
+ expect(saved.renderMarkdown).toBe(false);
+ expect(saved.linePerMessage).toBe(true);
+ // The rest of the stored document survives a preferences save untouched — the connector
+ // needs the host and the scanner's id, and this request knows neither.
+ expect(saved.config).toEqual(SCANNED_CONFIG);
+ });
+
+ it("the clear flag drops the token, and is refused while the connection is live", async () => {
+ await bindEnabled(SID);
+ const live = await api.put(BASE(SID), { clearBotToken: true });
+ expect(live.status).toBe(409);
+ expect(((await live.json()) as { error: { code: string } }).error.code).toBe(
+ "messaging_disable_before_clear",
+ );
+
+ expect((await api.post(`${BASE(SID)}/state`, { enabled: false })).status).toBe(200);
+ expect((await api.put(BASE(SID), { clearBotToken: true })).status).toBe(200);
+ const cleared = t.deps.messagingRepo.find(SID, "wechat")!;
+ expect(cleared.config.botToken).toBe("");
+ // The row and its identity stay: only a fresh scan can make it connectable again.
+ expect(cleared.accountId).toBe(BOT_ID);
+ const gate = await api.post(`${BASE(SID)}/state`, { enabled: true });
+ expect(gate.status).toBe(400);
+ expect(((await gate.json()) as { error: { code: string } }).error.code).toBe(
+ "wechat_token_required",
+ );
+ });
+
+ it("the bot id is the account: saving never collides, enabling does", async () => {
+ t.deps.sessionsRepo.insert(sessionRowOf(SID2, PROJECT));
+ t.deps.manager.adopt(sessionRowOf(SID2, PROJECT), echoFakeSession(SID2, []));
+ await bindEnabled(SID);
+ // The same bot saved on a second Session is fine; only the connection is exclusive.
+ t.deps.messagingRepo.upsert({
+ sessionId: SID2,
+ channel: "wechat",
+ accountId: BOT_ID,
+ config: SCANNED_CONFIG,
+ });
+ const clash = await api.post(`${BASE(SID2)}/state`, { enabled: true });
+ expect(clash.status).toBe(409);
+ expect(((await clash.json()) as { error: { code: string } }).error.code).toBe(
+ "account_enabled_elsewhere",
+ );
+ });
+
+ it("the credential probe takes no body and reads the stored binding", async () => {
+ const bare = await api.post(`${BASE(SID)}/test`, {});
+ expect(bare.status).toBe(400);
+ expect(((await bare.json()) as { error: { code: string } }).error.code).toBe(
+ "wechat_token_required",
+ );
+
+ t.deps.messagingRepo.upsert({
+ sessionId: SID,
+ channel: "wechat",
+ accountId: BOT_ID,
+ config: SCANNED_CONFIG,
+ });
+ const ok = (await (await api.post(`${BASE(SID)}/test`, {})).json()) as WeChatTestResponse;
+ expect(ok.ok).toBe(true);
+ // The platform names no account, so success carries no label.
+ expect("botUsername" in ok).toBe(false);
+
+ fake.failAuth = "invalid bot token";
+ const bad = (await (await api.post(`${BASE(SID)}/test`, {})).json()) as WeChatTestResponse;
+ expect(bad.ok).toBe(false);
+ expect(bad.error).toContain("invalid bot token");
+ });
+
+ it("joins the channel-agnostic read beside the others", async () => {
+ t.deps.messagingRepo.upsert({
+ sessionId: SID,
+ channel: "wechat",
+ accountId: BOT_ID,
+ config: SCANNED_CONFIG,
+ });
+ t.deps.messagingRepo.upsert({
+ sessionId: SID,
+ channel: "telegram",
+ accountId: "42",
+ config: { botToken: "42:tele" },
+ });
+ const body = (await (
+ await api.get(`/api/sessions/${SID}/messaging`)
+ ).json()) as MessagingBindingsResponse;
+ expect(body.bindings.map((b) => b.binding.channel).sort()).toEqual(["telegram", "wechat"]);
+ });
+
+ // —— The long poll ————————————————————————————————————————————————————————
+
+ it("reports the connection ready before any poll has answered", async () => {
+ // The reported bug: a long poll is a request held open until something arrives, so a
+ // connection reported ready only when one came back sat at `connecting` for the whole
+ // window on an idle bot — usable throughout, and saying so nowhere.
+ fake.stallPolls = true;
+ t.deps.messagingRepo.upsert({
+ sessionId: SID,
+ channel: "wechat",
+ accountId: BOT_ID,
+ config: SCANNED_CONFIG,
+ });
+ expect((await api.post(`${BASE(SID)}/state`, { enabled: true })).status).toBe(200);
+ await waitFor(() => t.deps.messaging.statusOf(SID, "wechat").state === "connected");
+ // Ready on the probe, with the poll behind it still parked and having returned nothing.
+ const client = fake.poller();
+ expect(client.credentialChecks).toBeGreaterThan(0);
+ expect(client.polls).toBeGreaterThan(0);
+ });
+
+ it("drains until the platform answers, then never again on that connection", async () => {
+ await bindEnabled(SID);
+ const client = fake.poller();
+ client.push(inboundText("hello", "m-0"));
+ await waitFor(() => client.drains.includes(false));
+ // Every drain comes first and there are at most DRAIN_ATTEMPTS of them: a window that
+ // closed on its own deadline handed over no cursor, so spending the drain on it would
+ // leave the next ordinary poll to relay a whole backlog as live traffic. The retry is
+ // bounded because an idle bot's poll may park every time.
+ const drains = client.drains.slice(0, client.drains.indexOf(false));
+ expect(drains.length).toBeGreaterThan(0);
+ expect(drains.length).toBeLessThanOrEqual(2);
+ expect(drains.every((d) => d === true)).toBe(true);
+ expect(client.drains.slice(drains.length).every((d) => d === false)).toBe(true);
+ });
+
+ it("does not spend the drain on a window that closed without an answer", async () => {
+ // The hole this closes: the adapter reports a timed-out window as an empty list with the
+ // cursor it was GIVEN, so a drain spent there leaves the cursor at the beginning and the
+ // next ordinary poll hands the whole backlog to the Agent as live traffic.
+ await bindEnabled(SID);
+ const client = fake.poller();
+ await waitFor(() => client.drains.length >= 2);
+ // The fake's empty drain times out exactly as production's does, so the second call is
+ // still a drain rather than an ordinary poll asking from the same unmoved cursor.
+ expect(client.drains[0]).toBe(true);
+ expect(client.drains[1]).toBe(true);
+ expect(client.cursors[1]).toBe(client.cursors[0]);
+ });
+
+ it("stops with the credential's own reason when the token is refused", async () => {
+ // The probe runs ahead of the poll, so a revoked token reports what is actually wrong
+ // instead of an endless poll failure.
+ fake.failAuth = "invalid bot token";
+ t.deps.messagingRepo.upsert({
+ sessionId: SID,
+ channel: "wechat",
+ accountId: BOT_ID,
+ config: SCANNED_CONFIG,
+ });
+ expect((await api.post(`${BASE(SID)}/state`, { enabled: true })).status).toBe(200);
+ await waitFor(() => t.deps.messaging.statusOf(SID, "wechat").state === "error");
+ expect(t.deps.messaging.statusOf(SID, "wechat").lastError).toContain("invalid bot token");
+ });
+
+ it("drops the first poll's backlog and keeps only its cursor", async () => {
+ // A binding switched on after a week dark must not replay that week as a task flood.
+ fake.createClient = ((creds: WeChatCredentials) => {
+ const client = new FakeWeChatClient(creds, fake);
+ fake.clients.push(client);
+ // Queued before the loop starts, so it is what the FIRST poll returns.
+ client.push(inboundText("sent while nothing was connected", "old-1"));
+ return client;
+ }) as FakeWeChatTransport["createClient"];
+
+ await bindEnabled(SID);
+ const client = fake.poller();
+ // The drain's cursor is carried into the next poll rather than starting over.
+ await waitFor(() => client.cursors.length >= 2);
+ expect(client.cursors[0]).toBe("");
+ expect(client.cursors[1]).toBe("cursor-1");
+
+ client.push(inboundText("hello", "new-1"));
+ await waitFor(() => runs.length === 1);
+ // Only the message that arrived after the drain ever became a task.
+ expect(runs).toHaveLength(1);
+ expect(runs[0]![0]!.text).toBe("hello");
+ });
+
+ it("relays an inbound message to the Agent and its reply back, carrying the conversation token", async () => {
+ await bindEnabled(SID);
+ const client = fake.poller();
+ client.push(inboundText("what is the weather?", "m-1", "ctx-42"));
+ await waitFor(() => fake.texts().length > 0);
+ expect(runs[0]![0]!.text).toBe("what is the weather?");
+ expect(fake.texts()[0]).toEqual({ userId: USER, text: "Reply text", contextToken: "ctx-42" });
+ // The chat is remembered, which is what the test-message button needs.
+ expect(t.deps.messagingRepo.find(SID, "wechat")?.lastChatId).toBe(USER);
+ });
+
+ it("sends the fixed test message to the remembered chat", async () => {
+ await bindEnabled(SID);
+ const noChat = await api.post(`${BASE(SID)}/test-message`, {});
+ expect(noChat.status).toBe(409);
+ expect(((await noChat.json()) as { error: { code: string } }).error.code).toBe(
+ "wechat_no_chat",
+ );
+
+ fake.poller().push(inboundText("hi", "m-2"));
+ await waitFor(() => fake.texts().length > 0);
+ expect((await api.post(`${BASE(SID)}/test-message`, {})).status).toBe(200);
+ expect(fake.texts().at(-1)!.text).toBe(MESSAGING_TEST_MESSAGE);
+ });
+
+ it("answers a message carrying nothing at all with the shared not-supported notice", async () => {
+ // The one inbound shape this channel cannot read: a recording WeChat could not
+ // transcribe. It arrives with no text and no attachment, and the bridge's own notice is
+ // what the chat gets — no channel-specific refusal says more than that one already does.
+ await bindEnabled(SID);
+ fake.poller().push({ userId: USER, messageId: "m-3", text: "", images: [], files: [] });
+ await waitFor(() => fake.texts().length > 0);
+ expect(fake.texts()[0]!.text).toBe(MESSAGING_UNSUPPORTED_NOTICE);
+ expect(runs).toHaveLength(0);
+ });
+
+ it("forgets a conversation token when the connection closes", async () => {
+ // A token from before a disable would otherwise address a conversation the user ended.
+ await bindEnabled(SID);
+ fake.poller().push(inboundText("hi", "m-4", "ctx-99"));
+ await waitFor(() => fake.texts().length > 0);
+ expect(fake.texts()[0]!.contextToken).toBe("ctx-99");
+
+ expect((await api.post(`${BASE(SID)}/state`, { enabled: false })).status).toBe(200);
+ await bindEnabled(SID);
+ // The remembered chat survives in the DB; the token does not, so the send goes without.
+ expect((await api.post(`${BASE(SID)}/test-message`, {})).status).toBe(200);
+ expect(fake.texts().at(-1)!.contextToken).toBeUndefined();
+ });
+
+ it("reports a poll failure as an outage, and recovers on its own when it clears", async () => {
+ await bindEnabled(SID);
+ const client = fake.poller();
+ fake.failPoll = "connection reset";
+ // The loop is parked on a long poll, so waking it is what makes it call again and fail.
+ client.push();
+ await waitFor(() => t.deps.messaging.statusOf(SID, "wechat").state === "error");
+ // Recovery needs nothing to arrive: the probe at the top of the cycle reports it, so the
+ // connection comes back while the poll behind it is still parked.
+ fake.failPoll = null;
+ await waitFor(() => t.deps.messaging.statusOf(SID, "wechat").state === "connected");
+ });
+
+ // —— Media, in both directions ————————————————————————————————————————————
+
+ it("an inbound picture reaches the model as an image part, typed from its bytes", async () => {
+ await bindEnabled(SID);
+ fake.poller().push({
+ userId: USER,
+ messageId: "m-5",
+ text: "",
+ images: [{ url: "https://cdn/i", aesKey: "a2V5" }],
+ files: [],
+ });
+ await waitFor(() => runs.length === 1);
+ expect(runs[0]).toHaveLength(1);
+ expect(runs[0]![0]!.type).toBe("image_url");
+ // The wire names no type for an image; the bytes are the only source, and conclusive.
+ expect(runs[0]![0]!.image_url).toBe(`data:image/png;base64,${IMAGE_BYTES.toString("base64")}`);
+ expect(fake.poller().fetches[0]!.what).toBe("The image");
+ });
+
+ it("an inbound file reaches the model as a path, keeping the sender's own name", async () => {
+ await bindEnabled(SID);
+ fake.poller().push({
+ userId: USER,
+ messageId: "m-6",
+ text: "summarize this",
+ images: [],
+ files: [{ fileName: "report.pdf", media: { url: "https://cdn/f" } }],
+ });
+ await waitFor(() => runs.length === 1);
+ const text = runs[0]![0]!.text!;
+ expect(text.startsWith("summarize this\n\n[attached file: ")).toBe(true);
+ expect(text).toContain("report.pdf");
+ });
+
+ it("refuses an oversized inbound transfer as a size problem the sender can fix", async () => {
+ await bindEnabled(SID);
+ fake.oversizedMedia = true;
+ fake.poller().push({
+ userId: USER,
+ messageId: "m-7",
+ text: "",
+ images: [{ url: "https://cdn/i" }],
+ files: [],
+ });
+ await waitFor(() => fake.texts().length > 0);
+ expect(fake.texts()[0]!.text).toContain("limit");
+ expect(runs).toHaveLength(0);
+ });
+
+ it("a failure that only ever hits the poll still backs off and reports once", async () => {
+ // The probe and the poll are different endpoints. A credential that keeps authenticating
+ // while `getupdates` keeps refusing — an endpoint-specific 5xx, a rate limit, a cursor the
+ // platform has started rejecting — must not zero the counter on every recovery: that walks
+ // the backoff nowhere and writes one error record per attempt, which for a token revoked
+ // overnight is what the loop exists not to do.
+ const delays: number[] = [];
+ const errors: unknown[] = [];
+ fake.failPoll = "getupdates refused";
+ const connector = new WeChatConnector(fake, {
+ // Non-zero so the loop yields to the macrotask queue between attempts; a zero delay
+ // resolves as a microtask and starves the poller below.
+ retryDelayMs: (failures) => {
+ delays.push(failures);
+ return 1;
+ },
+ });
+ const conn = await connector.connect(SCANNED_CONFIG, {
+ onMessage: async () => {},
+ onError: (err) => errors.push(err),
+ });
+ try {
+ await waitFor(() => delays.length >= 4);
+ // The counter climbs across attempts rather than resetting to 1 on every recovery…
+ expect(delays.slice(0, 4)).toEqual([1, 2, 3, 4]);
+ // …so the outage is one error record rather than one per attempt.
+ expect(errors).toHaveLength(1);
+ } finally {
+ conn.close();
+ }
+ });
+
+ it("sends a picture as a picture and any other file as an attachment", async () => {
+ // The capability QQ has to refuse outright: outbound media, both kinds, no public URL.
+ const connector = new WeChatConnector(fake, { retryDelayMs: () => 0 });
+ const outbound = await connector.createClient(SCANNED_CONFIG);
+ await outbound.sendImage(USER, { fileName: "chart.png", data: IMAGE_BYTES });
+ await outbound.sendFile(USER, { fileName: "report.pdf", data: FILE_BYTES });
+ const sends = fake.clients.at(-1)!.sends;
+ expect(sends.map((s) => s.kind)).toEqual(["image", "file"]);
+ expect(sends[0]!.kind === "image" && sends[0]!.file.data.equals(IMAGE_BYTES)).toBe(true);
+ expect(sends[0]!.kind === "image" && sends[0]!.file.fileName).toBe("chart.png");
+ expect(sends[1]!.kind === "file" && sends[1]!.file.fileName).toBe("report.pdf");
+ });
+
+ it("renders a reply's Markdown when the binding asks, and sends the source when it does not", async () => {
+ const connector = new WeChatConnector(fake, { retryDelayMs: () => 0 });
+ const outbound = await connector.createClient(SCANNED_CONFIG);
+ await outbound.sendText(USER, "# Title\n\n**bold**", { markdown: true });
+ await outbound.sendText(USER, "# Title\n\n**bold**");
+ const sends = fake.clients.at(-1)!.sends;
+ // WeChat reads Markdown itself, so a rendered heading stays a heading.
+ expect(sends[0]!.args.text).toBe("# Title\n\n**bold**");
+ expect(sends[1]!.args.text).toBe("# Title\n\n**bold**");
+ // …and the case where rendering actually changes something: a fifth-level heading has no
+ // scale here, so its markers go rather than arriving as five literal `#`.
+ await outbound.sendText(USER, "##### Deep", { markdown: true });
+ expect(fake.clients.at(-1)!.sends.at(-1)!.args.text).toBe("Deep");
+ });
+});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 51b17dd7..108bb32f 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -104,6 +104,11 @@ import type {
QQScanStartResponse,
QQTestRequest,
QQTestResponse,
+ WeChatBindingPutRequest,
+ WeChatBindingResponse,
+ WeChatScanPollResponse,
+ WeChatScanStartResponse,
+ WeChatTestResponse,
RecalledMessageResponse,
RetryNowResponse,
SteerRequest,
@@ -550,6 +555,16 @@ export const putQQBinding = (sessionId: string, body: QQBindingPutRequest) =>
body,
});
+/**
+ * Saves the WeChat delivery preferences. No credential rides along: this channel's token
+ * comes only from a scan, so a PUT before one answers 400 `wechat_token_required`.
+ */
+export const putWeChatBinding = (sessionId: string, body: WeChatBindingPutRequest) =>
+ apiFetch<WeChatBindingResponse>(
+ `/api/sessions/${encodeURIComponent(sessionId)}/messaging/wechat`,
+ { 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,
@@ -602,6 +617,48 @@ export const cancelQQScan = (sessionId: string, taskId: string) =>
body: { taskId },
});
+/**
+ * Starts a WeChat scan-to-connect flow — the ONLY way to bind this channel. The response
+ * carries the URL to render as a QR code and a task handle; the platform's own poll handle,
+ * which is what collects the bot token, stays on the server.
+ */
+export const startWeChatScan = (sessionId: string) =>
+ apiFetch<WeChatScanStartResponse>(
+ `/api/sessions/${encodeURIComponent(sessionId)}/messaging/wechat/scan`,
+ { method: "POST", body: {} },
+ );
+
+/** One poll of a scan. `completed` means the server has already SAVED the credential. */
+export const pollWeChatScan = (sessionId: string, taskId: string) =>
+ apiFetch<WeChatScanPollResponse>(
+ `/api/sessions/${encodeURIComponent(sessionId)}/messaging/wechat/scan/poll`,
+ { method: "POST", body: { taskId } },
+ );
+
+/**
+ * Submits the pairing code WeChat showed on the phone. It rides the NEXT poll rather than a
+ * request of its own, so this only records it — a wrong code surfaces as the poll asking again.
+ */
+export const verifyWeChatScan = (sessionId: string, taskId: string, verifyCode: string) =>
+ apiFetch<void>(`/api/sessions/${encodeURIComponent(sessionId)}/messaging/wechat/scan/verify`, {
+ method: "POST",
+ body: { taskId, verifyCode },
+ });
+
+/** Drops a scan the user walked away from, so its handle is forgotten rather than left to expire. */
+export const cancelWeChatScan = (sessionId: string, taskId: string) =>
+ apiFetch<void>(`/api/sessions/${encodeURIComponent(sessionId)}/messaging/wechat/scan/cancel`, {
+ method: "POST",
+ body: { taskId },
+ });
+
+/** WeChat credential probe of the STORED binding; there is no draft to send and no account label back. */
+export const testWeChatBinding = (sessionId: string) =>
+ apiFetch<WeChatTestResponse>(
+ `/api/sessions/${encodeURIComponent(sessionId)}/messaging/wechat/test`,
+ { method: "POST", body: {} },
+ );
+
/** 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`, {
diff --git a/packages/web/src/components/ui/icons.tsx b/packages/web/src/components/ui/icons.tsx
index 23b3ed78..3bfcc80c 100644
--- a/packages/web/src/components/ui/icons.tsx
+++ b/packages/web/src/components/ui/icons.tsx
@@ -164,13 +164,14 @@ export function CloseButton({
/** Info circle: the app's 9-radius status circle with a bar and a dot inside it. */
export const INFO_ICON = "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM12 11v5m0-8h.01";
-/** Chat bubble: the messaging binding's channel-neutral mark (dock panel tab, row-menu action). */
+/** Chat bubble: the messaging binding's channel-neutral mark (dock panel tab). */
export const MESSAGING_ICON = "M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z";
/**
- * Paper plane: the session-row mark for a Session that is relaying through a messaging
- * channel. One shape for every channel — shape alone is not the carrier, so the row
- * pairs it with the channel's name in a tooltip and in sr-only text.
+ * Paper plane: remote control — the session-row mark for a Session that is relaying through
+ * a messaging channel, and the row menu's action that sets one up. One shape for every
+ * channel — shape alone is not the carrier, so the row pairs it with the channel's name in
+ * a tooltip and in sr-only text, and the menu entry is labelled.
*/
export const MESSAGING_RELAY_ICON = "M22 2 11 13M22 2l-7 20-4-9-9-4z";
diff --git a/packages/web/src/components/ui/segmented.tsx b/packages/web/src/components/ui/segmented.tsx
index 45f22423..4c6dee87 100644
--- a/packages/web/src/components/ui/segmented.tsx
+++ b/packages/web/src/components/ui/segmented.tsx
@@ -1,4 +1,4 @@
-/** Segmented control (for 2-3-way choices like theme/language): small grayscale style. Shared by the sidebar user menu and the login page. */
+/** Segmented control (for 2- to 4-way choices like theme/language/messaging channel): small grayscale style. Shared by the sidebar user menu, the login page and the binding editor. */
export function Segmented<T extends string>({
options,
value,
@@ -8,11 +8,13 @@ export function Segmented<T extends string>({
options: ReadonlyArray<{ value: T; label: string }>;
value: T;
onChange: (v: T) => void;
- cols?: 2 | 3;
+ cols?: 2 | 3 | 4;
}) {
return (
<div
- className={`grid ${cols === 2 ? "grid-cols-2" : "grid-cols-3"} gap-0.5 rounded-md bg-gray-100 p-0.5 dark:bg-gray-800`}
+ // Spelled out rather than interpolated: Tailwind scans for whole class names, and a
+ // `grid-cols-${n}` built at runtime is never emitted into the stylesheet.
+ className={`grid ${cols === 2 ? "grid-cols-2" : cols === 4 ? "grid-cols-4" : "grid-cols-3"} gap-0.5 rounded-md bg-gray-100 p-0.5 dark:bg-gray-800`}
>
{options.map((opt) => (
<button
diff --git a/packages/web/src/components/ui/session-row-menu.tsx b/packages/web/src/components/ui/session-row-menu.tsx
index 595e1995..11554a7f 100644
--- a/packages/web/src/components/ui/session-row-menu.tsx
+++ b/packages/web/src/components/ui/session-row-menu.tsx
@@ -22,7 +22,7 @@ import type { AnchorRect } from "../../lib/context-menu";
import { S } from "../../lib/strings";
import { GlyphIcon } from "./glyph-icon";
import { Icon } from "./group-list";
-import { MESSAGING_ICON } from "./icons";
+import { MESSAGING_RELAY_ICON } from "./icons";
/** Pushpin (lucide pin: head + body + stem), the group-header pin toggle / pinned indicator. */
export const PIN_ICON =
@@ -111,7 +111,10 @@ export function sessionRowMenuItem(
case "rename":
return { label: S.chat.renameSession, icon: PENCIL_ICON, danger: false };
case "messaging":
- return { label: S.messaging.bindAction, icon: MESSAGING_ICON, danger: false };
+ // Same paper plane the session row flies when it is actually relaying: the menu entry
+ // and the mark it produces are one feature, and a reader should not have to learn two
+ // shapes for it.
+ return { label: S.messaging.bindAction, icon: MESSAGING_RELAY_ICON, danger: false };
case "archive":
return {
label: state.archived ? S.chat.unarchiveSession : S.chat.archiveSession,
diff --git a/packages/web/src/features/messaging/messaging-binding-editor.tsx b/packages/web/src/features/messaging/messaging-binding-editor.tsx
index 5bdc65bf..26b56e3f 100644
--- a/packages/web/src/features/messaging/messaging-binding-editor.tsx
+++ b/packages/web/src/features/messaging/messaging-binding-editor.tsx
@@ -30,9 +30,11 @@
* screen: the switch carries it as its tooltip and the "what binding does" fold states it
* in full. Deleting a stored credential remains a separate act — the per-field clear.
*
- * QQ additionally leads its section with scan-to-connect (`qq-scan-connect.tsx`): a QR code
- * scanned in the QQ app, after which the server holds the credentials without them ever
- * passing through this browser. The typed fields stay below it as the fallback.
+ * Two channels lead their section with scan-to-connect, after which the server holds the
+ * credentials without them ever passing through this browser. On QQ (`qq-scan-connect.tsx`)
+ * the typed fields stay below the QR as the fallback; on WeChat
+ * (`wechat-scan-connect.tsx`) there are no fields at all, because the bot token has no other
+ * source — so that channel's section is the QR, the stored-token row, and nothing else.
*
* The GET is re-polled while the host shows the editor (the hook's `poll` flag) so
* connect/error flips show up live.
@@ -61,6 +63,7 @@ import { Segmented } from "../../components/ui/segmented";
import { Switch } from "../../components/ui/switch";
import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";
import { QQScanConnect } from "./qq-scan-connect";
+import { WeChatScanConnect } from "./wechat-scan-connect";
import {
bindingsToForm,
emptyMessagingForm,
@@ -81,8 +84,12 @@ const STATUS_POLL_MS = 3000;
* the credential (field corner). The second is a developer console for some channels and a
* chat with a bot for others, so its label belongs to the channel — only the ones that do
* have a console reach for the shared `S.messaging.console` wording.
+ *
+ * A channel may have NEITHER, which is why the entry is nullable: WeChat's bot is authorized
+ * by a scan and has no public console and no walkthrough to point at, and inventing a URL
+ * would send a reader to a page that does not answer them.
*/
-const CHANNEL_LINKS: Record<MessagingChannel, { tutorial: string; credentialSource: string }> = {
+const CHANNEL_LINKS = {
feishu: {
// Feishu's own echo-bot walkthrough: creating a self-built app and its long connection.
tutorial: "https://open.feishu.cn/document/develop-an-echo-bot/introduction",
@@ -112,7 +119,11 @@ const CHANNEL_LINKS: Record<MessagingChannel, { tutorial: string; credentialSour
// because the retired hash-route app still redirects out of it.
credentialSource: "https://q.qq.com/qqbot/dashboard/",
},
-};
+ wechat: null,
+} as const satisfies Record<
+ MessagingChannel,
+ { tutorial: string; credentialSource: string } | null
+>;
const STATUS_TONE: Record<MessagingRuntimeStatus["state"], Tone> = {
disconnected: "muted",
@@ -154,7 +165,13 @@ function factsOf(
status: MessagingRuntimeStatus,
): MessagingChannelFacts {
if (binding === null) return { ...EMPTY_FACTS, status };
- const masked = binding.channel === "telegram" ? binding.botTokenMasked : binding.appSecretMasked;
+ // The two token channels name the field `botTokenMasked`; the two App-Secret ones name it
+ // `appSecretMasked`. Both are the same fact — a credential is stored — under the name its
+ // own channel gives it.
+ const masked =
+ binding.channel === "telegram" || binding.channel === "wechat"
+ ? binding.botTokenMasked
+ : binding.appSecretMasked;
return {
secretConfigured: masked !== undefined,
secretMasked: masked ?? null,
@@ -165,7 +182,12 @@ function factsOf(
}
function factsFromList(res: MessagingBindingsResponse): ChannelFactsMap {
- const map: ChannelFactsMap = { feishu: EMPTY_FACTS, telegram: EMPTY_FACTS, qq: EMPTY_FACTS };
+ const map: ChannelFactsMap = {
+ feishu: EMPTY_FACTS,
+ telegram: EMPTY_FACTS,
+ qq: EMPTY_FACTS,
+ wechat: EMPTY_FACTS,
+ };
for (const entry of res.bindings) {
map[entry.binding.channel] = factsOf(entry.binding, entry.status);
}
@@ -197,7 +219,7 @@ export interface MessagingBindingEditorState {
/** Why the switch is gated, when a reason is worth showing (null otherwise). */
toggleHint: string | null;
/**
- * A flow OUTSIDE the form saved this channel's binding — QQ's scan-to-connect, whose
+ * A flow OUTSIDE the form saved this channel's binding — either scan-to-connect, whose
* credentials never pass through the browser. Folds the result into that channel's facts
* and the form baseline, exactly as a Save would.
*/
@@ -264,6 +286,7 @@ export function useMessagingBinding(
feishu: EMPTY_FACTS,
telegram: EMPTY_FACTS,
qq: EMPTY_FACTS,
+ wechat: EMPTY_FACTS,
});
const [fieldErrors, setFieldErrors] = useState<MessagingFormErrors>({});
const [busy, setBusy] = useState(false);
@@ -338,7 +361,9 @@ export function useMessagingBinding(
? "telegram"
: channels.qq.enabled
? "qq"
- : null;
+ : channels.wechat.enabled
+ ? "wechat"
+ : null;
const otherEnabled = enabledChannel !== null && enabledChannel !== selected;
const dirty = form !== null && baseline !== null && formDirty(form, baseline);
@@ -356,7 +381,9 @@ export function useMessagingBinding(
? { feishu: fresh.feishu }
: channel === "qq"
? { qq: fresh.qq }
- : { telegram: fresh.telegram };
+ : channel === "wechat"
+ ? { wechat: fresh.wechat }
+ : { telegram: fresh.telegram };
setForm((prev) => (prev ? { ...prev, ...sub } : prev));
setBaseline((prev) => (prev ? { ...prev, ...sub } : prev));
}
@@ -378,6 +405,11 @@ export function useMessagingBinding(
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 if (draft.channel === "wechat") {
+ // No body: this channel's probe reads the stored binding, there being no draft.
+ const res = await api.testWeChatBinding(sessionId);
+ 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));
@@ -417,7 +449,9 @@ export function useMessagingBinding(
? await api.putTelegramBinding(sessionId, built.body)
: built.channel === "qq"
? await api.putQQBinding(sessionId, built.body)
- : await api.putFeishuBinding(sessionId, built.body);
+ : built.channel === "wechat"
+ ? await api.putWeChatBinding(sessionId, built.body)
+ : await api.putFeishuBinding(sessionId, built.body);
applyChannel(built.channel, res.binding, res.status);
toastSuccess(S.common.saved);
} catch (e) {
@@ -615,19 +649,26 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })
if (!form) return null;
const channel = form.channel;
const facts = b.channels[channel];
- const links = CHANNEL_LINKS[channel];
// The delivery preferences of the selected channel, and the patch that writes one back.
- // All three sub-states carry the same two, so resolving the channel once here keeps the
+ // Every sub-state carries the same three, so resolving the channel once here keeps the
// rows at the bottom free of a selector they have nothing to say about.
const delivery =
- channel === "telegram" ? form.telegram : channel === "qq" ? form.qq : form.feishu;
+ channel === "telegram"
+ ? form.telegram
+ : channel === "qq"
+ ? form.qq
+ : channel === "wechat"
+ ? form.wechat
+ : form.feishu;
const patchDelivery = (patch: Partial<MessagingDeliveryFields>) =>
b.patchForm(
channel === "telegram"
? { telegram: { ...form.telegram, ...patch } }
: channel === "qq"
? { qq: { ...form.qq, ...patch } }
- : { feishu: { ...form.feishu, ...patch } },
+ : channel === "wechat"
+ ? { wechat: { ...form.wechat, ...patch } }
+ : { feishu: { ...form.feishu, ...patch } },
);
return (
<div className="space-y-3">
@@ -635,11 +676,12 @@ 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={3}
+ cols={4}
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: "wechat" as MessagingChannel, label: S.messaging.channelName.wechat },
]}
value={channel}
onChange={(v) => b.selectChannel(v)}
@@ -765,7 +807,9 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })
? S.telegram.testMessageNoChat
: channel === "qq"
? S.qq.testMessageNoChat
- : S.feishu.testMessageNoChat,
+ : channel === "wechat"
+ ? S.wechat.testMessageNoChat
+ : S.feishu.testMessageNoChat,
}
: {})}
onClick={() => void b.sendTestMessage()}
@@ -791,7 +835,12 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })
// the reader looking for a web page Telegram has never had. The label names the
// thing the click actually reaches — Telegram's own page for it is titled
// "Launch @BotFather".
- link={<ExternalLink href={links.credentialSource} label={S.telegram.openBotFather} />}
+ link={
+ <ExternalLink
+ href={CHANNEL_LINKS.telegram.credentialSource}
+ label={S.telegram.openBotFather}
+ />
+ }
>
<PasswordInput
size="sm"
@@ -833,7 +882,9 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })
<CornerLinkedField
label={S.qq.appId}
required
- link={<ExternalLink href={links.credentialSource} label={S.messaging.console} />}
+ link={
+ <ExternalLink href={CHANNEL_LINKS.qq.credentialSource} label={S.messaging.console} />
+ }
>
<Input
size="sm"
@@ -875,12 +926,43 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })
same height across channels. */}
<p className="text-xs text-gray-500 dark:text-gray-400">{S.qq.repliesOnly}</p>
</>
+ ) : channel === "wechat" ? (
+ <>
+ {/* The whole credential form: there is nothing to type on this channel, so the QR
+ is not the easy path but the only one. */}
+ <WeChatScanConnect
+ sessionId={b.sessionId}
+ enabled={facts.enabled}
+ bound={facts.secretConfigured}
+ onBound={(binding) => b.adoptBinding(binding)}
+ />
+ {facts.secretMasked !== null && (
+ <StoredSecretRow
+ masked={facts.secretMasked}
+ clearLabel={S.wechat.clearToken}
+ checked={form.wechat.clearToken}
+ enabled={facts.enabled}
+ onChange={(checked) =>
+ b.patchForm({ wechat: { ...form.wechat, clearToken: checked } })
+ }
+ />
+ )}
+ {/* This channel's rule that cannot wait for a collapsed fold: it carries direct
+ chats only, so a user who binds it and then writes in a group sees nothing
+ arrive and concludes the binding is broken. */}
+ <p className="text-xs text-gray-500 dark:text-gray-400">{S.wechat.directOnly}</p>
+ </>
) : (
<>
<CornerLinkedField
label={S.feishu.appId}
required
- link={<ExternalLink href={links.credentialSource} label={S.messaging.console} />}
+ link={
+ <ExternalLink
+ href={CHANNEL_LINKS.feishu.credentialSource}
+ label={S.messaging.console}
+ />
+ }
>
<Input
size="sm"
@@ -978,7 +1060,9 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })
? S.messaging.renderMarkdownHelpTelegram
: channel === "qq"
? S.messaging.renderMarkdownHelpQQ
- : S.messaging.renderMarkdownHelpFeishu
+ : channel === "wechat"
+ ? S.messaging.renderMarkdownHelpWeChat
+ : S.messaging.renderMarkdownHelpFeishu
}
checked={delivery.renderMarkdown}
onChange={(v) => patchDelivery({ renderMarkdown: v })}
@@ -994,7 +1078,14 @@ 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 : channel === "qq" ? S.qq : S.feishu;
+ const per =
+ channel === "telegram"
+ ? S.telegram
+ : channel === "qq"
+ ? S.qq
+ : channel === "wechat"
+ ? S.wechat
+ : S.feishu;
const links = CHANNEL_LINKS[channel];
return (
<div className="space-y-2 border-t border-gray-200 pt-3 dark:border-gray-800">
@@ -1008,9 +1099,15 @@ export function MessagingBindingHelp({ channel }: { channel: MessagingChannel })
Disclosed here rather than parked beside the button, which is a control and so
cannot be the title a standing sentence would need. */}
{channel === "qq" && <p className="mt-1.5">{S.qq.scanHint}</p>}
- <p className="mt-1.5">
- <ExternalLink href={links.tutorial} label={S.messaging.tutorial} />
- </p>
+ {/* Why this channel's form has no fields, said where a reader looking for them
+ arrives. */}
+ {channel === "wechat" && <p className="mt-1.5">{S.wechat.scanOnly}</p>}
+ {/* Absent for a channel with nowhere public to send the reader (see CHANNEL_LINKS). */}
+ {links !== null && (
+ <p className="mt-1.5">
+ <ExternalLink href={links.tutorial} label={S.messaging.tutorial} />
+ </p>
+ )}
</HelpFold>
<HelpFold title={S.messaging.faqWhatTitle}>
<p>{per.intro}</p>
@@ -1019,6 +1116,9 @@ export function MessagingBindingHelp({ channel }: { channel: MessagingChannel })
{/* 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>}
+ {/* What actually travels on this channel, which is more than on any other here and
+ is the question its users ask first. */}
+ {channel === "wechat" && <p className="mt-1.5">{S.wechat.media}</p>}
<p className="mt-1.5">{S.messaging.faqWhatBinding}</p>
</HelpFold>
<HelpFold title={S.messaging.faqTroubleTitle}>
@@ -1028,6 +1128,7 @@ export function MessagingBindingHelp({ channel }: { channel: MessagingChannel })
{channel === "telegram" && <li>{S.messaging.troubleOnePoller}</li>}
{channel === "telegram" && <li>{S.messaging.troubleGroupPrivacy}</li>}
{channel === "qq" && <li>{S.messaging.troubleQQPassive}</li>}
+ {channel === "wechat" && <li>{S.messaging.troubleWeChatDirect}</li>}
{channel === "telegram" && <li>{S.messaging.troubleNoGroupInbound}</li>}
</ul>
</HelpFold>
diff --git a/packages/web/src/features/messaging/messaging-binding-form.ts b/packages/web/src/features/messaging/messaging-binding-form.ts
index 93f005e3..4a4e2d85 100644
--- a/packages/web/src/features/messaging/messaging-binding-form.ts
+++ b/packages/web/src/features/messaging/messaging-binding-form.ts
@@ -6,7 +6,9 @@
* 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.
+ * there is nothing for a domain to switch between. WeChat's has no credential at all — its
+ * token comes only from a scan, which writes it server-side — so its sub-state is the
+ * delivery preferences plus the clear checkbox, and its submit can never fail validation.
*
* Not every field is a credential: `linePerMessage` (send a reply one message per non-blank
* line), `finalReplyOnly` (send only a run's last reply, when the run ends) and
@@ -28,6 +30,7 @@ import type {
QQTestRequest,
TelegramBindingPutRequest,
TelegramTestRequest,
+ WeChatBindingPutRequest,
} from "@prismshadow/penguin-server/api";
/** Default Feishu open-platform domain (shown prefilled; Lark tenants overwrite it). */
@@ -67,6 +70,17 @@ export interface QQFormFields extends MessagingDeliveryFields {
clearSecret: boolean;
}
+/**
+ * WeChat's editable state: the delivery preferences, and the clear checkbox.
+ *
+ * No credential field, because there is nothing to type — the bot token arrives from a scan
+ * and is stored without ever passing through this form.
+ */
+export interface WeChatFormFields extends MessagingDeliveryFields {
+ /** The stored-token clear checkbox (models idiom): applied on save. */
+ clearToken: boolean;
+}
+
export interface TelegramFormFields extends MessagingDeliveryFields {
/** Always starts empty; a non-empty value replaces the stored token on save. */
botToken: string;
@@ -80,6 +94,7 @@ export interface MessagingFormState {
feishu: FeishuFormFields;
telegram: TelegramFormFields;
qq: QQFormFields;
+ wechat: WeChatFormFields;
}
export type MessagingFormField = "appId" | "appSecret" | "baseDomain" | "botToken";
@@ -93,12 +108,15 @@ export type MessagingFormResult =
| { ok: true; channel: "feishu"; body: FeishuBindingPutRequest }
| { ok: true; channel: "telegram"; body: TelegramBindingPutRequest }
| { ok: true; channel: "qq"; body: QQBindingPutRequest }
+ | { ok: true; channel: "wechat"; body: WeChatBindingPutRequest }
| { ok: false; errors: MessagingFormErrors };
export type MessagingTestRequestByChannel =
| { channel: "feishu"; body: FeishuTestRequest }
| { channel: "telegram"; body: TelegramTestRequest }
- | { channel: "qq"; body: QQTestRequest };
+ | { channel: "qq"; body: QQTestRequest }
+ /** WeChat's probe carries no body: nothing on its form is a credential to send. */
+ | { channel: "wechat" };
export function emptyMessagingForm(channel: MessagingChannel = "feishu"): MessagingFormState {
return {
@@ -129,6 +147,12 @@ export function emptyMessagingForm(channel: MessagingChannel = "feishu"): Messag
finalReplyOnly: false,
renderMarkdown: true,
},
+ wechat: {
+ clearToken: false,
+ linePerMessage: false,
+ finalReplyOnly: false,
+ renderMarkdown: true,
+ },
};
}
@@ -152,6 +176,15 @@ export function bindingsToForm(bindings: MessagingBindingInfo[]): MessagingFormS
finalReplyOnly: info.finalReplyOnly,
renderMarkdown: info.renderMarkdown,
};
+ } else if (info.channel === "wechat") {
+ // Nothing but preferences loads: this channel's only credential is the token, which
+ // the form never holds.
+ form.wechat = {
+ clearToken: false,
+ linePerMessage: info.linePerMessage,
+ finalReplyOnly: info.finalReplyOnly,
+ renderMarkdown: info.renderMarkdown,
+ };
} else if (info.channel === "qq") {
form.qq = {
appId: info.appId,
@@ -218,6 +251,20 @@ export function formToPut(form: MessagingFormState, hasStoredSecret: boolean): M
},
};
}
+ if (form.channel === "wechat") {
+ // The one submit that cannot fail: there is no field to leave blank or to mistype.
+ return {
+ ok: true,
+ channel: "wechat",
+ body: {
+ ...(form.wechat.clearToken && hasStoredSecret ? { clearBotToken: true } : {}),
+ // Always sent, for the same reason as the other channels': an omitted flag means "keep".
+ linePerMessage: form.wechat.linePerMessage,
+ finalReplyOnly: form.wechat.finalReplyOnly,
+ renderMarkdown: form.wechat.renderMarkdown,
+ },
+ };
+ }
if (form.channel === "qq") {
const appId = form.qq.appId.trim();
if (appId === "") errors.appId = "required";
@@ -273,6 +320,8 @@ export function formToTest(form: MessagingFormState): MessagingTestRequestByChan
const botToken = form.telegram.botToken.trim();
return { channel: "telegram", body: { ...(botToken !== "" ? { botToken } : {}) } };
}
+ // No draft to send: this channel's probe reads the stored binding.
+ if (form.channel === "wechat") return { channel: "wechat" };
if (form.channel === "qq") {
const appId = form.qq.appId.trim();
const appSecret = form.qq.appSecret.trim();
@@ -313,6 +362,14 @@ export function formDirty(form: MessagingFormState, baseline: MessagingFormState
form.telegram.renderMarkdown !== baseline.telegram.renderMarkdown
);
}
+ if (form.channel === "wechat") {
+ return (
+ form.wechat.clearToken ||
+ form.wechat.linePerMessage !== baseline.wechat.linePerMessage ||
+ form.wechat.finalReplyOnly !== baseline.wechat.finalReplyOnly ||
+ form.wechat.renderMarkdown !== baseline.wechat.renderMarkdown
+ );
+ }
if (form.channel === "qq") {
return (
form.qq.appId !== baseline.qq.appId ||
@@ -343,6 +400,8 @@ export function formTestable(form: MessagingFormState, secretConfigured: boolean
if (form.channel === "telegram") {
return form.telegram.botToken.trim() !== "" || secretConfigured;
}
+ // WeChat has no draft to probe: only a stored token can be tested.
+ if (form.channel === "wechat") return secretConfigured;
if (form.channel === "qq") {
return (form.qq.appId.trim() !== "" && form.qq.appSecret.trim() !== "") || secretConfigured;
}
diff --git a/packages/web/src/features/messaging/wechat-scan-connect.tsx b/packages/web/src/features/messaging/wechat-scan-connect.tsx
new file mode 100644
index 00000000..2d93ce8d
--- /dev/null
+++ b/packages/web/src/features/messaging/wechat-scan-connect.tsx
@@ -0,0 +1,363 @@
+/**
+ * WeChat scan-to-connect — the ONLY way to bind this channel, rather than QQ's convenient
+ * alternative to typing credentials: a WeChat bot token exists nowhere a person could copy
+ * it from, so this component is the whole of the credential form.
+ *
+ * What it may and may not know is the design, and it is the same rule qq-scan-connect.tsx
+ * follows. The server holds the platform's poll handle — the thing that turns into a bot
+ * token — and this component receives a task id it mints instead, plus a URL and a status. A
+ * completed poll returns the bot's id and the saved binding, because the credential went into
+ * storage server-side without passing back through the browser.
+ *
+ * The QR is rendered from the URL locally rather than fetched as an image: the URL is short,
+ * a generated `<svg>` stays crisp at any size, and an image request would put the handle into
+ * a third party's logs. Dark-on-white in both themes, for the reason the QQ panel documents:
+ * a code inverted for a dark background is read unreliably by phone cameras.
+ *
+ * ## The pairing code
+ *
+ * WeChat may interpose a step QQ has no equivalent of: the phone shows a short number that
+ * has to be entered here before the authorization completes. It arrives as a status rather
+ * than an error, so the panel grows an input in place instead of tearing the code down — the
+ * QR is still the thing being authorized, and taking it off screen mid-flow would strand the
+ * user. A wrong number is not reported as a failure either: the platform simply asks again,
+ * which reaches here as the same status a second time.
+ */
+import { useCallback, useEffect, useRef, useState } from "react";
+import { encode } from "uqr";
+import type {
+ MessagingBindingInfo,
+ WeChatBindingInfo,
+ WeChatScanPollResponse,
+} from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { apiErrorText } from "../../lib/api-error";
+import { S } from "../../lib/strings";
+import { Button } from "../../components/ui/button";
+import { Input } from "../../components/ui/input";
+import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";
+import { QrCode } from "./qq-scan-connect";
+
+/**
+ * Consecutive poll failures ridden out before the code comes down. The interval fires
+ * whether or not the previous request came back, so a single 502 from a busy platform must
+ * not take the QR off the screen while the user is still walking to their phone.
+ */
+const POLL_FAILURES_TOLERATED = 3;
+
+/** How many lapsed codes are replaced automatically before the panel stops asking for another. */
+const AUTO_REFRESH_LIMIT = 3;
+
+/** One poll attempt's outcome, as the loop hands it to the classifier. */
+export type WeChatScanAttempt =
+ { ok: true; res: WeChatScanPollResponse } | { ok: false; error: unknown };
+
+/** What the loop has seen so far, NOT counting the attempt being classified. */
+export interface WeChatScanTally {
+ /** Consecutive attempts that failed; any attempt that came back resets it. */
+ failures: number;
+ /** Codes already replaced automatically after the platform reported one expired. */
+ refreshes: number;
+}
+
+/** What one attempt tells the panel to do next. */
+export type WeChatScanStep =
+ | { kind: "wait" }
+ /** Scanned, or waiting for the pairing code: the panel's caption changes, nothing else. */
+ | { kind: "progress"; status: "scanned" | "need_verify_code" }
+ | { kind: "refresh" }
+ | { kind: "bound"; botId: string; binding: WeChatBindingInfo | undefined }
+ | {
+ kind: "stop";
+ notice: string;
+ /** Whether the notice is news rather than a fault (`already_bound` is not a failure). */
+ tone: "error" | "info";
+ /**
+ * The task is still the server's to forget: true when the panel gave up on a task
+ * nothing has resolved, false when the platform already reported the code spent and the
+ * server consumed it on that poll.
+ */
+ releaseTask: boolean;
+ };
+
+/**
+ * Classifies one poll attempt — the `updateCheckOutcome` idiom: the decision is a pure
+ * function, and the loop around it only carries the tally and performs the effects.
+ *
+ * Three of the answers are why this is a function at all. A failed attempt is `wait` until it
+ * has failed several times running, so a transient error does not abandon a scan mid-flight.
+ * `refresh` is capped, or a platform answering `expired` to codes it has just created would
+ * loop create/poll for as long as the panel stays open. And `already_bound` stops WITHOUT
+ * being a failure: nothing was saved because nothing needed to be.
+ */
+export function wechatScanStep(attempt: WeChatScanAttempt, tally: WeChatScanTally): WeChatScanStep {
+ if (!attempt.ok) {
+ return tally.failures + 1 < POLL_FAILURES_TOLERATED
+ ? { kind: "wait" }
+ : {
+ kind: "stop",
+ notice: S.wechat.scanFailed(apiErrorText(attempt.error)),
+ tone: "error",
+ releaseTask: true,
+ };
+ }
+ const { res } = attempt;
+ switch (res.status) {
+ case "completed":
+ return { kind: "bound", botId: res.botId ?? "", binding: res.binding };
+ case "scanned":
+ case "need_verify_code":
+ return { kind: "progress", status: res.status };
+ case "blocked":
+ return { kind: "stop", notice: S.wechat.scanBlocked, tone: "error", releaseTask: false };
+ case "already_bound":
+ return { kind: "stop", notice: S.wechat.scanAlreadyBound, tone: "info", releaseTask: false };
+ case "expired":
+ return tally.refreshes + 1 > AUTO_REFRESH_LIMIT
+ ? {
+ kind: "stop",
+ notice: S.wechat.scanExpiredRepeatedly,
+ tone: "error",
+ releaseTask: false,
+ }
+ : { kind: "refresh" };
+ default:
+ return { kind: "wait" };
+ }
+}
+
+/** Where the flow stands, as the panel shows it. */
+type ScanPhase =
+ | { kind: "idle" }
+ | { kind: "starting" }
+ | {
+ kind: "waiting";
+ taskId: string;
+ qrUrl: string;
+ pollMs: number;
+ refreshed: boolean;
+ /** What the last poll reported, which is the caption and whether the code input shows. */
+ progress: "pending" | "scanned" | "need_verify_code";
+ };
+
+export function WeChatScanConnect({
+ sessionId,
+ /** The channel's connection is enabled: a scan would rebind a live connector, so it is gated. */
+ enabled,
+ /** A token is already stored, so the control offers to REPLACE it rather than to connect. */
+ bound,
+ /** Fired when a scan stored a binding, so the editor refreshes its facts and baseline. */
+ onBound,
+}: {
+ sessionId: string;
+ enabled: boolean;
+ bound: boolean;
+ onBound: (binding: MessagingBindingInfo) => void;
+}) {
+ const [phase, setPhase] = useState<ScanPhase>({ kind: "idle" });
+ const [verifyCode, setVerifyCode] = useState("");
+ const [verifying, setVerifying] = useState(false);
+ /** The task the effects act on, read by the unmount cleanup without re-running it. */
+ const taskRef = useRef<string | null>(null);
+ /** Set once the component is going away, so an in-flight poll stops writing state. */
+ const goneRef = useRef(false);
+ /** What `wechatScanStep` classifies each attempt against; lives outside React state. */
+ const tallyRef = useRef<WeChatScanTally>({ failures: 0, refreshes: 0 });
+
+ const start = useCallback(
+ async (refreshed: boolean) => {
+ setPhase({ kind: "starting" });
+ setVerifyCode("");
+ // A new code starts a fresh failure count; only a scan the USER asked for starts a
+ // fresh refresh count, or the cap on automatic replacement would never be reached.
+ tallyRef.current = { failures: 0, refreshes: refreshed ? tallyRef.current.refreshes : 0 };
+ try {
+ const res = await api.startWeChatScan(sessionId);
+ if (goneRef.current) {
+ // Started into a component that is already gone: drop the task rather than leave
+ // the server holding a handle nobody will ever poll for.
+ void api.cancelWeChatScan(sessionId, res.taskId).catch(() => {});
+ return;
+ }
+ taskRef.current = res.taskId;
+ setPhase({
+ kind: "waiting",
+ taskId: res.taskId,
+ qrUrl: res.qrUrl,
+ pollMs: res.pollMs,
+ refreshed,
+ progress: "pending",
+ });
+ } catch (e) {
+ if (goneRef.current) return;
+ taskRef.current = null;
+ setPhase({ kind: "idle" });
+ toastError(S.wechat.scanFailed(apiErrorText(e)));
+ }
+ },
+ [sessionId],
+ );
+
+ const stop = useCallback(() => {
+ const taskId = taskRef.current;
+ taskRef.current = null;
+ setPhase({ kind: "idle" });
+ if (taskId !== null) void api.cancelWeChatScan(sessionId, taskId).catch(() => {});
+ }, [sessionId]);
+
+ // The poll loop. Restarted whenever the task changes and torn down with it; what each
+ // answer means is `wechatScanStep`'s, so this only carries the tally and does the effects.
+ useEffect(() => {
+ if (phase.kind !== "waiting") return;
+ const { taskId, pollMs } = phase;
+ let cancelled = false;
+ const timer = setInterval(() => {
+ void (async () => {
+ if (cancelled) return;
+ let attempt: WeChatScanAttempt;
+ try {
+ attempt = { ok: true, res: await api.pollWeChatScan(sessionId, taskId) };
+ } catch (error) {
+ attempt = { ok: false, error };
+ }
+ if (cancelled) return;
+ const step = wechatScanStep(attempt, tallyRef.current);
+ tallyRef.current = {
+ failures: attempt.ok ? 0 : tallyRef.current.failures + 1,
+ refreshes: tallyRef.current.refreshes,
+ };
+ if (step.kind === "wait") return;
+ if (step.kind === "progress") {
+ // The code stays up; only the caption (and the pairing-code input) changes.
+ setPhase((prev) =>
+ prev.kind === "waiting" && prev.taskId === taskId
+ ? { ...prev, progress: step.status }
+ : prev,
+ );
+ return;
+ }
+ taskRef.current = null;
+ if (step.kind === "refresh") {
+ tallyRef.current = { failures: 0, refreshes: tallyRef.current.refreshes + 1 };
+ void start(true);
+ return;
+ }
+ setPhase({ kind: "idle" });
+ if (step.kind === "bound") {
+ toastSuccess(S.wechat.scanDone(step.botId));
+ if (step.binding !== undefined) onBound(step.binding);
+ return;
+ }
+ // A run of failed polls says nothing about the server, so the task may well still be
+ // live: it is released here the way cancel and unmount release one.
+ if (step.releaseTask) void api.cancelWeChatScan(sessionId, taskId).catch(() => {});
+ if (step.tone === "info") toastInfo(step.notice);
+ else toastError(step.notice);
+ })();
+ }, pollMs);
+ return () => {
+ cancelled = true;
+ clearInterval(timer);
+ };
+ // `start` and `onBound` are stable enough for this to key on the task alone; re-running
+ // on their identity would restart the poll on every render of the host.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [phase.kind === "waiting" ? phase.taskId : null, sessionId]);
+
+ // Leaving the editor drops the task: the server then forgets its handle immediately
+ // instead of holding it until the TTL sweep.
+ useEffect(() => {
+ goneRef.current = false;
+ return () => {
+ goneRef.current = true;
+ const taskId = taskRef.current;
+ taskRef.current = null;
+ if (taskId !== null) void api.cancelWeChatScan(sessionId, taskId).catch(() => {});
+ };
+ }, [sessionId]);
+
+ const submitVerifyCode = async (taskId: string) => {
+ const code = verifyCode.trim();
+ if (code === "") return;
+ setVerifying(true);
+ try {
+ await api.verifyWeChatScan(sessionId, taskId, code);
+ // Cleared on submit rather than on acceptance: the platform reports a wrong code by
+ // asking again, and leaving the rejected digits in the box would read as accepted.
+ setVerifyCode("");
+ } catch (e) {
+ toastError(S.wechat.scanFailed(apiErrorText(e)));
+ } finally {
+ setVerifying(false);
+ }
+ };
+
+ if (phase.kind !== "waiting") {
+ return (
+ <div>
+ <Button
+ size="sm"
+ disabled={phase.kind === "starting" || enabled}
+ {...(enabled ? { title: S.wechat.scanDisableFirst } : {})}
+ onClick={() => void start(false)}
+ >
+ {phase.kind === "starting"
+ ? S.wechat.scanStarting
+ : bound
+ ? S.wechat.scanRescan
+ : S.wechat.scanStart}
+ </Button>
+ </div>
+ );
+ }
+
+ const needsCode = phase.progress === "need_verify_code";
+ return (
+ <div className="flex flex-wrap items-start gap-3 rounded-md border border-gray-200 p-3 dark:border-gray-800">
+ <QrCode value={phase.qrUrl} label={S.wechat.scanQrLabel} />
+ <div className="min-w-0 flex-1 space-y-1.5 text-xs text-gray-500 dark:text-gray-400">
+ <p className="text-sm text-gray-700 dark:text-gray-300">
+ {needsCode
+ ? S.wechat.verifyPrompt
+ : phase.progress === "scanned"
+ ? S.wechat.scanScanned
+ : S.wechat.scanWaiting}
+ </p>
+ {needsCode ? (
+ <form
+ className="flex items-center gap-2"
+ onSubmit={(e) => {
+ e.preventDefault();
+ void submitVerifyCode(phase.taskId);
+ }}
+ >
+ <Input
+ size="sm"
+ aria-label={S.wechat.verifyLabel}
+ value={verifyCode}
+ onChange={(e) => setVerifyCode(e.target.value)}
+ className="w-28 font-mono"
+ inputMode="numeric"
+ autoComplete="off"
+ autoFocus
+ />
+ <Button size="sm" type="submit" disabled={verifying || verifyCode.trim() === ""}>
+ {verifying ? S.wechat.verifySubmitting : S.wechat.verifySubmit}
+ </Button>
+ </form>
+ ) : (
+ <p>{S.wechat.scanSteps}</p>
+ )}
+ {/* Only shown once a code has actually lapsed: a standing note that codes expire is
+ noise until one does. */}
+ {phase.refreshed && (
+ <p className="text-gray-400 dark:text-gray-500">{S.wechat.scanRefreshed}</p>
+ )}
+ <p className="text-gray-400 dark:text-gray-500">{S.wechat.scanPrivacy}</p>
+ <Button size="sm" variant="ghost" onClick={stop}>
+ {S.common.cancel}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index d10de696..01674625 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -1958,22 +1958,89 @@ Scenarios:
],
},
+ /** WeChat-channel strings of the messaging binding editor (channel-neutral ones live under `messaging`). */
+ wechat: {
+ /** The what-binding-does FAQ fold's body (this channel's flavor). */
+ intro:
+ "Once bound, messages sent to the bot in WeChat arrive in this conversation and the AI's replies go back to WeChat. Binding is a QR code scanned in WeChat — no public address, and no credential to apply for in any console.",
+ /** The stored-token row's clear checkbox (the models-page clear idiom). */
+ clearToken: "Clear stored Bot Token",
+ /** Why this channel's form has no credential fields at all. */
+ scanOnly:
+ "A WeChat bot's credential comes only from scanning: there is no App ID or secret to fill in by hand.",
+ /** Why "send test message" is disabled before the bot has ever been messaged. */
+ testMessageNoChat:
+ "Send the bot a message in WeChat first, so it knows which conversation to reply to",
+ /**
+ * The channel's shape, stated below its controls rather than left in a collapsed fold:
+ * a user who binds it and then writes in a group sees nothing arrive.
+ */
+ directOnly:
+ "This channel carries direct chats with the bot only; group messages never reach it.",
+ /** What travels, and the one inbound kind that does not. */
+ media:
+ "Text, images and files travel in both directions. A voice message arrives as WeChat's own transcription of it; a recording WeChat could not transcribe cannot be read.",
+ /** Scan-to-connect: the button, and the states it moves through. */
+ scanStart: "Connect by scanning",
+ /** The same control once a binding exists: scanning again replaces the stored credential. */
+ scanRescan: "Scan again",
+ scanStarting: "Generating the code…",
+ scanQrLabel: "WeChat bot authorization QR code",
+ scanWaiting: "Waiting for the code to be scanned in WeChat…",
+ scanSteps: "Scan the code with WeChat on your phone, then confirm the authorization there.",
+ /** Scanned but not yet confirmed: the phone is waiting, not this panel. */
+ scanScanned: "Scanned — confirm the authorization on your phone.",
+ /** Shown only after a code has actually lapsed and been replaced. */
+ scanRefreshed: "The previous code lapsed; this one is new.",
+ /** Why the credential is safe to obtain this way — the question a careful user will ask. */
+ scanPrivacy:
+ "The credential is received and stored by the server; it never reaches the browser.",
+ scanDone: (botId: string): string =>
+ `Saved the credential for bot ${botId} — the connection can be enabled now`,
+ scanFailed: (reason: string): string => `Connecting by scan failed: ${reason}`,
+ /** Shown when replacing lapsed codes stopped being worth another round trip. */
+ scanExpiredRepeatedly:
+ "The code lapsed before it was scanned several times over. Try again later.",
+ /** The platform stopped accepting pairing codes for this scan. */
+ scanBlocked:
+ "Too many wrong pairing codes, so this scan is spent. Start a new one in a little while.",
+ /** Not a failure: the bot is already bound here, so no new credential was issued. */
+ scanAlreadyBound:
+ "This bot is already bound, here or somewhere else, so no new token was issued. If this conversation is the one that should have it, unbind the bot where it is in use and scan again.",
+ /** Why the scan button is gated while this channel holds the connection. */
+ scanDisableFirst: "Disable the connection before rebinding it by scan",
+ /** The pairing-code step: WeChat shows digits on the phone that must be typed here. */
+ verifyPrompt: "Your phone is showing a number. Enter it to continue:",
+ verifyLabel: "Pairing code",
+ verifySubmit: "Confirm",
+ verifySubmitting: "Submitting…",
+ /** The setup FAQ fold's steps. */
+ setupSteps: [
+ "Press “Connect by scanning” above to generate the code",
+ "Scan it with WeChat on your phone",
+ "If your phone shows a number, type it into the panel",
+ "Confirm the authorization on your phone; the credential is saved automatically",
+ "Find the bot in WeChat 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` /
* `qq`).
*/
messaging: {
- panelTitle: "Messaging",
+ panelTitle: "Remote control",
/** Session-row context-menu action (the trailing ellipsis marks that a dialog follows). */
- bindAction: "Messaging binding…",
- dialogTitle: "Messaging binding",
+ bindAction: "Remote control…",
+ dialogTitle: "Remote control",
/** The channel selector (always live: each channel's config is saved independently). */
channelLabel: "Channel",
channelName: {
feishu: "Feishu",
telegram: "Telegram",
qq: "QQ",
+ wechat: "WeChat",
},
/**
* Shared link labels: the tutorial (in the setup FAQ fold) and, at the credential field's
@@ -2029,6 +2096,8 @@ Scenarios:
"A reply's Markdown arrives as formatting instead of as `**characters**`. Telegram shows bold, italic, strikethrough, links, inline code and code blocks; it has no headings, lists or tables, so a heading becomes a bold line, list markers become part of the text, and a table arrives as a code block. If Telegram refuses the formatting, the reply is sent as plain text rather than lost.",
renderMarkdownHelpQQ:
"A reply's Markdown arrives as formatting instead of as `**characters**`. QQ shows headings, bold, italic, strikethrough, lists, quotes, rules and links; it has no code formatting and no tables, so a code block arrives as plain lines and a table as its rows. If QQ refuses the formatting, the reply is sent as plain text — which costs one more of the few replies QQ allows per message.",
+ renderMarkdownHelpWeChat:
+ "A reply's Markdown arrives as formatting instead of as `**characters**`. WeChat reads Markdown itself and shows the most of the four channels: headings, bold, strikethrough, lists, quotes, rules, links, inline code, code blocks and tables all render. What it cannot show keeps its words and loses its markers — headings past the fourth level, italics around Chinese text, and inline images, which become links.",
/** The saved delivery option: one message per non-blank line of a reply. */
linePerMessage: "One message per line",
/** Its disclosure, beside the label: what the option does to a reply, and its two edges. */
@@ -2051,6 +2120,7 @@ Scenarios:
feishu: "Feishu connection enabled",
telegram: "Telegram connection enabled",
qq: "QQ connection enabled",
+ wechat: "WeChat connection enabled",
},
/**
* Delivery observability under the toggle: has anything arrived, and did the last one get
@@ -2084,6 +2154,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. A getUpdates you run by hand (a curl to see what Telegram has queued) is that other program too: disable the connection here before running one. Inspecting them by hand can also discard them — any call you pass an offset to confirms everything before it, and the app's own next connect drops the backlog — so retest with a freshly sent message rather than the ones you just looked at.",
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.",
+ /** WeChat has no group inbound at all — the answer to "I @-ed it in a group and nothing happened". */
+ troubleWeChatDirect:
+ "The WeChat channel receives direct chats only: @-mentioning the bot in a group does nothing at all. Message it directly instead.",
/** 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.",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 2f394f38..818d4f90 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -1914,22 +1914,82 @@ Benchmark:
],
},
+ /** WeChat-channel strings of the messaging binding editor (channel-neutral ones live under `messaging`). */
+ wechat: {
+ /** The what-binding-does FAQ fold's body (this channel's flavor). */
+ intro:
+ "绑定后,在微信中发给机器人的消息会进入本对话,AI 的回复会发回微信。用微信扫码授权即可完成绑定,无需公网地址,也无需在任何后台申请凭据。",
+ /** The stored-token row's clear checkbox (the models-page clear idiom). */
+ clearToken: "清除已存 Bot Token",
+ /** Why this channel's form has no credential fields at all. */
+ scanOnly: "微信机器人的凭据只能通过扫码授权获得,没有可手动填写的 App ID 或密钥。",
+ /** Why "send test message" is disabled before the bot has ever been messaged. */
+ testMessageNoChat: "先在微信中给机器人发一条消息,机器人才知道要发到哪个会话",
+ /**
+ * The channel's shape, stated below its controls rather than left in a collapsed fold:
+ * a user who binds it and then writes in a group sees nothing arrive.
+ */
+ directOnly: "这个渠道只支持与机器人的单聊,收不到群聊消息。",
+ /** What travels, and the one inbound kind that does not. */
+ media:
+ "文字、图片和文件都能双向传输。语音消息按微信自带的语音转文字结果进入对话,微信没能转写的语音则无法处理。",
+ /** Scan-to-connect: the button, and the states it moves through. */
+ scanStart: "扫码连接",
+ /** The same control once a binding exists: scanning again replaces the stored credential. */
+ scanRescan: "重新扫码",
+ scanStarting: "生成二维码…",
+ scanQrLabel: "微信机器人授权二维码",
+ scanWaiting: "等待在微信中扫码…",
+ scanSteps: "用手机微信扫描二维码,然后在手机上确认授权。",
+ /** Scanned but not yet confirmed: the phone is waiting, not this panel. */
+ scanScanned: "已扫码,请在手机上确认授权。",
+ /** Shown only after a code has actually lapsed and been replaced. */
+ scanRefreshed: "上一个二维码已过期,这是新的。",
+ /** Why the credential is safe to obtain this way — the question a careful user will ask. */
+ scanPrivacy: "凭据由服务端直接接收并保存,不会经过浏览器。",
+ scanDone: (botId: string): string => `已保存机器人 ${botId} 的凭据,可以启用连接了`,
+ scanFailed: (reason: string): string => `扫码连接失败:${reason}`,
+ /** Shown when replacing lapsed codes stopped being worth another round trip. */
+ scanExpiredRepeatedly: "二维码多次在扫描前就已过期。请稍后重新发起扫码。",
+ /** The platform stopped accepting pairing codes for this scan. */
+ scanBlocked: "配对码输入错误次数过多,本次扫码已作废。请稍后重新发起扫码。",
+ /** Not a failure: the bot is already bound here, so no new credential was issued. */
+ scanAlreadyBound:
+ "这个机器人已经被绑定——可能在本服务,也可能在别处,因此没有签发新的凭据。如果该由本会话持有它,请先在正在使用它的地方解绑,再重新扫码。",
+ /** Why the scan button is gated while this channel holds the connection. */
+ scanDisableFirst: "先停用连接,再重新扫码绑定",
+ /** The pairing-code step: WeChat shows digits on the phone that must be typed here. */
+ verifyPrompt: "手机上显示了一组数字,输入它以继续连接:",
+ verifyLabel: "配对码",
+ verifySubmit: "确认",
+ verifySubmitting: "提交中…",
+ /** The setup FAQ fold's steps. */
+ setupSteps: [
+ "点击上方的「扫码连接」,生成授权二维码",
+ "用手机微信扫描这个二维码",
+ "如果手机上显示了一组数字,把它输入到面板中",
+ "在手机上确认授权,凭据会自动保存",
+ "在微信中找到这个机器人,给它发一条消息",
+ ],
+ },
+
/**
* Session ↔ messaging-bot binding: the dock panel, the row action + dialog, and the
* channel-neutral editor strings (per-channel fields live under `feishu` / `telegram` /
* `qq`).
*/
messaging: {
- panelTitle: "消息软件",
+ panelTitle: "远程控制",
/** Session-row context-menu action (the trailing ellipsis marks that a dialog follows). */
- bindAction: "消息软件绑定…",
- dialogTitle: "消息软件绑定",
+ bindAction: "远程控制…",
+ dialogTitle: "远程控制",
/** The channel selector (always live: each channel's config is saved independently). */
channelLabel: "渠道",
channelName: {
feishu: "飞书",
telegram: "Telegram",
qq: "QQ",
+ wechat: "微信",
},
/**
* Shared link labels: the tutorial (in the setup FAQ fold) and, at the credential field's
@@ -1983,6 +2043,8 @@ Benchmark:
"开启后,回复中的 Markdown 以排版形式到达,而不是显示为 `**字符**`。Telegram 支持粗体、斜体、删除线、链接、行内代码与代码块;它没有标题、列表和表格,因此标题渲染为一行粗体,列表符号作为文本的一部分保留,表格改以代码块发送。若 Telegram 拒绝该排版,回复会改以纯文本发出,不会丢失。",
renderMarkdownHelpQQ:
"开启后,回复中的 Markdown 以排版形式到达,而不是显示为 `**字符**`。QQ 支持标题、粗体、斜体、删除线、列表、引用、分割线和链接;它没有代码格式,也没有表格,因此代码块按普通文本行到达,表格按其行到达。若 QQ 拒绝该排版,回复会改以纯文本发出——这会多占用 QQ 对每条消息只允许的少数几条回复中的一条。",
+ renderMarkdownHelpWeChat:
+ "开启后,回复中的 Markdown 以排版形式到达,而不是显示为 `**字符**`。微信自己就读 Markdown,四个渠道里它支持得最全:标题、粗体、删除线、列表、引用、分割线、链接、行内代码、代码块和表格都能渲染。它不支持的部分会被去掉标记只留文字——五级以下的标题、中文两侧的斜体星号,以及行内图片(改为链接)。",
/** The saved delivery option: one message per non-blank line of a reply. */
linePerMessage: "每行一条消息",
/** Its disclosure, beside the label: what the option does to a reply, and its two edges. */
@@ -2005,6 +2067,7 @@ Benchmark:
feishu: "飞书连接已启用",
telegram: "Telegram 连接已启用",
qq: "QQ 连接已启用",
+ wechat: "微信连接已启用",
},
/**
* Delivery observability under the toggle: has anything arrived, and did the last one get
@@ -2036,6 +2099,8 @@ Benchmark:
"Telegram 提示已有其他程序在轮询?一个 Bot Token 同一时刻只能被一个程序使用——关闭正在占用它的另一个 PenguinHarness 服务端或机器人脚本,或为该会话单独建一个机器人。手动执行的 getUpdates(例如用 curl 查看 Telegram 那边积压了什么)同样算作「另一个程序」:跑它之前先在这里停用连接。而且手动查看也可能把它们丢掉——任何带 offset 的调用都会确认它之前的全部更新,应用自己的下一次连接也会清空积压——所以复测请重新发一条新消息,而不是指望刚才看到的那几条。",
troubleGroupPrivacy:
"在 Telegram 群里发消息,机器人毫无反应?Telegram 的 Group Privacy 默认开启,此时不担任该群管理员的机器人只能收到明确指向它的命令(如 /start@your_bot)和对它自己消息的回复,普通群消息根本不会送达,连接本身也没有任何异常。把机器人设为该群的管理员即可单独解决,管理员始终收到全部消息。也可以到 @BotFather 用 /setprivacy 关闭 Group Privacy,然后把机器人移出该群再重新拉入——已在的群不会自动生效。",
+ /** WeChat has no group inbound at all — the answer to "I @-ed it in a group and nothing happened". */
+ troubleWeChatDirect: "微信渠道只接收单聊消息:在群里 @机器人不会有任何反应,请直接私聊它。",
/** The QQ-only failure a user will otherwise read as "the bot is broken". */
troubleQQPassive:
"QQ 里收不到回复?QQ 只允许机器人回复你刚发出的消息:在网页端发起的对话不会同步过去,距离你上一条 QQ 消息过去几分钟后也发不出。在 QQ 里再发一条消息即可继续。",
diff --git a/packages/web/test/messaging-binding-editor.test.ts b/packages/web/test/messaging-binding-editor.test.ts
index a33ca1dc..9544b611 100644
--- a/packages/web/test/messaging-binding-editor.test.ts
+++ b/packages/web/test/messaging-binding-editor.test.ts
@@ -39,6 +39,18 @@ const DARK: MessagingChannelFacts = {
lastChatKnown: false,
};
+/**
+ * Where a channel's credential section starts, for the assertions that the delivery rows
+ * trail it. WeChat has no credential FIELD — its token comes only from a scan — so its scan
+ * button is what stands at the head of that section.
+ */
+function credentialAnchor(channel: MessagingChannel): string {
+ if (channel === "telegram") return S.telegram.botToken;
+ if (channel === "qq") return S.qq.appId;
+ if (channel === "wechat") return S.wechat.scanStart;
+ return S.feishu.appId;
+}
+
/** A state object shaped like the hook's, with the handlers stubbed (this renders, never acts). */
function stateOf(
channel: MessagingChannel,
@@ -51,7 +63,7 @@ function stateOf(
form: emptyMessagingForm(channel),
patchForm: () => {},
selectChannel: () => {},
- channels: { feishu: DARK, telegram: DARK, qq: DARK, ...facts },
+ channels: { feishu: DARK, telegram: DARK, qq: DARK, wechat: DARK, ...facts },
fieldErrors: {},
dirty: false,
busy: false,
@@ -178,7 +190,7 @@ describe("MessagingBindingBody", () => {
});
it('closes the form with the delivery options, each explanation behind its label\'s "?"', () => {
- for (const channel of ["feishu", "telegram", "qq"] as MessagingChannel[]) {
+ for (const channel of ["feishu", "telegram", "qq", "wechat"] as MessagingChannel[]) {
const html = render(stateOf(channel));
// Every channel carries both: they are delivery preferences, not credentials.
expect(html).toContain(S.messaging.linePerMessage);
@@ -189,13 +201,7 @@ describe("MessagingBindingBody", () => {
expect(html).not.toContain(S.messaging.linePerMessageHelp);
expect(html).not.toContain(S.messaging.finalReplyOnlyHelp);
// After the credential fields, not among them.
- const fieldAt = html.indexOf(
- channel === "telegram"
- ? S.telegram.botToken
- : channel === "qq"
- ? S.qq.appId
- : S.feishu.appId,
- );
+ const fieldAt = html.indexOf(credentialAnchor(channel));
expect(fieldAt).toBeGreaterThanOrEqual(0);
expect(html.indexOf(S.messaging.finalReplyOnly)).toBeGreaterThan(fieldAt);
// In the order the two take effect: which messages are sent, then how each is split.
@@ -231,8 +237,9 @@ describe("MessagingBindingBody", () => {
feishu: S.messaging.renderMarkdownHelpFeishu,
telegram: S.messaging.renderMarkdownHelpTelegram,
qq: S.messaging.renderMarkdownHelpQQ,
+ wechat: S.messaging.renderMarkdownHelpWeChat,
} as const;
- for (const channel of ["feishu", "telegram", "qq"] as MessagingChannel[]) {
+ for (const channel of ["feishu", "telegram", "qq", "wechat"] as MessagingChannel[]) {
const html = render(stateOf(channel));
expect(html).toContain(S.messaging.renderMarkdown);
// Semantics disclose — the sentence is in the popover panel, which renders collapsed.
@@ -240,17 +247,11 @@ describe("MessagingBindingBody", () => {
expect(html).not.toContain(help[channel]);
// One sentence per channel: what a channel can show is the whole of what the reader
// needs here, and a shared line would have to say "depending on the channel".
- for (const other of ["feishu", "telegram", "qq"] as MessagingChannel[]) {
+ for (const other of ["feishu", "telegram", "qq", "wechat"] as MessagingChannel[]) {
if (other !== channel) expect(html).not.toContain(help[other]);
}
// After the credential fields, like the other delivery preference.
- const fieldAt = html.indexOf(
- channel === "telegram"
- ? S.telegram.botToken
- : channel === "qq"
- ? S.qq.appId
- : S.feishu.appId,
- );
+ const fieldAt = html.indexOf(credentialAnchor(channel));
expect(html.indexOf(S.messaging.renderMarkdown)).toBeGreaterThan(fieldAt);
}
});
@@ -268,16 +269,19 @@ describe("MessagingBindingBody", () => {
expect(render(stateOf("feishu"))).not.toContain(S.qq.repliesOnly);
});
- it("offers all three channels in the selector", () => {
+ it("offers all four 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,
+ S.messaging.channelName.wechat,
]) {
expect(html).toContain(`>${name}</button>`);
}
- expect(html).toContain("grid-cols-3");
+ // The grid's column count is spelled out in the component rather than interpolated, so
+ // a fourth channel that did not widen it would silently wrap onto a second row.
+ expect(html).toContain("grid-cols-4");
});
it("says whether anything has arrived, and which end failed when something did", () => {
diff --git a/packages/web/test/messaging-binding-form.test.ts b/packages/web/test/messaging-binding-form.test.ts
index 70c8e687..7c3e9beb 100644
--- a/packages/web/test/messaging-binding-form.test.ts
+++ b/packages/web/test/messaging-binding-form.test.ts
@@ -14,6 +14,7 @@ import type {
FeishuBindingInfo,
QQBindingInfo,
TelegramBindingInfo,
+ WeChatBindingInfo,
} from "@prismshadow/penguin-server/api";
import {
FEISHU_DEFAULT_DOMAIN,
@@ -72,6 +73,20 @@ const STORED_QQ: QQBindingInfo = {
updatedAt: "2026-08-27T00:00:00.000Z",
};
+const STORED_WECHAT: WeChatBindingInfo = {
+ channel: "wechat",
+ sessionId: "session-1",
+ botId: "bot_9001",
+ botTokenMasked: "scan…-XYZ",
+ enabled: false,
+ linePerMessage: true,
+ finalReplyOnly: false,
+ renderMarkdown: false,
+ lastChatKnown: true,
+ createdAt: "2026-08-28T00:00:00.000Z",
+ updatedAt: "2026-08-28T00:00:00.000Z",
+};
+
describe("emptyMessagingForm / bindingsToForm", () => {
it("starts empty forms on Feishu with the default domain, both channels blank", () => {
expect(emptyMessagingForm()).toEqual({
@@ -101,6 +116,13 @@ describe("emptyMessagingForm / bindingsToForm", () => {
finalReplyOnly: false,
renderMarkdown: true,
},
+ // WeChat's sub-state is the preferences and the clear box: its token has no field.
+ wechat: {
+ clearToken: false,
+ linePerMessage: false,
+ finalReplyOnly: false,
+ renderMarkdown: true,
+ },
});
});
@@ -137,8 +159,14 @@ describe("emptyMessagingForm / bindingsToForm", () => {
finalReplyOnly: false,
renderMarkdown: true,
},
+ wechat: {
+ clearToken: false,
+ linePerMessage: false,
+ finalReplyOnly: false,
+ renderMarkdown: true,
+ },
});
- // All three coexist: every saved channel loads its own non-secret fields.
+ // All of them 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");
@@ -549,3 +577,66 @@ describe("the QQ channel", () => {
expect(formTestable(half, false)).toBe(true);
});
});
+
+describe("the WeChat channel", () => {
+ it("loads preferences and nothing else, having no credential field to load one into", () => {
+ const form = bindingsToForm([STORED_WECHAT]);
+ expect(form.channel).toBe("wechat");
+ expect(form.wechat).toEqual({
+ clearToken: false,
+ linePerMessage: true,
+ finalReplyOnly: false,
+ renderMarkdown: false,
+ });
+ });
+
+ it("submits preferences alone, and cannot fail validation because nothing is typed", () => {
+ const form = bindingsToForm([STORED_WECHAT]);
+ expect(formToPut(form, true)).toEqual({
+ ok: true,
+ channel: "wechat",
+ // Always sent, like the other channels': an omitted flag means "keep", which would
+ // leave no way to turn one back off.
+ body: { linePerMessage: true, finalReplyOnly: false, renderMarkdown: false },
+ });
+ });
+
+ it("sends the clear flag only when there is a stored token for it to drop", () => {
+ const form = bindingsToForm([STORED_WECHAT]);
+ form.wechat.clearToken = true;
+ expect(formToPut(form, true)).toEqual({
+ ok: true,
+ channel: "wechat",
+ body: {
+ clearBotToken: true,
+ linePerMessage: true,
+ finalReplyOnly: false,
+ renderMarkdown: false,
+ },
+ });
+ // A checked box on a binding with nothing stored asks the server to drop nothing.
+ expect(formToPut(form, false)).toEqual({
+ ok: true,
+ channel: "wechat",
+ body: { linePerMessage: true, finalReplyOnly: false, renderMarkdown: false },
+ });
+ });
+
+ it("routes its probe and its dirty/testable checks to its own fields", () => {
+ const form = bindingsToForm([STORED_WECHAT]);
+ // No body at all: the probe reads the stored binding, there being no draft to send.
+ expect(formToTest(form)).toEqual({ channel: "wechat" });
+
+ const baseline = bindingsToForm([STORED_WECHAT]);
+ expect(formDirty(form, baseline)).toBe(false);
+ form.wechat.renderMarkdown = !form.wechat.renderMarkdown;
+ expect(formDirty(form, baseline)).toBe(true);
+ const cleared = bindingsToForm([STORED_WECHAT]);
+ cleared.wechat.clearToken = true;
+ expect(formDirty(cleared, baseline)).toBe(true);
+
+ // Only a stored token is testable: this channel has no draft credential, ever.
+ expect(formTestable(emptyMessagingForm("wechat"), true)).toBe(true);
+ expect(formTestable(emptyMessagingForm("wechat"), false)).toBe(false);
+ });
+});
diff --git a/packages/web/test/session-row-menu.test.ts b/packages/web/test/session-row-menu.test.ts
index bff487ec..0aa0c732 100644
--- a/packages/web/test/session-row-menu.test.ts
+++ b/packages/web/test/session-row-menu.test.ts
@@ -29,7 +29,7 @@ import {
sessionRowMenuItem,
} from "../src/components/ui/session-row-menu";
import type { SessionRowAction } from "../src/components/ui/session-row-menu";
-import { MESSAGING_ICON } from "../src/components/ui/icons";
+import { MESSAGING_RELAY_ICON } from "../src/components/ui/icons";
import { setActiveStrings, zh } from "../src/lib/strings";
import { en } from "../src/lib/strings-en";
@@ -127,7 +127,9 @@ describe("sessionRowMenuItem", () => {
(a) => sessionRowMenuItem(a, RESTING).icon,
);
expect(new Set(icons).size).toBe(icons.length);
- expect(icons).toEqual([PIN_ICON, PENCIL_ICON, MESSAGING_ICON, ARCHIVE_ICON, TRASH_ICON]);
+ // Remote control wears the same paper plane the session row flies while it is relaying:
+ // the action and the mark it produces are one feature.
+ expect(icons).toEqual([PIN_ICON, PENCIL_ICON, MESSAGING_RELAY_ICON, ARCHIVE_ICON, TRASH_ICON]);
});
it("flips archive's label and glyph on an archived row", () => {
diff --git a/packages/web/test/wechat-scan-connect.test.ts b/packages/web/test/wechat-scan-connect.test.ts
new file mode 100644
index 00000000..bdfbe805
--- /dev/null
+++ b/packages/web/test/wechat-scan-connect.test.ts
@@ -0,0 +1,161 @@
+/**
+ * The WeChat scan-to-connect block: what it renders, and the decision its poll loop makes on
+ * each answer.
+ *
+ * It carries more states than QQ's, and that is what most of this file is about. WeChat
+ * separates SCANNING from confirming and may interpose a pairing code shown on the phone, so
+ * two of its answers change the panel's caption while leaving the code up — tearing the QR
+ * down mid-flow would strand a user who is looking at their phone. Two more end the flow
+ * without being failures or lapses: a code spent on wrong pairing digits, and a bot that was
+ * already bound here, which is news rather than an error.
+ *
+ * The QR itself is QQ's component, so its rendering rules are asserted there; what is
+ * asserted here is that this panel reaches for it rather than growing a second one.
+ *
+ * The loop is tested by value rather than by mounting: this package's vitest runs in `node`,
+ * deliberately, so the classification lives in a pure function (`wechatScanStep`, the
+ * `updateCheckOutcome` idiom) and the effects around it stay a thin shell.
+ */
+import { describe, expect, it } from "vitest";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import type { WeChatBindingInfo, WeChatScanPollResponse } from "@prismshadow/penguin-server/api";
+import { ApiError } from "../src/api/client";
+import { WeChatScanConnect, wechatScanStep } from "../src/features/messaging/wechat-scan-connect";
+import type { WeChatScanTally } from "../src/features/messaging/wechat-scan-connect";
+import { S, zh } from "../src/lib/strings";
+import { en } from "../src/lib/strings-en";
+
+describe("WeChatScanConnect", () => {
+ const render = (opts: { enabled?: boolean; bound?: boolean } = {}) =>
+ renderToStaticMarkup(
+ createElement(WeChatScanConnect, {
+ sessionId: "session-1",
+ enabled: opts.enabled ?? false,
+ bound: opts.bound ?? false,
+ onBound: () => {},
+ }),
+ );
+
+ it("offers the scan as a control alone, with its explanation disclosed elsewhere", () => {
+ const html = render();
+ expect(html).toContain(S.wechat.scanStart);
+ // What scanning is, and that it is the ONLY way to bind this channel, is semantics: the
+ // setup fold says it. A neighbouring button is not a title for a standing sentence.
+ expect(html).not.toContain(S.wechat.scanOnly);
+ // Nothing is requested until the user asks: no code exists on first render.
+ expect(html).not.toContain(S.wechat.scanWaiting);
+ });
+
+ it("offers to replace a credential rather than to connect once one is stored", () => {
+ // The same control, two meanings: with a token saved, scanning rebinds.
+ expect(render({ bound: true })).toContain(S.wechat.scanRescan);
+ expect(render({ bound: true })).not.toContain(S.wechat.scanStart);
+ });
+
+ it("gates the scan while the connection is enabled, and says why", () => {
+ const html = render({ enabled: true });
+ expect(html).toContain("disabled=");
+ // A rebind would swap the credential under a live connector, so it is refused with a
+ // reason rather than silently done.
+ expect(html).toContain(`title="${S.wechat.scanDisableFirst}"`);
+ expect(render()).not.toContain(`title="${S.wechat.scanDisableFirst}"`);
+ });
+});
+
+describe("wechatScanStep", () => {
+ const fresh: WeChatScanTally = { failures: 0, refreshes: 0 };
+ const ok = (res: WeChatScanPollResponse) => ({ ok: true, res }) as const;
+ const failed = (error: unknown) => ({ ok: false, error }) as const;
+
+ it("keeps waiting while nothing has happened yet", () => {
+ expect(wechatScanStep(ok({ status: "pending" }), fresh)).toEqual({ kind: "wait" });
+ });
+
+ it("reports progress without taking the code down, which is what the phone is still for", () => {
+ // Both are mid-flow: the QR is still the thing being authorized, and only the caption
+ // (and, for the second, the pairing-code input) changes.
+ expect(wechatScanStep(ok({ status: "scanned" }), fresh)).toEqual({
+ kind: "progress",
+ status: "scanned",
+ });
+ expect(wechatScanStep(ok({ status: "need_verify_code" }), fresh)).toEqual({
+ kind: "progress",
+ status: "need_verify_code",
+ });
+ });
+
+ it("hands the binding on, so the editor adopts it without a second GET", () => {
+ const binding = { channel: "wechat", botId: "bot_9001" } as WeChatBindingInfo;
+ expect(wechatScanStep(ok({ status: "completed", botId: "bot_9001", binding }), fresh)).toEqual({
+ kind: "bound",
+ botId: "bot_9001",
+ binding,
+ });
+ });
+
+ it("ends on a spent pairing code, which polling the same handle cannot recover", () => {
+ expect(wechatScanStep(ok({ status: "blocked" }), fresh)).toEqual({
+ kind: "stop",
+ notice: S.wechat.scanBlocked,
+ tone: "error",
+ // The platform declared the code spent, so the server consumed the task on that poll.
+ releaseTask: false,
+ });
+ });
+
+ it("reports an already-bound bot as news rather than as a failure", () => {
+ // Nothing was saved because nothing needed to be: the existing binding still works, and
+ // a red toast would tell the user to fix something that is not broken.
+ expect(wechatScanStep(ok({ status: "already_bound" }), fresh)).toEqual({
+ kind: "stop",
+ notice: S.wechat.scanAlreadyBound,
+ tone: "info",
+ releaseTask: false,
+ });
+ });
+
+ it("rides out a transient failure rather than taking the code off the screen", () => {
+ // The user is walking to their phone when one poll 502s. Tearing the panel down there
+ // means their scan lands on a task the panel already abandoned and binds nothing.
+ const error = new ApiError(502, "wechat_scan_failed", "bad gateway");
+ expect(wechatScanStep(failed(error), fresh)).toEqual({ kind: "wait" });
+ expect(wechatScanStep(failed(error), { failures: 1, refreshes: 0 })).toEqual({ kind: "wait" });
+ // Failing over and over is not transient any more. Giving up releases the task: nothing
+ // resolved it, so the server would otherwise hold its handle until the sweep.
+ expect(wechatScanStep(failed(error), { failures: 2, refreshes: 0 })).toEqual({
+ kind: "stop",
+ notice: S.wechat.scanFailed("bad gateway"),
+ tone: "error",
+ releaseTask: true,
+ });
+ // One answer that came back resets the run — the loop passes failures: 0 again.
+ expect(wechatScanStep(ok({ status: "pending" }), { failures: 2, refreshes: 0 })).toEqual({
+ kind: "wait",
+ });
+ });
+
+ it("replaces a lapsed code, but a bounded number of times", () => {
+ expect(wechatScanStep(ok({ status: "expired" }), fresh)).toEqual({ kind: "refresh" });
+ expect(wechatScanStep(ok({ status: "expired" }), { failures: 0, refreshes: 2 })).toEqual({
+ kind: "refresh",
+ });
+ // A platform reporting codes it just created as expired would otherwise loop
+ // create/poll for as long as the panel stays open.
+ expect(wechatScanStep(ok({ status: "expired" }), { failures: 0, refreshes: 3 })).toEqual({
+ kind: "stop",
+ notice: S.wechat.scanExpiredRepeatedly,
+ tone: "error",
+ releaseTask: false,
+ });
+ });
+
+ it("names no position for the code, which wraps above the text in a narrow panel", () => {
+ // The waiting panel is `flex flex-wrap`: in the dock or on a phone the steps sit BELOW
+ // the QR, so copy that says "the code on the left" is wrong exactly where it is read.
+ for (const dict of [zh, en]) {
+ expect(dict.wechat.scanSteps).not.toMatch(/左侧|右侧|left|right/);
+ expect(dict.wechat.verifyPrompt).not.toMatch(/左侧|右侧|left|right/);
+ }
+ });
+});