🤖 Open-source, local-first alternative to Grok Bot, OpenAI dots and Claude Duet. Your own AI bots on any model: GPT, Claude, Gemini, Grok, DeepSeek, Kimi, GLM and 70+ more through one Modelflare key. Reach them in the app, WeChat or Feishu; they remember you, work in the background, run commands and use your computer. Pay per use.
Python ai-agentai-assistantchatbotclaudecomputer-usedeepseekdesktop-appdshelectronfeishugeminigptgrokllmlocal-firstmodelflaremulti-modelopenai-compatiblepersonal-ai-agentwechat
feat: the first Feishu sender becomes the owner; WeChat holds undeliverable replies until the user writes again
Marla9d165ce00bd9
diff --git a/README.md b/README.mdindex 93f649b..0d0de10 100644--- a/README.md+++ b/README.md@@ -240,8 +240,8 @@ docker exec amb cat /data/ui-token # 然后打开 http://<主机>:3600/?token=## 🔒 本地优先,也好看- **数据留在你手里。** 对话、记忆、文件和 API Key 都存放在你的设备上。本地控制台只监听 `127.0.0.1`,桌面版每次启动都会生成新的访问令牌。-- **只听主人的。** 机器人默认只回应主人(扫码登录的微信、你在应用里设的飞书主人)和你允许的人。其他人发消息只会收到一句提示,不会调用模型;你在信息面板里,或在聊天里回复「同意 编号」放行。-- **回复不会丢。** 回复先存到本地再发;网络断了会自动重试,应用重启后接着发,发不出去的会在信息面板里告诉你原因。+- **只听主人的。** 机器人默认只回应主人(扫码登录的微信;飞书连上后第一个给它发消息的人,也就是你)和你允许的人。其他人发消息只会收到一句提示,不会调用模型;你在信息面板里,或在聊天里回复「同意 编号」放行。+- **回复不会丢。** 回复先存到本地再发;网络断了会自动重试,应用重启后接着发;你在微信里超过 24 小时没说话时,回复先留着,等你下次发消息时一起送到。- **遥测保持关闭。** 内置电脑操作驱动的遥测已关闭,内置网关以关闭自动更新的方式运行。- **浅色、深色或跟随系统。** 六个机器人角色,眼睛会跟着你的鼠标转。- **托盘与开机自启。** 关闭窗口会收到托盘;macOS 和 Windows 支持开机自启。diff --git a/README_en.md b/README_en.mdindex db7e076..b500ed5 100644--- a/README_en.md+++ b/README_en.md@@ -240,8 +240,8 @@ A bot is more than a chat window: it has a persona, a default model, its own wor## 🔒 Local-first, and easy on the eyes- **Your data stays with you.** Conversations, memory, files and API keys are stored on your device. The local console listens on `127.0.0.1` only, and the desktop app generates a fresh access token on every launch.-- **It answers to you.** By default a bot replies only to its owner (the WeChat account that scanned the QR code, or the Feishu user you mark as owner) and the people you allow. Anyone else gets a one-line notice and no model is called; you let them in from the info panel, or by replying `yes <code>` in chat.-- **Replies are not lost.** A reply is saved locally before it is sent; network errors are retried, sending resumes after a restart, and anything that cannot be delivered is listed in the info panel with the reason.+- **It answers to you.** By default a bot replies only to its owner (the WeChat account that scanned the QR code; on Feishu, the first person to message it after you connect it, which is you) and the people you allow. Anyone else gets a one-line notice and no model is called; you let them in from the info panel, or by replying `yes <code>` in chat.+- **Replies are not lost.** A reply is saved locally before it is sent; network errors are retried, sending resumes after a restart, and when WeChat's 24-hour window has closed the reply waits and arrives with your next message.- **Telemetry kept off.** Telemetry in the bundled computer-use driver is switched off, and the built-in gateway runs with auto-update disabled.- **Light, dark or follow the system.** Six bot characters, and their eyes follow your pointer.- **Tray and autostart.** Close the window to hide to the tray; autostart is available on macOS and Windows.diff --git a/docs/development.md b/docs/development.mdindex 95cd440..41619c5 100644--- a/docs/development.md+++ b/docs/development.md@@ -109,7 +109,7 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令## 界面- 侧栏:机器人列表(头像 + 名称 + 最近一条消息),+ 新建,右键 重命名 / 删除;左下角账户按钮打开设置(`⌘/Ctrl+,`)。-- 对话页:顶部悬浮的机器人名称胶囊打开信息面板(`⌘/Ctrl+⇧+I`:渠道、使用请求、待审批、没发出去的消息、记忆、最近会话,⚙ 进机器人设置);回复流式显示(Markdown、代码块一键复制),可随时停止(`Esc`);审批与提问以卡片形式出现在对话里;向上翻阅时不会被拉回底部。+- 对话页:顶部悬浮的机器人名称胶囊打开信息面板(`⌘/Ctrl+⇧+I`:渠道、使用请求、待审批、记忆、最近会话,⚙ 进机器人设置);回复流式显示(Markdown、代码块一键复制),可随时停止(`Esc`);审批与提问以卡片形式出现在对话里;向上翻阅时不会被拉回底部。- 命令面板 `⌘/Ctrl+K`;外观(跟随系统 / 浅色 / 深色)在 设置 → 常规。- 视觉:中性色与组件改编自 magpie 的界面(MIT),强调色为 Modelflare 荧光黄绿 `#d7ff00`。设计系统说明见 `ui/design/README.md`。@@ -136,7 +136,7 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令代理跑在你自己的电脑上(甚至可能是完全权限),所以默认**只有主人和你允许的人**能和机器人对话,每个机器人、每个渠道分开算(`src/core/access.ts`):-- **主人**:微信是扫码登录的那个微信;飞书在应用里设——第一个给机器人发消息的人会出现在信息面板的「使用请求」里,点「设为主人」(多半就是你自己)。本机的网页对话不受限制。+- **主人**:微信是扫码登录的那个微信;飞书用 App ID / App Secret 连接、不扫码,连上之后**第一个给机器人发单聊消息的人**就是主人(先到先得)——连上后用你自己的飞书给机器人发一句话就完成绑定,这条消息照常回复。扫码时没拿到扫码者的微信也一样。机器人设置 → 谁能使用 里显示「飞书主人:…(第一个发消息的人)」,点「更换」(要确认)清掉主人,下一个发消息的人成为主人;换一个飞书应用或断开飞书时也会清掉。拒绝过的人不会成为主人。本机的网页对话不受限制。- **其他人**发消息:只收到一句「你还没有被允许使用这个机器人,已通知主人」(同一个人每小时最多一次),不进队列、不调用模型、不花钱。请求出现在信息面板(允许 / 拒绝),也会带 4 位配对码发给主人(每个机器人每小时最多 3 条;主人 24 小时内在那个渠道说过话才发得出去),主人在聊天里回复「同意 1234」/「拒绝 1234」即可。配对码不会和工具审批的编号撞。被拒绝的人之后发什么都不回。- 允许名单在 机器人设置 → 谁能使用 里,可以移除(移除后他再发消息会重新申请);`/status` 也会显示。- 升级时,已经和机器人有单聊会话的人自动加入允许名单(标为「升级前已在使用」),不会被拦在外面;换一个微信重新扫码时,原来的主人也留在名单里。@@ -148,7 +148,8 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令- 同一会话按顺序一条一条发;网络或平台临时出错时自动重试(5 秒起,逐步拉长到 5 分钟),渠道没连上时等它连上。- 应用退出或崩溃后,重启时接着发,已经发出去的不会再发(长回复分段发,从没发的那段接着发)。每条消息的 id 由收到的那条消息推出来,同一条消息被平台重复投递也只有一个最终回复;只有恰好在发送途中崩溃的那一段可能再发一次——它带着固定的飞书 `uuid`(飞书 1 小时内去重)和微信 `client_id`。-- 再也发不出去的(微信对方超过 24 小时没说话、本轮 10 条配额用完、等待超过一天、平台多次拒绝)标记出来并写明原因,显示在信息面板的「没发出去的消息」里,也记在诊断信息里。+- 微信只能在对方 24 小时内发过消息时回复,每条消息之后最多回 10 条。这时发不了的消息不丢,先留着(held),等对方下次发消息时先发出去:几条文字合成一条「你不在时:…」(一条微信放得下就合,文件照原样),排在这次的回复前面,顺序不变、只发一次。留着的最多 7 天;“收到”、审批提示这类过一会儿就没意义的照旧按自己的期限。+- 再也发不出去的(平台多次拒绝、等待太久)标记出来并写明原因,记在日志和诊断信息里。## 电脑操作(Computer Use)@@ -174,7 +175,7 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令- `cardkit:card:write`(创建与更新卡片,用于流式回复)3. 先在本程序信息面板的「渠道 → 飞书」里填入 App ID / App Secret 并保存(长连接需要程序在线才能保存下一步)。4. 事件与回调 → 订阅方式选「**使用长连接接收事件**」,添加事件 `im.message.receive_v1`。-5. 发布版本并在可用范围内添加自己,然后在飞书里私聊机器人。+5. 发布版本并在可用范围内添加自己,然后用你自己的飞书私聊机器人发一句话:连上后第一个发消息的人就是飞书主人(见「谁能使用机器人」)。说明:当前只处理单聊(p2p),群聊消息会被忽略。diff --git a/docs/development_en.md b/docs/development_en.mdindex 46e4acb..59c6ae6 100644--- a/docs/development_en.md+++ b/docs/development_en.md@@ -109,7 +109,7 @@ Inside the container the console listens on 0.0.0.0, so token access is enforced## Interface- Sidebar: bot list (avatar + name + latest message), + New, right-click to rename / delete; the account button at the bottom-left opens Settings (`⌘/Ctrl+,`).-- Chat screen: the floating bot-name pill at the top opens the info panel (`⌘/Ctrl+⇧+I`: channels, requests, pending approvals, undelivered messages, memory, recent sessions; ⚙ opens bot settings). Replies stream in (Markdown, one-click copy for code blocks) and can be stopped at any time (`Esc`). Approvals and questions appear as cards in the chat. Scrolling up is never yanked back to the bottom.+- Chat screen: the floating bot-name pill at the top opens the info panel (`⌘/Ctrl+⇧+I`: channels, requests, pending approvals, memory, recent sessions; ⚙ opens bot settings). Replies stream in (Markdown, one-click copy for code blocks) and can be stopped at any time (`Esc`). Approvals and questions appear as cards in the chat. Scrolling up is never yanked back to the bottom.- Command palette `⌘/Ctrl+K`; appearance (system / light / dark) is in Settings → General.- Visuals: neutrals and components are adapted from magpie's UI (MIT); the accent is Modelflare's fluorescent yellow-green `#d7ff00`. The design system is described in `ui/design/README.md`.@@ -136,7 +136,7 @@ In agent mode each bot has a file permission preset. Switch it with the permissiThe agent runs on your own computer (possibly with full access), so by default **only the owner and people you allow** can talk to a bot, per bot and per channel (`src/core/access.ts`):-- **Owner**: on WeChat, the account that scanned the QR code; on Feishu you set it in the app: the first person who messages the bot shows up under "Requests" in the info panel, click "Make owner" (usually that is you). The local web chat is never restricted.+- **Owner**: on WeChat, the account that scanned the QR code. Feishu connects with an App ID and App Secret and no scan, so **the first person to message the bot one-to-one after it is connected** becomes the owner (trust on first use): once it is connected, send the bot one line from your own Feishu, and that message is answered as usual. A WeChat login that did not report the scanner's id works the same way. Bot settings → Who can use shows "Feishu owner: … (first to message)"; "Change" (after a confirmation) clears the owner so the next person to message becomes the owner. Switching to another Feishu app or disconnecting Feishu clears it too. People who were denied never become the owner. The local web chat is never restricted.- **Anyone else** gets a single line, "you are not allowed to use this bot yet, the owner has been told" (at most once an hour per person); the message is not queued, no model is called and nothing is spent. The request shows in the info panel (allow / deny) and is sent to the owner with a 4-digit pairing code (at most 3 per bot per hour, and only if the owner spoke on that channel in the last 24 hours); the owner replies `同意 1234` / `拒绝 1234` (or `yes 1234` / `no 1234`) in chat. Pairing codes never collide with tool-approval codes. People who were denied get no reply at all.- The allowlist is in Bot settings → Who can use; entries can be removed (they can ask again by sending a message). `/status` shows it too.- On upgrade, everyone who already had a direct conversation with a bot is put on its allowlist (marked "used before the upgrade"), so nobody is cut off; re-scanning with another WeChat account keeps the previous owner on the list.@@ -148,7 +148,8 @@ Final replies, delivered files, approval prompts and notices are written to an o- Messages to one conversation go out one at a time, in order. Network or platform errors are retried (from 5 s, backing off to 5 min); a channel that is offline is waited for.- After the app quits or crashes, it carries on at the next start, and what was already sent is not sent again (a long reply resumes from the first unsent part). Ids are derived from the incoming message, so a message the platform delivers twice still gets one final reply; only the part that was in flight at the moment of a crash may go out twice, and it carries a fixed Feishu `uuid` (Feishu dedupes for an hour) and WeChat `client_id`.-- Messages that can no longer be sent (on WeChat the person has not written for 24 hours or the 10-message quota is used up; waiting for more than a day; repeated platform rejections) are marked with the reason, listed in the info panel under "Undelivered messages", and included in the diagnostics.+- WeChat only lets a bot reply within 24 hours of the person's last message, and at most 10 times per message. A message that cannot go out for that reason is held, not dropped: the next time the person writes, held messages go out first, before the reply, in their original order and only once, with the text ones merged into one "你不在时:…" ("While you were away: …") message when they fit in one WeChat message (files go as they are). Held messages are kept for up to 7 days; short-lived ones such as the "received" note and approval prompts keep their own deadline.+- Messages that can no longer be sent (repeated platform rejections, waiting too long) are marked with the reason in the log and the diagnostics.## Computer use@@ -174,7 +175,7 @@ Each bot can turn computer use on or off, choose a backend and an approval mode- `cardkit:card:write` (create and update cards, used for streaming replies)3. First enter the App ID / App Secret in this app's info panel → Channels → Feishu and save (the long connection must be online before the next step can be saved).4. Events & callbacks → subscription mode: "**Receive events through persistent connection**", and add the event `im.message.receive_v1`.-5. Publish a version, add yourself to the availability scope, then message the bot one-to-one in Feishu.+5. Publish a version, add yourself to the availability scope, then send the bot one line from your own Feishu: the first person to message it after it is connected becomes its Feishu owner (see "Who can use a bot").Note: only one-to-one (p2p) chats are handled for now; group messages are ignored.diff --git a/docs/privacy.md b/docs/privacy.mdindex 99a8841..1f04f83 100644--- a/docs/privacy.md+++ b/docs/privacy.md@@ -28,7 +28,7 @@| 微信登录态与同步游标 | 数据目录内(`weixin/` 等) | 与微信 iLink 接口通信时会 | 腾讯微信 || 飞书 App ID / Secret | 数据目录内的配置 | 与飞书开放平台建立长连接时会 | 飞书 || 允许名单与使用请求 | `anymodel.db`:谁能用哪个机器人、陌生人发来的第一条消息(截断,帮你认出是谁) | 不会 | — |-| 待发送的回复 | `anymodel.db` 的出站队列:没发出去的消息内容和原因(发出去的留 7 天、发不出去的留 30 天后删除) | 发送时会 | 微信 / 飞书 |+| 待发送的回复 | `anymodel.db` 的出站队列:还没发出去的消息内容和原因,包括等对方下次发消息再发的微信消息(最多留 7 天;发出去的留 7 天、发不出去的留 30 天后删除) | 发送时会 | 微信 / 飞书 || 设置 | `config.json` | 不会 | — || 日志 | `logs/app.log`(按大小轮转) | 不会;「复制诊断信息」由你手动复制,密钥已替换成 `***` | — || 屏幕截图(电脑操作) | 不长期保存 | 会 | 作为模型请求的一部分,经 Modelflare 发给支持视觉的模型;不会转发到微信或飞书聊天,除非你要求作为文件发送 |diff --git a/docs/privacy_en.md b/docs/privacy_en.mdindex 4485fbe..2060c7a 100644--- a/docs/privacy_en.md+++ b/docs/privacy_en.md@@ -28,7 +28,7 @@ This document explains what AnyModelBot stores where, what leaves your device, a| WeChat sign-in state and sync cursor | Inside the data directory (`weixin/` and others) | When talking to the WeChat iLink API | Tencent WeChat || Feishu App ID / Secret | Configuration inside the data directory | When opening the long connection to the Feishu Open Platform | Feishu || Allowlist and access requests | `anymodel.db`: who may use which bot, and the first message a stranger sent (truncated, so you can tell who it is) | No | — |-| Replies waiting to be sent | `anymodel.db` outbox: unsent message content and the reason (sent ones are deleted after 7 days, undeliverable ones after 30) | When they are sent | WeChat / Feishu |+| Replies waiting to be sent | `anymodel.db` outbox: unsent message content and the reason, including WeChat messages held until the person writes again (kept up to 7 days; sent ones are deleted after 7 days, undeliverable ones after 30) | When they are sent | WeChat / Feishu || Settings | `config.json` | No | — || Logs | `logs/app.log` (rotated by size) | No; "Copy diagnostics" is something you copy by hand, with keys replaced by `***` | — || Screenshots (computer use) | Not kept long-term | Yes | Sent as part of the model request through Modelflare to a vision-capable model; never forwarded to WeChat or Feishu chats unless you ask for them as files |diff --git a/src/app.ts b/src/app.tsindex e0cbb8d..5d093b9 100644--- a/src/app.ts+++ b/src/app.ts@@ -149,10 +149,6 @@ export class App {});this.store = new Store(path.join(config.dataDir, "anymodel.db"));this.outbox = new Outbox(this.store);- this.outbox.onGone = (row) => {- const bot = this.store.getBot(row.botId);- this.notice("warn", `机器人「${bot?.name ?? row.botId}」有一条${row.channel === "weixin" ? "微信" : "飞书"}消息没能发出去:${row.error}`);- };this.access = new AccessControl(this.store, { notify: (to, text, id) => this.reach(to, text, id) });if (config.magpie.mode === "managed") {this.magpie = new MagpieSupervisor({ dataDir: config.dataDir, binPath: config.magpie.binPath || undefined });@@ -679,6 +675,8 @@ export class App {const prevOwner = this.store.getWeixinAccount(botId)?.ownerUserId;this.store.saveWeixinAccount({ botId, botToken: res.botToken, ilinkBotId: res.ilinkBotId, baseUrl: res.baseUrl, ownerUserId: res.userId });if (prevOwner && prevOwner !== res.userId) this.access.allow(botId, "weixin", prevOwner, "previous-owner");+ // 这次拿到了扫码者:之前没拿到时第一个发消息成为主人的人,也留在允许名单里+ if (res.userId) this.access.resetOwner(botId, "weixin", { keep: true });const bot = this.store.getBot(botId);if (bot && !bot.weixinEnabled) this.store.updateBot(botId, { weixinEnabled: true });await ch.weixin?.stop();diff --git a/src/channels/weixin/channel.ts b/src/channels/weixin/channel.tsindex 14ea4e1..6d02d50 100644--- a/src/channels/weixin/channel.ts+++ b/src/channels/weixin/channel.ts@@ -4,7 +4,7 @@ import { splitText } from "../../core/types.js";import { Dedup, KeyedQueue } from "../../core/queue.js";import type { BotRuntime } from "../../core/runtime.js";import type { OutboxBody, OutboxKind, OutboxRow, Store } from "../../store/db.js";-import { Gone, Later, Outbox, ReplyIds, stableId } from "../../core/outbox.js";+import { Gone, Held, Later, Outbox, ReplyIds, stableId, type HeldGroup } from "../../core/outbox.js";import { IlinkClient, MessageItemType, MessageType, WeixinApiError, hasDownloadableMedia, type InboundMedia, type MessageItem, type WeixinMessage } from "./api.js";import { StreamingMarkdownFilter } from "./markdown-filter.js";import { WeixinQuota } from "./quota.js";@@ -87,15 +87,48 @@ function transient(e: unknown): boolean {return !(x?.syscall && ["open", "read", "stat", "scandir"].includes(x.syscall));}-/** 能不能给这个人发:要有会话凭证、24 小时窗口没过、还有配额;不能就放弃(Gone),返回凭证 */+/** 能不能给这个人发:要有会话凭证、24 小时窗口没过、还有配额;不能就留着(Held),等他下次发消息;返回凭证 */function reachable(quota: WeixinQuota, userId: string): string {const peer = quota.peer(userId);- if (!peer?.contextToken) throw new Gone("对方还没有给机器人发过消息,微信不允许主动发送");- if (!quota.open(userId)) throw new Gone("对方超过 24 小时没有发消息,微信不再允许回复");- if (quota.remaining(userId) <= 0) throw new Gone("本轮可发送条数已用完(对方每发一条消息,24 小时内最多回复 10 条)");+ if (!peer?.contextToken) throw new Held("对方还没有给机器人发过消息,等他发消息后再发");+ if (!quota.open(userId)) throw new Held("对方超过 24 小时没有发消息,等他下次发消息时再发");+ if (quota.remaining(userId) <= 0) throw new Held("本轮可发送条数已用完(对方每发一条消息,24 小时内最多回复 10 条),等他下次发消息时再发");return peer.contextToken;}+/** 留着的消息在对方下次发消息时送达,开头加上这句 */+export const AWAY_PREFIX = "你不在时:";++/**+ * 对方又发消息了,留着给他的消息怎么发(Outbox.release 的 combine):相邻的文字合成一条「你不在时:…」(一条微信放得下就合),+ * 文件和发了一半的长回复照原样发,顺序不变。+ */+export function combineHeld(rows: OutboxRow[]): HeldGroup[] {+ const groups: HeldGroup[] = [];+ let cur: { rows: OutboxRow[]; texts: string[]; len: number } | undefined;+ const flush = () => {+ if (cur) groups.push({ rows: cur.rows, body: { text: AWAY_PREFIX + (cur.texts.length > 1 ? "\n" : "") + cur.texts.join("\n\n"), raw: true, away: true } });+ cur = undefined;+ };+ for (const r of rows) {+ const raw = r.body.text ?? "";+ if (r.kind === "file" || r.progress > 0 || !raw.trim()) {+ flush();+ groups.push({ rows: [r] });+ continue;+ }+ // 已经合成过的(又被留着)不再加前缀;Markdown 先按微信的规则过滤掉,合成的那条原样发+ const text = r.body.away ? raw.slice(AWAY_PREFIX.length).trim() : r.body.raw ? raw.trim() : filterMarkdown(raw);+ if (cur && cur.len + 2 + text.length > WEIXIN_CAPS.maxTextLength) flush();+ cur ??= { rows: [], texts: [], len: AWAY_PREFIX.length };+ cur.rows.push(r);+ cur.texts.push(text);+ cur.len += 2 + text.length;+ }+ flush();+ return groups;+}+/*** 把一条出站记录发到微信:文本按 4000 字切分,配额不够时截断并在末尾说明;文件走 CDN,发不出去改发一句说明。* 发送成功才扣配额(出站队列按会话一条一条发,先查后扣不会超发);每段带确定的 client_id。@@ -216,7 +249,7 @@ export class WeixinReply implements ReplySession {try {await deliverWeixin(this.client, this.quota, row, () => {}, false);} catch (e) {- if (!(e instanceof Gone)) throw e;+ if (!(e instanceof Gone) && !(e instanceof Held)) throw e;this.log.warn("weixin reply dropped", { userId: this.userId, reason: e.message });}}@@ -325,7 +358,7 @@ export class WeixinChannel {/*** 主动发到一个微信会话的回复(代理自己醒来的一轮:后台命令结束):和普通回复一样经出站队列,id 由 key 推出;- * 会话凭证、24 小时窗口和配额在发送时才查(deliverWeixin),发不出去在界面里看得到。+ * 会话凭证、24 小时窗口和配额在发送时才查(deliverWeixin),发不出去就留着,等对方下次发消息时先发。*/followUp(userId: string, key: string): ReplySession {const token = this.store.getWeixinPeer(this.botId, userId)?.contextToken ?? "";@@ -395,6 +428,8 @@ export class WeixinChannel {if (!this.dedup.firstSeen(id)) return;const userId = m.from_user_id;const peer = this.quota.onInbound(userId, m.context_token ?? "");+ // 对方又发消息了(24 小时窗口和配额重新开始):之前留着没发的先发,合成「你不在时:…」,排在这次的回复前面+ this.outbox.release(this.botId, "weixin", userId, combineHeld);const ev: InboundEvent = {id,channel: "weixin",diff --git a/src/core/access.ts b/src/core/access.tsindex 86ce673..41218a1 100644--- a/src/core/access.ts+++ b/src/core/access.ts@@ -1,8 +1,8 @@/*** 谁能和机器人对话:默认只有主人。代理跑在用户自己的电脑上(甚至可能是完全权限),陌生人找到机器人也不能驱动它。*- * - 主人:微信 = 扫码登录的那个微信;飞书(以及没拿到扫码者的微信)= 在应用里设的主人- * (第一个给机器人发消息的人会出现在信息面板的「使用请求」里,点「设为主人」)。+ * - 主人:微信 = 扫码登录的那个微信;飞书(以及没拿到扫码者的微信)= 连上之后第一个发单聊消息的人+ * (先到先得;这条消息照常处理)。机器人设置里可以「更换」:清掉主人,下一个发消息的人成为主人。* - 其他人发消息:登记成使用请求,只回一句"还没被允许"(同一个人每小时最多一次),不进队列、不碰模型、不花钱;* 请求出现在信息面板里,也会带配对码发给主人(每个机器人每小时最多 3 条),主人回复「同意 1234」即可。* - 允许的人进允许名单,在机器人设置里能看到、能移除;被拒绝的人不再回复。@@ -34,8 +34,8 @@ export type Notify = (to: { botId: string; channel: string; peerId: string }, teexport interface Owner {peerId: string;- /** login = 扫码登录的微信;app = 在应用里设的 */- via: "login" | "app";+ /** login = 扫码登录的微信;first-message = 连上之后第一个发消息的人 */+ via: "login" | "first-message";entryId?: string;}@@ -45,8 +45,13 @@ export function shortPeer(id: string): string {return s.length > 10 ? `…${s.slice(-6)}` : s;}+/** 名字,没有名字时是 id 的末尾几位 */+export function peerName(e: Pick<AccessEntry, "peerId" | "senderId" | "name">): string {+ return e.name && e.name !== e.peerId ? e.name : shortPeer(e.senderId || e.peerId);+}+export function whoText(e: Pick<AccessEntry, "channel" | "peerId" | "senderId" | "name">): string {- return `${CHANNEL_LABEL[e.channel] ?? e.channel}用户 ${e.name && e.name !== e.peerId ? e.name : shortPeer(e.senderId || e.peerId)}`;+ return `${CHANNEL_LABEL[e.channel] ?? e.channel}用户 ${peerName(e)}`;}const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n - 1) + "…" : s);@@ -61,14 +66,14 @@ export class AccessControl {return (this.opts.now ?? Date.now)();}- /** 某个渠道的主人:微信优先用扫码登录的人,其余是在应用里设的 */+ /** 某个渠道的主人:微信优先用扫码登录的人,其余是连上之后第一个发消息的人 */owner(botId: string, channel: string): Owner | undefined {if (channel === "weixin") {const o = this.store.getWeixinAccount(botId)?.ownerUserId;if (o) return { peerId: o, via: "login" };}const e = this.store.listAccess({ botId, channel, status: "owner" })[0];- return e ? { peerId: e.peerId, via: "app", entryId: e.id } : undefined;+ return e ? { peerId: e.peerId, via: "first-message", entryId: e.id } : undefined;}private isOwner(ev: InboundEvent): boolean {@@ -92,7 +97,7 @@ export class AccessControl {* 返回给他的一句话(同一个人每小时最多一次;被拒绝的人不回)。*/admit(ev: InboundEvent): { ok: true } | { ok: false; reply?: string } {- if (this.allowed(ev)) return { ok: true };+ if (this.claimOwner(ev) || this.allowed(ev)) return { ok: true };const now = this.now();let e = this.store.getAccess(ev.botId, ev.channel, ev.conversation.id);if (e?.status === "denied") return { ok: false };@@ -126,6 +131,37 @@ export class AccessControl {return { ok: false, reply: REFUSAL_TEXT };}+ /**+ * 这个渠道还没有主人(飞书刚连上、主人被更换、扫码时没拿到扫码者的微信):第一个发单聊消息的人成为主人,+ * 他的这条消息照常处理。拒绝过的人不算。+ */+ private claimOwner(ev: InboundEvent): boolean {+ if (ev.channel === "web" || ev.conversation.kind === "group" || this.owner(ev.botId, ev.channel)) return false;+ const cur = this.store.getAccess(ev.botId, ev.channel, ev.conversation.id);+ if (cur?.status === "denied") return false;+ const now = this.now();+ const decided = { status: "owner" as const, code: "", decidedAt: now, decidedBy: "first-message", updatedAt: now };+ if (cur) this.store.updateAccess(cur.id, decided);+ else+ this.store.putAccess({+ id: crypto.randomUUID(),+ botId: ev.botId,+ channel: ev.channel,+ peerId: ev.conversation.id,+ senderId: ev.sender.id,+ name: ev.sender.name ?? "",+ source: "first-message",+ text: clip(eventText(ev).replace(/\s+/g, " "), 200),+ requests: 1,+ createdAt: now,+ repliedAt: 0,+ notifiedAt: 0,+ ...decided,+ });+ log.info("access owner claimed by the first message", { bot: ev.botId, channel: ev.channel, peer: shortPeer(ev.conversation.id) });+ return true;+ }+/** 把新请求带配对码发给各渠道的主人(每个机器人每小时最多 NOTICE_LIMIT 条;超出的只在应用里显示) */private notifyOwners(e: AccessEntry): void {const now = this.now();@@ -180,22 +216,19 @@ export class AccessControl {}/**- * 设为这个渠道的主人(飞书;或没拿到扫码者的微信)。原来的主人改为普通允许。- * 扫码登录的微信已经是主人时不能改(重新扫码就换了)。+ * 更换主人(机器人设置里的「更换」、飞书换了一个应用):清掉这个渠道"第一个发消息"的主人,下一个发单聊消息的人成为主人。+ * 原来的主人移出名单(之后发消息要重新被允许,除非他就是下一个发消息的人);keep 时留在允许名单里(扫码拿到了扫码者的微信)。+ * 扫码登录的微信主人不在这里,重新扫码就换了。*/- setOwner(id: string, by: string): AccessEntry {- const e = this.store.getAccessById(id);- if (!e) throw new Error("记录不存在");- if (e.channel === "weixin" && this.store.getWeixinAccount(e.botId)?.ownerUserId) throw new Error("微信的主人是扫码登录的人;要换主人,请用那个微信重新扫码");+ resetOwner(botId: string, channel: string, opts: { keep?: boolean } = {}): boolean {const now = this.now();- for (const o of this.store.listAccess({ botId: e.botId, channel: e.channel, status: "owner" })) {- if (o.id !== id) this.store.updateAccess(o.id, { status: "allowed", updatedAt: now });+ const owners = this.store.listAccess({ botId, channel, status: "owner" });+ for (const o of owners) {+ if (opts.keep) this.store.updateAccess(o.id, { status: "allowed", source: "previous-owner", updatedAt: now });+ else this.store.deleteAccess(o.id);+ log.info("access owner reset", { bot: botId, channel, peer: shortPeer(o.peerId), kept: !!opts.keep });}- const was = e.status;- this.store.updateAccess(id, { status: "owner", code: "", decidedAt: now, decidedBy: by, updatedAt: now });- log.info("access owner set", { bot: e.botId, channel: e.channel, peer: shortPeer(e.peerId), by });- if (was === "pending") this.opts.notify?.({ botId: e.botId, channel: e.channel, peerId: e.peerId }, "你已被设为这个机器人的主人。以后有人想使用它时,我会在这里告诉你。", `access:${id}:owner:${now}`);- return this.store.getAccessById(id)!;+ return owners.length > 0;}/** 直接加入允许名单(迁移、换了扫码的微信、测试) */@@ -224,7 +257,7 @@ export class AccessControl {});}- /** 移除(允许名单里的人、被拒绝的人、在应用里设的主人):之后他再发消息会重新申请 */+ /** 移除(允许名单里的人、被拒绝的人):之后他再发消息会重新申请 */remove(id: string): boolean {const e = this.store.getAccessById(id);if (!e) return false;diff --git a/src/core/outbox.ts b/src/core/outbox.tsindex 4b5b177..547f2ea 100644--- a/src/core/outbox.ts+++ b/src/core/outbox.ts@@ -3,7 +3,9 @@* - 每条消息有确定的 id(由入站消息 id 推出来),同一 id 只写一次、只发一次;* - 同一会话按写入顺序一条一条发,前一条没发完,后面的等着;* - 临时失败按退避重试(5 秒起,翻倍到 5 分钟),渠道没在运行时等它上线;- * - 发不出去了(配额用完、超过 24 小时、过期、平台多次拒绝)标记 gone 并记下原因,界面里能看到;+ * - 要等对方先发消息才能发的(微信:超过 24 小时没说话、本轮配额用完)留着(held),对方下次发消息时按原来的顺序先发出去,+ * 能合并的合成一条「你不在时:…」,排在这次的回复前面;+ * - 再也发不出去了(平台多次拒绝、等待太久)标记 gone 并记下原因,只记在日志和诊断信息里;* - 应用重启后接着发。流式的中间内容和"正在输入"不经过这里。** 设计改编自 deepseek-ai/dsh-superagent-prototype(MIT,© 2026 DeepSeek Harness Team):src/app/outbox.ts 的回执 +@@ -17,13 +19,17 @@ const log = logger("outbox");/** 暂时不能发(渠道没上线、登录过期等):稍后再试,不算失败 */export class Later extends Error {}-/** 再也发不出去了:标记 gone,message 是给人看的原因 */+/** 再也发不出去了:标记 gone,message 是原因(日志、诊断信息) */export class Gone extends Error {}+/** 要等对方先发消息才能发(微信 24 小时窗口已过、本轮配额用完):留着,对方下次发消息时再发(见 release) */+export class Held extends Error {}/** 普通消息最长等多久(微信的会话凭证 24 小时有效,飞书也不该再补发一天前的回复) */export const OUTBOX_TTL_MS = 24 * 3600_000;/** 平台明确拒绝(有错误码)的,试这么多次就放弃 */export const REJECTIONS_BEFORE_GONE = 5;+/** 留着等对方发消息的,最多留多久(ack、审批提示这类短命的照旧按自己的期限) */+export const HOLD_TTL_MS = 7 * 86400_000;export interface OutboxInput {id: string;@@ -39,6 +45,12 @@ export interface OutboxInput {ttlMs?: number;}+/** 对方发消息后一起发的一组留着的消息:body 给了就合成这一条发,否则这组只有一条、照原样发 */+export interface HeldGroup {+ rows: OutboxRow[];+ body?: OutboxBody;+}+/** 渠道的发送函数:成功返回;Later / Gone / 其他错误(临时失败,会重试)。progress 记下长文本已发出的分段数 */export type Deliver = (row: OutboxRow, progress: (n: number) => void) => Promise<void>;@@ -69,8 +81,6 @@ export class Outbox {private scheduled = false;private started = false;private stopped = false;- /** 一条消息发不出去了(界面提示、日志) */- onGone: ((row: OutboxRow) => void) | undefined;constructor(private store: Store,@@ -122,6 +132,7 @@ export class Outbox {this.started = true;this.stopped = false;try {+ for (const r of this.store.listOutbox({ status: "held", limit: 500 })) if (r.expiresAt <= this.now()) this.gone(r, "等待太久,已不再发送");this.store.pruneOutbox(this.now());// 重启了:等着退避的不用再等,马上试一次this.store.resumeOutbox(this.now());@@ -155,12 +166,23 @@ export class Outbox {}}- /** 界面上"知道了" */- dismiss(id: string): boolean {- const row = this.store.getOutbox(id);- if (!row || row.status !== "gone") return false;- this.store.updateOutbox(id, { dismissed: true }, this.now());- return true;+ /**+ * 对方又发消息了:留着给他的消息放回队列,按原来的顺序排在这次回复的前面。+ * combine 决定哪几条合成一条发(每组第一条换成合并后的内容,其余标记 merged);不给就一条一条发。过期的不再发。+ */+ release(botId: string, channel: string, peerId: string, combine?: (rows: OutboxRow[]) => HeldGroup[]): number {+ const held = this.store.heldOutbox(`${botId}:${channel}:${peerId}`);+ if (!held.length) return 0;+ const now = this.now();+ const live = held.filter((r) => r.expiresAt > now || (this.gone(r, "等待太久,已不再发送"), false));+ for (const g of combine ? combine(live) : live.map((r): HeldGroup => ({ rows: [r] }))) {+ const [first, ...rest] = g.rows;+ this.store.updateOutbox(first.id, { status: "pending", due: now, error: "", ...(g.body ? { body: g.body, progress: 0 } : {}) }, now);+ for (const r of rest) this.store.updateOutbox(r.id, { status: "merged" }, now);+ }+ if (live.length) log.info(`releasing ${live.length} held message(s)`, { bot: botId, channel });+ this.kick();+ return live.length;}private kick(): void {@@ -223,6 +245,7 @@ export class Outbox {const msg = String((e as Error)?.message ?? e).slice(0, 300);const now = this.now();if (e instanceof Gone) return this.gone(row, msg);+ if (e instanceof Held) return this.hold(row, msg);// 关机中:留到下次启动if (this.stopped) return;const [base, max] = this.opts.retry ?? [5000, 300_000];@@ -238,13 +261,15 @@ export class Outbox {this.store.updateOutbox(row.id, { attempts, error: msg, due: now + delay }, now);}+ /** 留着等对方发消息:不算失败;普通消息最多留 HOLD_TTL_MS,短命的(ack、审批提示)照旧按自己的期限 */+ private hold(row: OutboxRow, reason: string): void {+ const expiresAt = row.expiresAt - row.createdAt >= OUTBOX_TTL_MS ? Math.max(row.expiresAt, row.createdAt + HOLD_TTL_MS) : row.expiresAt;+ this.store.updateOutbox(row.id, { status: "held", error: reason, expiresAt }, this.now());+ log.info("message held until the user writes again", { id: row.id, channel: row.channel, kind: row.kind, reason });+ }+private gone(row: OutboxRow, reason: string): void {this.store.updateOutbox(row.id, { status: "gone", error: reason }, this.now());log.warn("message gone", { id: row.id, channel: row.channel, kind: row.kind, reason });- try {- this.onGone?.({ ...row, status: "gone", error: reason });- } catch {- /* ignore */- }}}diff --git a/src/diagnostics.ts b/src/diagnostics.tsindex b4e4e88..895454d 100644--- a/src/diagnostics.ts+++ b/src/diagnostics.ts@@ -362,12 +362,13 @@ export function diagnosticsStatus(app: App): Record<string, unknown> {};}-/** 出站队列:等着发的、最近 7 天没发出去的(只有数量和原因,不含消息内容) */+/** 出站队列:等着发的、留着等对方发消息的、最近 7 天没发出去的(只有数量和原因,不含消息内容) */function outboxSummary(app: App): Record<string, unknown> | undefined {try {const pending = app.store.listOutbox({ status: "pending", limit: 500 });+ const held = app.store.listOutbox({ status: "held", limit: 500 });const gone = app.store.listOutbox({ status: "gone", since: Date.now() - 7 * 86400_000, limit: 500 });- return { pending: pending.length, retrying: pending.filter((r) => r.attempts > 0).length, lastError: pending.find((r) => r.error)?.error, gone7d: gone.length, lastGone: gone[0]?.error };+ return { pending: pending.length, retrying: pending.filter((r) => r.attempts > 0).length, lastError: pending.find((r) => r.error)?.error, held: held.length, gone7d: gone.length, lastGone: gone[0]?.error };} catch {return undefined;}@@ -402,7 +403,7 @@ export function diagnosticsReport(app: App, lines = 200): string {const ps = pwshReportLine(s.pwsh);if (ps) out.push(ps);const ob = s.outbox;- if (ob) out.push(`[出站队列] 等待发送 ${ob.pending} 条(重试中 ${ob.retrying})${ob.lastError ? ` · 最近错误:${ob.lastError}` : ""} · 最近 7 天没发出去 ${ob.gone7d} 条${ob.lastGone ? ` · 最近一次:${ob.lastGone}` : ""}`);+ if (ob) out.push(`[出站队列] 等待发送 ${ob.pending} 条(重试中 ${ob.retrying})${ob.lastError ? ` · 最近错误:${ob.lastError}` : ""} · 等对方发消息后再发 ${ob.held} 条 · 最近 7 天没发出去 ${ob.gone7d} 条${ob.lastGone ? ` · 最近一次:${ob.lastGone}` : ""}`);const m = app.lastDiagnostics.model;if (m) {out.push("");diff --git a/src/store/db.ts b/src/store/db.tsindex ed0f9ae..79c72e4 100644--- a/src/store/db.ts+++ b/src/store/db.ts@@ -89,7 +89,7 @@ export interface ApprovalRow {}/**- * 谁能和机器人对话(每个机器人、每个渠道):owner = 在应用里设的主人(微信的主人默认是扫码登录的人,不存在这里),+ * 谁能和机器人对话(每个机器人、每个渠道):owner = 连上之后第一个发消息的主人(微信的主人默认是扫码登录的人,不存在这里),* allowed = 允许名单,pending = 等主人处理的使用请求,denied = 被拒绝(不再回复,主人可移除)。* peerId 是单聊会话 id(微信 = 用户 id,飞书 = 单聊 chat_id)。*/@@ -103,7 +103,7 @@ export interface AccessEntry {senderId: string;name: string;status: AccessStatus;- /** 怎么来的:request(发消息申请)、migration(升级前已在使用)、previous-owner(换了扫码的微信)、app(在应用里添加) */+ /** 怎么来的:request(发消息申请)、first-message(第一个发消息,成了主人)、migration(升级前已在使用)、previous-owner(之前的主人)、app(在应用里添加) */source: string;/** 待处理请求的配对码(主人回复「同意 1234」);处理后清空 */code: string;@@ -120,7 +120,8 @@ export interface AccessEntry {notifiedAt: number;}-export type OutboxStatus = "pending" | "sent" | "gone";+/** pending 等着发;held 等对方先发消息(微信);sent 发出去了;merged 合进别的一条发出去了;gone 再也发不出去 */+export type OutboxStatus = "pending" | "held" | "sent" | "merged" | "gone";/** 出站消息的内容:文本(最终回复、提示、通知)、文件、带按钮的卡片(飞书审批) */export interface OutboxBody {text?: string;@@ -135,6 +136,8 @@ export interface OutboxBody {cardSeq?: number;/** 卡片上已经是最终全文 */shown?: boolean;+ /** 已经是合成的「你不在时:…」(再被留着时不再加前缀) */+ away?: boolean;}export type OutboxKind = "text" | "file" | "card" | "notice";/** 持久化的出站消息(见 core/outbox.ts) */@@ -155,13 +158,12 @@ export interface OutboxRow {/** 已经发出去的分段数(长文本分多条发,崩溃后从这里接着发) */progress: number;due: number;- /** 最近一次失败的原因;gone 时是发不出去的原因 */+ /** 最近一次失败的原因;held / gone 时是留着 / 发不出去的原因 */error: string;createdAt: number;updatedAt: number;expiresAt: number;sentAt: number;- dismissed: boolean;}type Row = Record<string, unknown>;@@ -216,7 +218,7 @@ CREATE TABLE IF NOT EXISTS outbox (reply_to TEXT NOT NULL DEFAULT '', status TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0,progress INTEGER NOT NULL DEFAULT 0, due INTEGER NOT NULL, error TEXT NOT NULL DEFAULT '',created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, expires_at INTEGER NOT NULL,- sent_at INTEGER NOT NULL DEFAULT 0, dismissed INTEGER NOT NULL DEFAULT 0);+ sent_at INTEGER NOT NULL DEFAULT 0);CREATE INDEX IF NOT EXISTS outbox_status ON outbox(status, seq);CREATE INDEX IF NOT EXISTS outbox_bot ON outbox(bot_id, status);`;@@ -731,7 +733,6 @@ export class Store {updatedAt: Number(r.updated_at),expiresAt: Number(r.expires_at),sentAt: Number(r.sent_at),- dismissed: Number(r.dismissed) === 1,};}/** 同一 id 只写一次;返回是否是新写入的 */@@ -752,30 +753,33 @@ export class Store {pendingOutbox(limit = 1000): OutboxRow[] {return (this.db.prepare("SELECT * FROM outbox WHERE status = 'pending' ORDER BY seq LIMIT ?").all(limit) as Row[]).map((r) => this.toOutbox(r));}- updateOutbox(id: string, patch: Partial<Pick<OutboxRow, "status" | "attempts" | "progress" | "due" | "error" | "sentAt" | "dismissed">>, now = Date.now()): void {- const cols: Record<string, string> = { status: "status", attempts: "attempts", progress: "progress", due: "due", error: "error", sentAt: "sent_at", dismissed: "dismissed" };+ updateOutbox(id: string, patch: Partial<Pick<OutboxRow, "status" | "attempts" | "progress" | "due" | "error" | "sentAt" | "expiresAt" | "body">>, now = Date.now()): void {+ const cols: Record<string, string> = { status: "status", attempts: "attempts", progress: "progress", due: "due", error: "error", sentAt: "sent_at", expiresAt: "expires_at", body: "body" };const keys = (Object.keys(patch) as Array<keyof typeof patch>).filter((k) => k in cols);if (!keys.length) return;- const vals = keys.map((k) => (typeof patch[k] === "boolean" ? (patch[k] ? 1 : 0) : (patch[k] as string | number)));+ const vals = keys.map((k) => (k === "body" ? JSON.stringify(patch.body) : (patch[k] as string | number)));this.db.prepare(`UPDATE outbox SET ${keys.map((k) => `${cols[k]} = ?`).join(", ")}, updated_at = ? WHERE id = ?`).run(...vals, now, id);}- listOutbox(opts: { botId?: string; status?: OutboxStatus; dismissed?: boolean; since?: number; limit?: number } = {}): OutboxRow[] {+ listOutbox(opts: { botId?: string; status?: OutboxStatus; since?: number; limit?: number } = {}): OutboxRow[] {const where: string[] = [];const args: Array<string | number> = [];if (opts.botId) (where.push("bot_id = ?"), args.push(opts.botId));if (opts.status) (where.push("status = ?"), args.push(opts.status));- if (opts.dismissed !== undefined) (where.push("dismissed = ?"), args.push(opts.dismissed ? 1 : 0));if (opts.since) (where.push("updated_at >= ?"), args.push(opts.since));const sql = `SELECT * FROM outbox ${where.length ? "WHERE " + where.join(" AND ") : ""} ORDER BY seq DESC LIMIT ${Math.max(1, Math.min(500, opts.limit ?? 100))}`;return (this.db.prepare(sql).all(...args) as Row[]).map((r) => this.toOutbox(r));}+ /** 留着等这个会话的对方发消息的,按写入顺序 */+ heldOutbox(conversationId: string): OutboxRow[] {+ return (this.db.prepare("SELECT * FROM outbox WHERE conversation_id = ? AND status = 'held' ORDER BY seq").all(conversationId) as Row[]).map((r) => this.toOutbox(r));+ }/** 启动时:等着退避重试的马上再试一次 */resumeOutbox(now = Date.now()): number {return Number(this.db.prepare("UPDATE outbox SET due = ? WHERE status = 'pending' AND due > ?").run(now, now).changes);}- /** 清理:发出去的留 7 天(这期间同一 id 不会再发),发不出去的留 30 天 */+ /** 清理:发出去的(含合进别的一条发的)留 7 天(这期间同一 id 不会再发),发不出去的留 30 天 */pruneOutbox(now = Date.now()): void {- this.db.prepare("DELETE FROM outbox WHERE (status = 'sent' AND updated_at < ?) OR (status = 'gone' AND updated_at < ?)").run(now - 7 * 86400_000, now - 30 * 86400_000);+ this.db.prepare("DELETE FROM outbox WHERE (status IN ('sent', 'merged') AND updated_at < ?) OR (status = 'gone' AND updated_at < ?)").run(now - 7 * 86400_000, now - 30 * 86400_000);}}diff --git a/src/web/server.ts b/src/web/server.tsindex dca8efb..6a768af 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -20,8 +20,8 @@ import type { ApprovalRow } from "../store/db.js";import { normalizeSettings } from "../agent/settings.js";import { scopeLabel } from "../agent/memory.js";import { pwshProbe, type PwshMode } from "../agent/pwsh.js";-import { shortPeer, whoText } from "../core/access.js";-import type { AccessEntry, OutboxRow } from "../store/db.js";+import { peerName, shortPeer, whoText } from "../core/access.js";+import type { AccessEntry } from "../store/db.js";const log = logger("web");const require = createRequire(import.meta.url);@@ -160,27 +160,6 @@ function publicAccess(e: AccessEntry) {};}-/** 出站队列里等着重发或发不出去的消息:发给谁、内容摘要、原因 */-function publicOutbox(app: App, r: OutboxRow) {- const owner = app.access.owner(r.botId, r.channel)?.peerId === r.peerId;- const e = owner ? undefined : app.store.getAccess(r.botId, r.channel, r.peerId);- const preview = r.kind === "file" ? `文件「${r.body.name ?? ""}」` : (r.body.text ?? "").replace(/\s+/g, " ").slice(0, 120);- return {- id: r.id,- channel: r.channel,- to: owner ? `${r.channel === "weixin" ? "微信" : "飞书"}主人` : whoText(e ?? { channel: r.channel, peerId: r.peerId, senderId: r.peerId, name: "" }),- kind: r.kind,- preview,- status: r.status,- attempts: r.attempts,- error: r.error,- createdAt: r.createdAt,- updatedAt: r.updatedAt,- due: r.due,- expiresAt: r.expiresAt,- };-}-/** 账户操作的错误:Modelflare 返回的状态码原样带给界面(没有状态码的网络错误按 502) */async function accountCall<T>(fn: () => Promise<T>): Promise<T> {try {@@ -668,8 +647,9 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strconst v = app.access.view(id);const owner = (ch: "weixin" | "feishu") => {const o = v.owners[ch];- const e = o?.entryId ? app.store.getAccessById(o.entryId) : undefined;- return o ? { peer: shortPeer(o.peerId), who: e ? whoText(e) : whoText({ channel: ch, peerId: o.peerId, senderId: o.peerId, name: "" }), via: o.via, entryId: o.entryId ?? null } : null;+ if (!o) return null;+ const e = (o.entryId ? app.store.getAccessById(o.entryId) : undefined) ?? { channel: ch, peerId: o.peerId, senderId: o.peerId, name: "" };+ return { peer: shortPeer(o.peerId), name: peerName(e), who: whoText(e), via: o.via };};return send(res, 200, {policy: v.policy,@@ -686,13 +666,14 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strif (!r) throw new HttpError(409, "这个请求已经处理过了");return send(res, 200, { entry: publicAccess(r) });}- if (seg[4] === "owner") {- try {- return send(res, 200, { entry: publicAccess(app.access.setOwner(entry.id, "web")) });- } catch (e) {- throw new HttpError(409, (e as Error).message);- }- }+ }+ // 更换主人:清掉"第一个发消息"的主人,下一个发单聊消息的人成为主人(扫码登录的微信要重新扫码)+ if (seg[2] === "access" && seg[3] === "owner" && seg.length === 5 && m === "DELETE") {+ const ch = seg[4];+ if (ch !== "weixin" && ch !== "feishu") throw new HttpError(404, "没有这个渠道");+ if (app.access.owner(id, ch)?.via === "login") throw new HttpError(409, "微信的主人是扫码登录的人;要换主人,请用那个微信重新扫码");+ app.access.resetOwner(id, ch);+ return send(res, 200, { ok: true });}if (seg[2] === "access" && seg.length === 4 && m === "DELETE") {const entry = app.store.getAccessById(decodeURIComponent(seg[3]));@@ -700,27 +681,18 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strapp.access.remove(entry.id);return send(res, 200, { ok: true });}- // —— 出站队列:等着重发的、发不出去的(信息面板) ——- if (sub === "outbox" && m === "GET") {- const waiting = app.store.listOutbox({ botId: id, status: "pending", limit: 50 }).filter((r) => r.attempts > 0 || r.error);- const failed = app.store.listOutbox({ botId: id, status: "gone", dismissed: false, since: Date.now() - 7 * 86400_000, limit: 50 });- return send(res, 200, { waiting: waiting.map((r) => publicOutbox(app, r)), failed: failed.map((r) => publicOutbox(app, r)) });- }- if (seg[2] === "outbox" && seg.length === 5 && seg[4] === "dismiss" && m === "POST") {- const row = app.store.getOutbox(decodeURIComponent(seg[3]));- if (!row || row.botId !== id) throw new HttpError(404, "消息不存在");- if (!app.outbox.dismiss(row.id)) throw new HttpError(409, "这条消息还在发送");- return send(res, 200, { ok: true });- }if (sub === "feishu" && m === "PUT") {const b = await readJson(req);const appId = String(b.appId ?? "").trim();const appSecret = String(b.appSecret ?? "").trim() || bot.feishuAppSecret;+ // 换了一个飞书应用:单聊会话都是新的,原来的主人对不上了,连上后第一个发消息的人成为主人+ if (appId !== bot.feishuAppId) app.access.resetOwner(id, "feishu");app.store.updateBot(id, { feishuAppId: appId, feishuAppSecret: appId ? appSecret : "" });await app.restartBot(id);return send(res, 200, app.channelStatus(id));}if (sub === "feishu" && m === "DELETE") {+ app.access.resetOwner(id, "feishu");app.store.updateBot(id, { feishuAppId: "", feishuAppSecret: "" });await app.restartBot(id);return send(res, 200, app.channelStatus(id));diff --git a/test/access.e2e.test.ts b/test/access.e2e.test.tsindex b08ad83..72d67ab 100644--- a/test/access.e2e.test.ts+++ b/test/access.e2e.test.ts@@ -1,7 +1,7 @@/*** 准入端到端:mock iLink + 假飞书 + 真实 App/Web(外部模型端点模式)。* 陌生人被拦(只回一句、不碰模型)→ 主人在微信里「同意 1234」或在应用里批准 → 对方能对话;拒绝、移除;- * 飞书在应用里设主人;升级前已在对话的人自动加入允许名单。+ * 飞书连上后第一个发消息的人成为主人(可以更换);升级前已在对话的人自动加入允许名单。*/import { describe, it, expect, beforeAll, afterAll } from "vitest";import fs from "node:fs";@@ -157,26 +157,20 @@ describe("微信:只有主人和允许的人", () => {});});-describe("飞书:在应用里设主人", () => {- it("还没有主人:第一个发消息的人被拦下,在应用里「设为主人」后能用,并且收到后续请求的通知", async () => {+describe("飞书:第一个发消息的人成为主人", () => {+ it("还没有主人:第一个发消息的人成为主人,这条消息照常回复;之后的人是使用请求,主人在飞书里「允许 1234」", async () => {// 模拟过了一小时:上面的请求通知不占这里的限额app.store.db.prepare("UPDATE access SET notified_at = 0").run();const ch = app.channels.get("default")!.feishu!;- feishu.onMessage!(feishuEvent("我是老板", { chatId: "oc_boss", senderOpenId: "ou_boss" }));- await ch.idle();- expect(feishu.texts.at(-1)).toBe(REFUSAL_TEXT);- const req = (await api("/bots/default/access")).json.requests.find((r: any) => r.channel === "feishu");- expect(req).toMatchObject({ text: "我是老板", peer: "oc_boss" });expect((await api("/bots/default/access")).json.owners.feishu).toBeNull();- const r = await api(`/bots/default/access/${req.id}/owner`, { method: "POST", body: {} });- expect(r.json.entry.status).toBe("owner");- await ch.idle();- expect(feishu.notices.at(-1)).toMatchObject({ chatId: "oc_boss", text: expect.stringContaining("主人") });- expect((await api("/bots/default/access")).json.owners.feishu).toMatchObject({ via: "app", peer: "oc_boss" });-- feishu.onMessage!(feishuEvent("帮我看看", { chatId: "oc_boss", senderOpenId: "ou_boss" }));+ const texts = feishu.texts.length;+ feishu.onMessage!(feishuEvent("我是老板", { chatId: "oc_boss", senderOpenId: "ou_boss" }));await ch.idle();- expect([...feishu.cards.values()].at(-1)).toBe("[mock-a] 你说:帮我看看");+ expect([...feishu.cards.values()].at(-1)).toBe("[mock-a] 你说:我是老板");+ expect(feishu.texts.length).toBe(texts);+ const acc = (await api("/bots/default/access")).json;+ expect(acc.owners.feishu).toEqual({ via: "first-message", peer: "oc_boss", name: "ou_boss", who: "飞书用户 ou_boss" });+ expect(acc.requests.filter((r: any) => r.channel === "feishu")).toEqual([]);// 同事来了:飞书主人和微信主人都收到配对码,主人在飞书里回复「允许 1234」const ownerWx = to(OWNER).length;@@ -197,6 +191,24 @@ describe("飞书:在应用里设主人", () => {expect([...feishu.cards.values()].at(-1)).toBe("[mock-a] 你说:谢谢");});+ it("更换:清掉主人,下一个发消息的人成为主人;扫码登录的微信主人不能这样换", async () => {+ const ch = app.channels.get("default")!.feishu!;+ expect((await api("/bots/default/access/owner/weixin", { method: "DELETE" })).status).toBe(409);+ expect((await api("/bots/default/access/owner/feishu", { method: "DELETE" })).status).toBe(200);+ expect((await api("/bots/default/access")).json.owners.feishu).toBeNull();+ feishu.onMessage!(feishuEvent("这是我自己的飞书", { chatId: "oc_me", senderOpenId: "ou_me" }));+ await ch.idle();+ expect([...feishu.cards.values()].at(-1)).toBe("[mock-a] 你说:这是我自己的飞书");+ expect((await api("/bots/default/access")).json.owners.feishu).toMatchObject({ via: "first-message", peer: "oc_me" });+ // 原来的主人要重新申请;被允许的同事照常能用+ feishu.onMessage!(feishuEvent("我还是主人吗", { chatId: "oc_boss", senderOpenId: "ou_boss" }));+ await ch.idle();+ expect(feishu.texts.at(-1)).toBe(REFUSAL_TEXT);+ feishu.onMessage!(feishuEvent("我还能用吗", { chatId: "oc_colleague", senderOpenId: "ou_colleague" }));+ await ch.idle();+ expect([...feishu.cards.values()].at(-1)).toBe("[mock-a] 你说:我还能用吗");+ });+it("升级前的飞书单聊照常能用", async () => {const ch = app.channels.get("default")!.feishu!;feishu.onMessage!(feishuEvent("老用户", { chatId: "oc_old", senderOpenId: "ou_old" }));diff --git a/test/access.unit.test.ts b/test/access.unit.test.tsindex e27189e..6e46f05 100644--- a/test/access.unit.test.ts+++ b/test/access.unit.test.ts@@ -97,30 +97,66 @@ describe("AccessControl", () => {expect(access.view("b").requests[0].text).toBe("hi again");});- it("Feishu: the first sender can be made owner in the app; later requests reach that owner, who can approve in Feishu", () => {+ it("Feishu: the first DM claims ownership and is handled normally; a second sender becomes a request the owner approves in Feishu", () => {const { access, sent } = setup();expect(access.owner("b", "feishu")).toBeUndefined();- access.admit(ev("feishu", "oc_me", "我是主人"));- const mine = access.view("b").requests[0];- access.setOwner(mine.id, "web");- expect(access.owner("b", "feishu")).toEqual({ peerId: "oc_me", via: "app", entryId: mine.id });- expect(access.allowed(ev("feishu", "oc_me", "x"))).toBe(true);- expect(sent.at(-1)).toMatchObject({ channel: "feishu", peerId: "oc_me", text: expect.stringContaining("主人") });-- access.admit(ev("feishu", "oc_colleague", "借用一下"));+ // 第一个发单聊消息的人:直接放行(这条消息照常处理),成为飞书主人,不通知谁+ expect(access.admit(ev("feishu", "oc_me", "我是主人"))).toEqual({ ok: true });+ expect(access.owner("b", "feishu")).toEqual({ peerId: "oc_me", via: "first-message", entryId: expect.any(String) });+ expect(access.view("b").requests).toEqual([]);+ expect(access.view("b").entries).toEqual([expect.objectContaining({ peerId: "oc_me", status: "owner", source: "first-message", senderId: "ou_oc_me", text: "我是主人" })]);+ expect(sent).toEqual([]);+ expect(access.admit(ev("feishu", "oc_me", "再来一句"))).toEqual({ ok: true });++ // 第二个、不同的人:使用请求,飞书主人和微信主人都收到配对码+ expect(access.admit(ev("feishu", "oc_colleague", "借用一下"))).toEqual({ ok: false, reply: REFUSAL_TEXT });const req = access.view("b").requests[0];- // 两个渠道的主人都收到- expect(sent.filter((s) => s.id.startsWith(`access:${req.id}`)).map((s) => s.channel).sort()).toEqual(["feishu", "weixin"]);+ expect(req).toMatchObject({ peerId: "oc_colleague", status: "pending" });+ expect(sent.filter((s) => s.id.startsWith(`access:${req.id}`)).map((s) => [s.channel, s.peerId]).sort()).toEqual([["feishu", "oc_me"], ["weixin", "[email protected]"]]);+ // 主人在飞书里回复「允许 1234」+ expect(access.handleReply(ev("feishu", "oc_colleague", `允许 ${req.code}`)).handled).toBe(false);expect(access.handleReply(ev("feishu", "oc_me", `允许 ${req.code}`)).handled).toBe(true);expect(access.allowed(ev("feishu", "oc_colleague", "x"))).toBe(true);+ expect(access.owner("b", "feishu")!.peerId).toBe("oc_me");+ });- // 换主人:原来的主人变成普通允许- access.setOwner(req.id, "web");- expect(access.owner("b", "feishu")!.peerId).toBe("oc_colleague");- expect(access.view("b").entries.find((e) => e.peerId === "oc_me")!.status).toBe("allowed");- // 扫码登录的微信主人不能在应用里改- access.admit(ev("weixin", "[email protected]", "hi"));- expect(() => access.setOwner(access.view("b").requests[0].id, "web")).toThrow(/扫码/);+ it("更换: resetting the owner removes them; the next DM claims it again; denied senders never claim", () => {+ const { access } = setup();+ // 同事抢先发了一句,成了飞书主人;有人发广告,被拒绝+ expect(access.admit(ev("feishu", "oc_wrong", "我先发"))).toEqual({ ok: true });+ access.admit(ev("feishu", "oc_spam", "广告"));+ access.decide(access.view("b").requests[0].id, false, "web");++ expect(access.resetOwner("b", "feishu")).toBe(true);+ expect(access.owner("b", "feishu")).toBeUndefined();+ expect(access.allowed(ev("feishu", "oc_wrong", "x"))).toBe(false);+ // 拒绝过的人不能认领+ expect(access.admit(ev("feishu", "oc_spam", "我又来了"))).toEqual({ ok: false });+ expect(access.owner("b", "feishu")).toBeUndefined();+ // 下一个发消息的人成为主人;原来的主人要重新申请+ expect(access.admit(ev("feishu", "oc_me", "绑定"))).toEqual({ ok: true });+ expect(access.owner("b", "feishu")!.peerId).toBe("oc_me");+ expect(access.admit(ev("feishu", "oc_wrong", "我还能用吗"))).toEqual({ ok: false, reply: REFUSAL_TEXT });+ // 允许名单里的人在没有主人时也会认领(升级前就在用的人多半就是你自己)+ access.resetOwner("b", "feishu");+ access.allow("b", "feishu", "oc_old", "migration");+ expect(access.admit(ev("feishu", "oc_old", "hi"))).toEqual({ ok: true });+ expect(access.owner("b", "feishu")!.peerId).toBe("oc_old");+ expect(access.resetOwner("b", "weixin")).toBe(false);+ });++ it("WeChat login without the scanner's id: the first DM claims ownership; a later login with an id keeps them on the allowlist", () => {+ const { store, access } = setup();+ store.saveWeixinAccount({ botId: "b", botToken: "t", ilinkBotId: "[email protected]", baseUrl: "http://x", ownerUserId: "" });+ expect(access.owner("b", "weixin")).toBeUndefined();+ expect(access.admit(ev("weixin", "[email protected]", "你好"))).toEqual({ ok: true });+ expect(access.owner("b", "weixin")).toMatchObject({ peerId: "[email protected]", via: "first-message" });+ expect(access.admit(ev("weixin", "[email protected]", "hi"))).toEqual({ ok: false, reply: REFUSAL_TEXT });+ // 重新扫码拿到了扫码者(App 里登录成功时这样调用)+ access.resetOwner("b", "weixin", { keep: true });+ store.saveWeixinAccount({ botId: "b", botToken: "t", ilinkBotId: "[email protected]", baseUrl: "http://x", ownerUserId: "[email protected]" });+ expect(access.owner("b", "weixin")).toEqual({ peerId: "[email protected]", via: "login" });+ expect(store.getAccess("b", "weixin", "[email protected]")).toMatchObject({ status: "allowed", source: "previous-owner" });});it("pairing codes and tool approval codes never collide", () => {diff --git a/test/outbox.e2e.test.ts b/test/outbox.e2e.test.tsindex bc7b887..df21be3 100644--- a/test/outbox.e2e.test.ts+++ b/test/outbox.e2e.test.ts@@ -2,7 +2,7 @@* 出站队列端到端:mock iLink + 真实 App。* - 回复发不出去时进程被 kill -9,重启后补发,而且只发一次;* - 同一条入站消息重启后被重复投递:回复的 id 相同,不会再发一遍;- * - 重启后发现对方超过 24 小时没说话 / 本轮配额用完:标记 gone,信息面板能看到原因,可以"知道了"。+ * - 重启后发现对方超过 24 小时没说话 / 本轮配额用完:留着;对方下次发消息时先收到合成的「你不在时:…」,再收到这次的回复,只收到一次。*/import { describe, it, expect, beforeAll, afterAll, afterEach } from "vitest";import { spawn, type ChildProcess } from "node:child_process";@@ -131,36 +131,61 @@ describe("出站队列:崩溃与重启", () => {expect(sentTo(OWNER, "只答一次")).toHaveLength(1);});- it("重启后对方的 24 小时窗口已过 / 配额已用完:标记 gone,信息面板能看到原因,可以「知道了」", async () => {+ it("重启后对方的 24 小时窗口已过 / 配额已用完:留着;对方下次发消息时先收到「你不在时:…」,再收到这次的回复,只收到一次", async () => {await startApp();ilink.state.sendDown = true;ilink.push(OWNER, "过期测试");await until(() => rows().some((r) => JSON.parse(r.body).text?.includes("过期测试") && r.attempts >= 1), 8000);+ // 这一轮已经答完(回复在出站队列里等着重发),不是被重启打断的+ await app!.channels.get("default")!.weixin!.idle();app!.access.allow("default", "weixin", "[email protected]", "test");await app!.stop();- // 关机期间:主人的窗口过了 24 小时;朋友那边还有一条没发出去的回复,而他这一轮的配额已经用完+ // 关机期间:主人的窗口过了 24 小时;朋友那边还有两条没发出去的回复,而他这一轮的配额已经用完const s = new Store(dbFile());const owner = s.getWeixinPeer("default", OWNER)!;s.upsertWeixinPeer({ ...owner, windowStartedAt: Date.now() - 25 * 3600_000 });s.upsertWeixinPeer({ botId: "default", userId: "[email protected]", contextToken: "ctx-f", quotaRemaining: 0, windowStartedAt: Date.now() });- s.insertOutbox({ id: "wx:default:test-quota:0", botId: "default", channel: "weixin", conversationId: "default:weixin:[email protected]", peerId: "[email protected]", kind: "text", body: { text: "配额测试的回复" }, replyTo: "", due: Date.now(), createdAt: Date.now(), expiresAt: Date.now() + 3600_000 });+ for (const [i, text] of ["配额测试的第一条", "配额测试的第二条"].entries()) {+ s.insertOutbox({ id: `wx:default:test-quota:${i}`, botId: "default", channel: "weixin", conversationId: "default:weixin:[email protected]", peerId: "[email protected]", kind: "text", body: { text }, replyTo: "", due: Date.now(), createdAt: Date.now(), expiresAt: Date.now() + 24 * 3600_000 });+ }s.close();ilink.state.sendDown = false;await startApp();- await until(() => rows().filter((r) => r.status === "gone").length >= 2, 8000);- const box = await api("/bots/default/outbox");- const reasons = box.json.failed.map((f: any) => [f.to, f.preview, f.error]);- expect(reasons).toEqual(- expect.arrayContaining([- ["微信主人", "[mock-a] 你说:过期测试", expect.stringMatching(/超过 24 小时/)],- ["微信用户 friend", "配额测试的回复", expect.stringMatching(/本轮可发送条数已用完/)],- ]),- );+ await until(() => rows().filter((r) => r.status === "held").length >= 3, 8000);+ await app!.outbox.idle();+ expect(rows().filter((r) => r.status === "gone")).toEqual([]);+ expect(rows().find((r) => JSON.parse(r.body).text?.includes("过期测试"))!.error).toMatch(/超过 24 小时/);expect(sentTo(OWNER, "过期测试")).toHaveLength(0);- // 状态里也记了一笔- expect((await api("/status")).json.notices.some((n: any) => n.text.includes("没能发出去"))).toBe(true);- for (const f of box.json.failed) expect((await api(`/bots/default/outbox/${encodeURIComponent(f.id)}/dismiss`, { method: "POST", body: {} })).status).toBe(200);- expect((await api("/bots/default/outbox")).json.failed).toEqual([]);+ expect(sentTo("[email protected]", "配额测试")).toHaveLength(0);+ // 没有"没发出去的消息"面板,也不再提示+ expect((await api("/bots/default/outbox")).status).toBe(404);+ expect((await api("/status")).json.notices.some((n: any) => n.text.includes("没能发出去"))).toBe(false);++ // 主人回来了:先收到留着的回复,再收到这次的回复+ const from = ilink.state.sent.length;+ const since = (user: string) => ilink.state.sent.slice(from).filter((x) => x.to === user).map((x) => x.text);+ ilink.push(OWNER, "我回来了");+ await until(() => since(OWNER).length >= 2, 8000);+ expect(since(OWNER)).toEqual(["你不在时:[mock-a] 你说:过期测试", "[mock-a] 你说:我回来了"]);+ // 朋友:两条合成一条,顺序不变+ ilink.push("[email protected]", "在吗");+ await until(() => since("[email protected]").length >= 2, 8000);+ expect(since("[email protected]")).toEqual(["你不在时:\n配额测试的第一条\n\n配额测试的第二条", "[mock-a] 你说:在吗"]);+ expect(app!.store.getOutbox("wx:default:test-quota:0")).toMatchObject({ status: "sent" });+ expect(app!.store.getOutbox("wx:default:test-quota:1")).toMatchObject({ status: "merged" });++ // 只送一次:重启、再发消息都不会再补发+ await app!.stop();+ await startApp();+ ilink.push(OWNER, "再来一句");+ ilink.push("[email protected]", "还在");+ await until(() => since(OWNER).length >= 3 && since("[email protected]").length >= 3, 8000);+ await app!.channels.get("default")!.weixin!.idle();+ await new Promise((r) => setTimeout(r, 300));+ expect(since(OWNER)).toEqual(["你不在时:[mock-a] 你说:过期测试", "[mock-a] 你说:我回来了", "[mock-a] 你说:再来一句"]);+ expect(since("[email protected]")).toHaveLength(3);+ expect(sentTo(OWNER, "你不在时")).toHaveLength(1);+ expect(sentTo("[email protected]", "你不在时")).toHaveLength(1);});});diff --git a/test/outbox.unit.test.ts b/test/outbox.unit.test.tsindex 9ab8996..7c93007 100644--- a/test/outbox.unit.test.ts+++ b/test/outbox.unit.test.ts@@ -1,5 +1,6 @@/**- * 出站队列:先落库再发、同一 id 只发一次、按会话排队、退避重试、Later 不计失败、Gone 记下原因、过期、重启后接着发。+ * 出站队列:先落库再发、同一 id 只发一次、按会话排队、退避重试、Later 不计失败、Gone 记下原因、过期、重启后接着发;+ * Held 留着,对方下次发消息时按顺序先发(合成「你不在时:…」),只发一次。* 以及微信 / 飞书的发送函数(配额、24 小时窗口、分段续发、卡片降级)。*/import { describe, it, expect } from "vitest";@@ -7,8 +8,8 @@ import fs from "node:fs";import os from "node:os";import path from "node:path";import { Store, type OutboxRow } from "../src/store/db.js";-import { Gone, Later, Outbox, REJECTIONS_BEFORE_GONE, stableId } from "../src/core/outbox.js";-import { deliverWeixin } from "../src/channels/weixin/channel.js";+import { Gone, HOLD_TTL_MS, Held, Later, OUTBOX_TTL_MS, Outbox, REJECTIONS_BEFORE_GONE, stableId } from "../src/core/outbox.js";+import { AWAY_PREFIX, combineHeld, deliverWeixin } from "../src/channels/weixin/channel.js";import { WeixinQuota } from "../src/channels/weixin/quota.js";import { deliverFeishu } from "../src/channels/feishu/card.js";import { FakeFeishu, until } from "./helpers.js";@@ -67,8 +68,6 @@ describe("Outbox", () => {it("Later waits without counting; Gone and repeated rejections are kept with the reason", async () => {const store = new Store(":memory:");const ob = new Outbox(store, { retry: [20, 40] });- const gone: OutboxRow[] = [];- ob.onGone = (r) => gone.push(r);let later = 3;ob.register("b", "weixin", async (row) => {if (row.body.text === "later" && later-- > 0) throw new Later("渠道没上线");@@ -84,10 +83,75 @@ describe("Outbox", () => {expect(store.getOutbox("g")).toMatchObject({ status: "gone", error: "本轮可发送条数已用完" });expect(store.getOutbox("r")).toMatchObject({ status: "gone", attempts: REJECTIONS_BEFORE_GONE - 1 });expect(store.getOutbox("r")!.error).toContain("ret=-2");- expect(gone.map((r) => r.id).sort()).toEqual(["g", "r"]);- // 界面"知道了"- expect(ob.dismiss("g")).toBe(true);- expect(store.listOutbox({ botId: "b", status: "gone", dismissed: false }).map((r) => r.id)).toEqual(["r"]);+ expect(store.listOutbox({ botId: "b", status: "gone" }).map((r) => r.id).sort()).toEqual(["g", "r"]);+ });++ it("Held waits for the user's next message; then the held messages go out once, in order, merged into 「你不在时:…」, before the reply", async () => {+ const store = new Store(":memory:");+ const ob = new Outbox(store, { retry: [20, 40] });+ let open = false;+ const sent: string[] = [];+ ob.register("b", "weixin", async (row) => {+ if (!open) throw new Held("对方超过 24 小时没有发消息,等他下次发消息时再发");+ sent.push(row.kind === "file" ? `[file ${row.body.name}]` : row.body.text!);+ });+ ob.start();+ await ob.send(input("h1", "**结果**:A 云最便宜"));+ await ob.send({ ...input("h2", "需批准:`rm -rf build/`", "u1"), body: { text: "需批准:`rm -rf build/`", raw: true } });+ await ob.send({ ...input("h3", "", "u1"), kind: "file", body: { path: "/tmp/r.md", name: "报告.md" } });+ await ob.send(input("h4", "第四条"));+ await ob.send(input("other", "别人的", "u2"));+ await ob.idle();+ expect(sent).toEqual([]);+ expect(store.listOutbox({ status: "held" }).map((r) => r.id).sort()).toEqual(["h1", "h2", "h3", "h4", "other"]);+ expect(store.getOutbox("h1")).toMatchObject({ attempts: 0, error: expect.stringMatching(/超过 24 小时/) });+ // 普通消息留得比 24 小时久,不会在对方回来前过期+ expect(store.getOutbox("h1")!.expiresAt - store.getOutbox("h1")!.createdAt).toBe(HOLD_TTL_MS);++ // u1 又发消息了:先发留着的(文字合成一条,文件照原样,顺序不变),再发这次的回复;u2 的继续留着+ open = true;+ expect(ob.release("b", "weixin", "u1", combineHeld)).toBe(4);+ await ob.send(input("reply", "这次的回复"));+ await ob.idle();+ // 普通回复先按微信的规则过滤 Markdown(图片去掉),审批提示原样+ expect(sent).toEqual([`${AWAY_PREFIX}\n**结果**:A 云最便宜\n\n需批准:\`rm -rf build/\``, "[file 报告.md]", `${AWAY_PREFIX}第四条`, "这次的回复"]);+ expect(["h1", "h2", "h3", "h4"].map((id) => store.getOutbox(id)!.status)).toEqual(["sent", "merged", "sent", "sent"]);+ expect(store.getOutbox("other")!.status).toBe("held");+ // 只发一次:再放一次、同一 id 再写一遍都不会重发+ expect(ob.release("b", "weixin", "u1", combineHeld)).toBe(0);+ await ob.send(input("h2", "需批准:`rm -rf build/`"));+ await ob.idle();+ expect(sent).toHaveLength(4);+ });++ it("held messages past their deadline are not sent when the user comes back; a merged message held again keeps one prefix", async () => {+ let now = 1_000_000;+ const store = new Store(":memory:");+ const ob = new Outbox(store, { now: () => now });+ let open = false;+ const sent: string[] = [];+ ob.register("b", "weixin", async (row) => {+ if (!open) throw new Held("本轮可发送条数已用完");+ sent.push(row.body.text!);+ });+ ob.start();+ // ack、审批提示这类短命的:留着也按自己的期限+ await ob.send({ ...input("ack", "收到"), ttlMs: 10 * 60_000 });+ await ob.send(input("final", "结果"));+ await ob.idle();+ expect(store.getOutbox("ack")!.expiresAt).toBe(1_000_000 + 10 * 60_000);+ expect(store.getOutbox("final")!.expiresAt).toBe(1_000_000 + HOLD_TTL_MS);+ expect(HOLD_TTL_MS).toBeGreaterThan(OUTBOX_TTL_MS);+ now += 3600_000;+ // 放回去时又发不出去:合成的那条再留着,下次不会叠两个前缀+ expect(ob.release("b", "weixin", "u1", combineHeld)).toBe(1);+ await ob.idle();+ expect(store.getOutbox("ack")).toMatchObject({ status: "gone", error: expect.stringMatching(/等待太久/) });+ expect(store.getOutbox("final")).toMatchObject({ status: "held", body: { text: `${AWAY_PREFIX}结果`, away: true } });+ open = true;+ ob.release("b", "weixin", "u1", combineHeld);+ await ob.idle();+ expect(sent).toEqual([`${AWAY_PREFIX}结果`]);});it("waits for the channel to register; expired messages are marked gone and the next one goes", async () => {@@ -175,14 +239,15 @@ describe("deliverWeixin", () => {expect(quota.remaining("u1")).toBe(7);});- it("too little quota: truncates with a note; none left or the 24h window passed: gone with the reason", async () => {+ it("too little quota: truncates with a note; none left or the 24h window passed: held with the reason", async () => {const a = setup(1);await deliverWeixin(a.client, a.quota, a.row("x".repeat(5000)), () => {});expect(a.sent).toHaveLength(1);expect(a.sent[0].text).toMatch(/已达到本轮可发送条数上限/);await expect(deliverWeixin(a.client, a.quota, a.row("再来一条"), () => {})).rejects.toThrow(/本轮可发送条数已用完/);+ await expect(deliverWeixin(a.client, a.quota, a.row("再来一条"), () => {})).rejects.toBeInstanceOf(Held);const b = setup(10, 25 * 3600_000);- await expect(deliverWeixin(b.client, b.quota, b.row("晚了"), () => {})).rejects.toBeInstanceOf(Gone);+ await expect(deliverWeixin(b.client, b.quota, b.row("晚了"), () => {})).rejects.toBeInstanceOf(Held);await expect(deliverWeixin(b.client, b.quota, b.row("晚了"), () => {})).rejects.toThrow(/超过 24 小时/);expect(b.sent).toEqual([]);});diff --git a/ui/components/ui.js b/ui/components/ui.jsindex 327220d..4b8f39a 100644--- a/ui/components/ui.js+++ b/ui/components/ui.js@@ -283,7 +283,7 @@ const STATE = {failed: ["失败", "err"], stopped: ["已停止", "off"], wait: ["等待扫码", "warn"], scaned: ["已扫码", "warn"], need_verifycode: ["需验证码", "warn"],confirmed: ["已确认", "ok"], already_bound: ["已绑定", "ok"], cancelled: ["已取消", "off"], idle: ["空闲", "off"], fetching: ["获取中", "warn"],pending: ["待处理", "warn"], allowed: ["已批准", "ok"], rejected: ["已拒绝", "err"], answered: ["已回答", "ok"],- retrying: ["重试中", "warn"], denied: ["已拒绝", "err"],+ denied: ["已拒绝", "err"],};export const Badge = ({ s }) => {const [text, kind] = STATE[s] || [s, ""];diff --git a/ui/lib/access.js b/ui/lib/access.jsindex defd037..23f5e19 100644--- a/ui/lib/access.js+++ b/ui/lib/access.js@@ -1,11 +1,11 @@-// 谁能使用机器人:信息面板(使用请求、没发出去的消息)和机器人设置(主人、允许名单)共用的说法。+// 谁能使用机器人:信息面板(使用请求)和机器人设置(主人、允许名单)共用的说法。export const CHANNEL_NAME = { web: "网页", feishu: "飞书", weixin: "微信" };/** 允许名单里每个人是怎么来的 */export const SOURCE_LABEL = {request: "你允许的",migration: "升级前已在使用",- "previous-owner": "之前扫码登录的微信",+ "previous-owner": "之前的主人",app: "在应用里添加",test: "测试",};diff --git a/ui/screens/bot-settings.js b/ui/screens/bot-settings.jsindex 3fcdfea..e513b07 100644--- a/ui/screens/bot-settings.js+++ b/ui/screens/bot-settings.js@@ -79,7 +79,7 @@ function BudgetRows({ bot, budget, account, onSaved, onOpenSettings }) {}/**- * 谁能使用:只有主人和允许名单里的人。主人 = 扫码登录的微信 / 在应用里设的飞书主人;+ * 谁能使用:只有主人和允许名单里的人。主人 = 扫码登录的微信 / 连上之后第一个发消息的人(可以「更换」:下一个发消息的人成为主人);* 允许名单和拒绝过的人可以移除(移除后他再发消息会重新申请)。*/function AccessRows({ botId }) {@@ -107,23 +107,23 @@ function AccessRows({ botId }) {}))) return;call(encodeURIComponent(e.id), "DELETE");};- const clearOwner = async (ch, o) => {- if (!(await confirmSheet({ title: `取消${CHANNEL_NAME[ch]}主人?`, body: `「${o.who}」之后发消息需要重新被允许;下一个发消息的人可以在信息面板里设为主人。`, confirmLabel: "取消主人", danger: true }))) return;- call(encodeURIComponent(o.entryId), "DELETE");+ const resetOwner = async (ch, o) => {+ const name = CHANNEL_NAME[ch];+ if (!(await confirmSheet({ title: `更换${name}主人?`, body: `「${o.name}」不再是主人,之后发消息需要重新被允许。下一个给机器人发消息的人会成为${name}主人:用你自己的${name}发一句话就行。`, confirmLabel: "更换", danger: true }))) return;+ call(`owner/${ch}`, "DELETE");};if (!d) return html`<div class="list-head">谁能使用</div><div class="list"><div class="row"><${Skeleton} w="45%" /></div></div>`;const allowed = d.entries.filter((e) => e.status === "allowed");const denied = d.entries.filter((e) => e.status === "denied");const owner = (ch) => {const o = d.owners[ch];- const sub = o- ? `${o.who} · ${o.via === "login" ? "扫码登录的微信" : "在应用里设的"}`- : ch === "weixin"- ? "扫码登录后,扫码的那个微信就是主人"- : "还没有:第一个给机器人发消息的人会出现在信息面板,点「设为主人」";- return html`<${Row} id=${`access-${ch}`} name=${`${CHANNEL_NAME[ch]}主人`} sub=${sub}>- ${o && o.via === "app" && html`<button type="button" class="text" onClick=${() => clearOwner(ch, o)}>取消</button>`}- <//>`;+ if (o) {+ return html`<${Row} id=${`access-${ch}`} name=${`${CHANNEL_NAME[ch]}主人:${o.name}(${o.via === "login" ? "扫码登录的微信" : "第一个发消息的人"})`}>+ ${o.via !== "login" && html`<button type="button" class="text" onClick=${() => resetOwner(ch, o)}>更换</button>`}+ <//>`;+ }+ const sub = ch === "weixin" ? "扫码登录后,扫码的那个微信就是主人" : `还没有:用你自己的${CHANNEL_NAME[ch]}给机器人发一句话,就完成绑定`;+ return html`<${Row} id=${`access-${ch}`} name=${`${CHANNEL_NAME[ch]}主人`} sub=${sub} />`;};return html`<div class="list-head">谁能使用</div><div class="list">diff --git a/ui/screens/info-panel.js b/ui/screens/info-panel.jsindex 268f662..303d02a 100644--- a/ui/screens/info-panel.js+++ b/ui/screens/info-panel.js@@ -21,7 +21,7 @@ export function usePoll(fn, ms, deps = []) {return [data, err, load];}-function FeishuRow({ bot, st, reload }) {+function FeishuRow({ bot, st, owner, reload }) {const [open, setOpen] = useState(false);const [appId, setAppId] = useState(bot.feishuAppId);const [secret, setSecret] = useState("");@@ -40,7 +40,7 @@ function FeishuRow({ bot, st, reload }) {setBusy(false);};const clear = async () => {- if (!(await confirmSheet({ title: "断开飞书?", body: "会清除这个机器人的飞书 App ID 与 App Secret。", confirmLabel: "断开", danger: true }))) return;+ if (!(await confirmSheet({ title: "断开飞书?", body: "会清除这个机器人的飞书 App ID 与 App Secret;重新连接后,第一个发消息的人成为飞书主人。", confirmLabel: "断开", danger: true }))) return;try {await api(`/bots/${bot.id}/feishu`, { method: "DELETE" });setAppId("");@@ -62,11 +62,13 @@ function FeishuRow({ bot, st, reload }) {<button type="button" class="btn primary" disabled=${!appId.trim() || busy} onClick=${save}>${busy ? html`<${Spinner} />` : "保存并连接"}</button>${bot.feishuAppId && html`<button type="button" class="text danger" onClick=${clear}>断开</button>`}</div>+ ${owner === null && html`<p class="hint">${bot.feishuAppId ? "" : "连接后,"}用你自己的飞书给机器人发一句话,就完成绑定。</p>`}+ ${owner && html`<p class="hint">飞书主人:${owner.name}(第一个发消息的人)</p>`}<p class="hint">在飞书开放平台启用「机器人」,事件订阅选「使用长连接接收事件」并订阅 <code>im.message.receive_v1</code>;权限:<code>im:message.p2p_msg:readonly</code>、<code>im:message:send_as_bot</code>、<code>cardkit:card:write</code>。</p></div>`}`;}-function WeixinRow({ bot, st, reload }) {+function WeixinRow({ bot, st, owner, reload }) {const [open, setOpen] = useState(false);const [code, setCode] = useState("");const login = st.login;@@ -93,6 +95,7 @@ function WeixinRow({ bot, st, reload }) {${login && login.state === "need_verifycode" && html`<div class="actions"><input class="field" style="width:140px" placeholder="验证码" value=${code} onInput=${(e) => setCode(e.target.value)} /><button type="button" class="btn" onClick=${() => call("/verify", { code }).then(() => setCode(""))}>提交</button></div>`}${st.account && st.account.pausedUntil > Date.now() && html`<p class="hint">暂停至 ${fmtTime(st.account.pausedUntil)}</p>`}+ ${st.account && owner === null && html`<p class="hint">用你自己的微信给机器人发一句话,就完成绑定。</p>`}<div class="actions">${active ? html`<button type="button" class="btn" onClick=${() => call("/cancel")}>取消</button>` : html`<button type="button" class="btn primary" onClick=${() => call("/login")}>${st.account ? "重新扫码登录" : "扫码登录"}</button>`}<button type="button" class="text" onClick=${() => call("", { enabled: !bot.weixinEnabled })}>${bot.weixinEnabled ? "停用微信渠道" : "启用微信渠道"}</button>@@ -102,10 +105,7 @@ function WeixinRow({ bot, st, reload }) {</div>`}`;}-/**- * 使用请求:不在允许名单里的人给机器人发了消息(他只收到一句"还没被允许",没有调用模型)。- * 允许 / 拒绝;这个渠道还没有主人时,可以把他设为主人(多半就是你自己)。- */+/** 使用请求:不在允许名单里的人给机器人发了消息(他只收到一句"还没被允许",没有调用模型)。允许 / 拒绝。 */function AccessRequests({ botId, data, reload }) {const [busy, setBusy] = useState("");if (!data || !data.requests.length) return null;@@ -113,7 +113,7 @@ function AccessRequests({ botId, data, reload }) {setBusy(r.id + what);try {await api(`/bots/${botId}/access/${encodeURIComponent(r.id)}/${what}`, { method: "POST", body: {} });- toast(what === "approve" ? `已允许「${r.who}」` : what === "deny" ? `已拒绝「${r.who}」` : `已设为${CHANNEL_NAME[r.channel]}主人`);+ toast(what === "approve" ? `已允许「${r.who}」` : `已拒绝「${r.who}」`);} catch (e) {failed(e);}@@ -121,9 +121,7 @@ function AccessRequests({ botId, data, reload }) {reload();};return html`<div class="list-head">使用请求<span class="badge count warn">${data.requests.length}</span></div>- <div class="stack">${data.requests.map((r) => {- const noOwner = !data.owners[r.channel];- return html`<div key=${r.id} class="stack approval" style="--gap: var(--space-1)">+ <div class="stack">${data.requests.map((r) => html`<div key=${r.id} class="stack approval" style="--gap: var(--space-1)"><span class="hint">${CHANNEL_NAME[r.channel] || r.channel} · ${fmtAgo(r.createdAt)}${r.requests > 1 ? ` · 发了 ${r.requests} 条消息` : ""}</span><div class="card"><div class="meta"><span>想使用这个机器人 · 配对码 <span class="num">${r.code}</span></span></div>@@ -132,47 +130,10 @@ function AccessRequests({ botId, data, reload }) {<div class="actions"><${Button} variant="primary" loading=${busy === r.id + "approve"} disabled=${!!busy} onClick=${() => act(r, "approve")}>允许</${Button}><${Button} loading=${busy === r.id + "deny"} disabled=${!!busy} onClick=${() => act(r, "deny")}>拒绝</${Button}>- ${noOwner && html`<${Button} variant="ghost" loading=${busy === r.id + "owner"} disabled=${!!busy} onClick=${() => act(r, "owner")}>设为主人</${Button}>`}</div>- <span class="hint">${noOwner- ? `${CHANNEL_NAME[r.channel]}还没有主人。如果这是你自己,点「设为主人」,以后的请求也会发给你。`- : `他只收到一句提示,没有调用模型。主人在聊天里回复「同意 ${r.code}」也可以。`}</span>+ <span class="hint">他只收到一句提示,没有调用模型。主人在聊天里回复「同意 ${r.code}」也可以。</span></div>- </div>`;- })}</div>`;-}--/** 没发出去的消息:出站队列还在重试的,和发不出去、已经放弃的(附原因,可以"知道了") */-function Undelivered({ botId }) {- const [d, , reload] = usePoll(() => api(`/bots/${botId}/outbox`), 8000, [botId]);- if (!d || (!d.failed.length && !d.waiting.length)) return null;- const dismiss = async (f) => {- try {- await api(`/bots/${botId}/outbox/${encodeURIComponent(f.id)}/dismiss`, { method: "POST", body: {} });- reload();- } catch (e) {- failed(e);- }- };- return html`<div class="list-head">没发出去的消息${d.failed.length > 0 && html`<span class="badge count warn">${d.failed.length}</span>`}</div>- <div class="list">- ${d.waiting.map((w) => html`<div key=${w.id} class="row compact">- <div class="who">- <div class="name">发给${w.to}</div>- <div class="sub">${w.preview || "(空)"}</div>- <div class="sub wrap">${w.attempts ? `第 ${w.attempts} 次没发出去,稍后自动重试` : "等渠道连上后发送"}${w.error ? `:${w.error}` : ""}</div>- </div>- <${Badge} s="retrying" />- </div>`)}- ${d.failed.map((f) => html`<div key=${f.id} class="row compact">- <div class="who">- <div class="name">发给${f.to} · ${fmtAgo(f.updatedAt)}</div>- <div class="sub">${f.preview || "(空)"}</div>- <div class="sub wrap">${f.error}</div>- </div>- <button type="button" class="text" onClick=${() => dismiss(f)}>知道了</button>- </div>`)}- </div>`;+ </div>`)}</div>`;}function MemorySection({ botId }) {@@ -268,7 +229,7 @@ export function InfoPanel({ bot, onClose, onOpenBotSettings, onOpenChat }) {<div class="list-head">渠道</div><div class="list">${detail && detail.bot- ? html`<${FeishuRow} bot=${detail.bot} st=${detail.channels.feishu} reload=${reloadDetail} /><${WeixinRow} bot=${detail.bot} st=${detail.channels.weixin} reload=${reloadDetail} />`+ ? html`<${FeishuRow} bot=${detail.bot} st=${detail.channels.feishu} owner=${access ? access.owners.feishu : undefined} reload=${reloadDetail} /><${WeixinRow} bot=${detail.bot} st=${detail.channels.weixin} owner=${access ? access.owners.weixin : undefined} reload=${reloadDetail} />`: html`<div class="row"><${Skeleton} w="50%" /></div><div class="row"><${Skeleton} w="40%" /></div>`}</div>@@ -283,8 +244,6 @@ export function InfoPanel({ bot, onClose, onOpenBotSettings, onOpenChat }) {<button type="button" class="text" style="justify-self:start" onClick=${reloadAppr}>刷新</button></div>`: html`<div class="list"><div class="row"><span class="hint">没有待处理的审批</span></div></div>`}- <${Undelivered} botId=${bot.id} />-<${MemorySection} botId=${bot.id} /><div class="list-head">最近会话</div>