Skip to content

🤖 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.

feat: 聊天渠道改成全局账号,所有机器人共用,/bot 切换机器人

dyk98864e9d6e01c9
diff --git a/README.md b/README.md
index f7219da..807761d 100644
--- a/README.md
+++ b/README.md
@@ -242,8 +242,9 @@ npm start # 本地管理界面:http://127.0.0.1:3600/
- **记忆会延续。** 机器人用 Markdown 保存三层记忆(团队、机器人、群),会过滤看起来像密钥的内容。
- **长对话也能用下去。** 上下文快满之前,上下文管家会压缩,或开一个新段并带上交接摘要。
+- **账号全局共用。** 微信、飞书、Telegram、Slack、Discord、Notion 的账号在设置里加一次,所有机器人共用,每个服务可以加多个、起别名。在聊天软件里发一次 `/bot 名字` 就换一个机器人聊,也可以让机器人读你的 Notion 和飞书消息。
- **微信和飞书。** 微信扫码连接,飞书机器人支持流式回复卡片;微信还能收发图片和文件。
-- **Telegram、Slack、Discord。** 在信息面板填 token 连接,不需要公网地址;回复边写边显示,能收发图片和文件。目前只处理单聊,审批和提问回复文字。
+- **Telegram、Slack、Discord。** 在 设置 › 连接 里填 token 连接,不需要公网地址;回复边写边显示,能收发图片和文件。目前只处理单聊,审批和提问回复文字。
- **四种运行方式。** 桌面版、命令行、Docker,以及 `127.0.0.1:3600` 的本地网页控制台。
<p align="center">
diff --git a/README_en.md b/README_en.md
index ace82ad..b5bdde1 100644
--- a/README_en.md
+++ b/README_en.md
@@ -242,8 +242,9 @@ The full story, in Chinese: [AnyModelBot 超级智能体](./docs/blog/superagent
- **Memory that carries over.** Bots keep Markdown memory at three levels (team, bot and group) and filter out anything that looks like a secret.
- **Long chats stay usable.** A context steward compacts or starts a fresh segment with a hand-off summary before the window fills up.
+- **Accounts shared by all bots.** Add WeChat, Feishu, Telegram, Slack, Discord and Notion accounts once in Settings. Every bot shares them, and each service can have several accounts with aliases. Send `/bot name` once in a chat app to talk to a different bot, or let a bot read your Notion and Feishu messages.
- **WeChat and Feishu.** Scan a QR code to connect WeChat, or connect a Feishu bot with streaming reply cards. WeChat also carries images and files.
-- **Telegram, Slack and Discord.** Paste a token in the info panel. No public address needed. Replies appear as they're written, and images and files work both ways. Direct messages only for now, and approvals and questions are answered by text.
+- **Telegram, Slack and Discord.** Paste a token in Settings › Connections. No public address needed. Replies appear as they're written, and images and files work both ways. Direct messages only for now, and approvals and questions are answered by text.
- **Four ways to run it.** Desktop app, command line, Docker, or the local web console at `127.0.0.1:3600`.
<p align="center">
diff --git a/docs/development.md b/docs/development.md
index 1775545..6ffec6b 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -4,7 +4,7 @@
这份文档给想从源码运行、打包或参与开发的人看。普通用户直接从 [Releases](https://github.com/modelflare-ai/AnyModelBot/releases) 下载安装包即可,见 [README](../README.md#-下载)。
-- 一个机器人 = 人设 + 默认模型 + 渠道(飞书 / 微信)。定位:自用、单用户;每个机器人对应一个飞书应用。
+- 一个机器人 = 人设 + 默认模型 + 记忆。账号是全局的(设置 › 连接),所有机器人共用,同一个服务可以加多个。定位:自用、单用户。
- 模型来自 [Modelflare](https://modelflare.dev/?utm_source=anymodelbot&utm_campaign=amb_readme):首次启动登录(或注册)Modelflare 账户,模型自动列出;也可以直接粘贴一个 API Key。请求经过内置的 [magpie](https://github.com/yetone/magpie) 网关转发。
- 三种运行方式,同一套代码:**桌面版(Electron)**、**命令行 `npm start`**、**Docker**。
@@ -84,7 +84,7 @@ docker run -d --name amb -p 3600:3600 -v amb-data:/data anymodel-bot
docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令牌>
```
-容器内界面监听 0.0.0.0,因此强制令牌访问。不要把 3600 端口直接暴露到公网。微信扫码在对话页的信息面板(点顶部机器人名称)→「渠道」里完成。
+容器内界面监听 0.0.0.0,因此强制令牌访问。不要把 3600 端口直接暴露到公网。微信扫码在 设置 › 连接 里完成。
## 模型(Modelflare)
@@ -97,7 +97,8 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令
- 生图 / 生视频:代理模式下机器人有 `media_models`(可用模型、默认模型、参数范围、参考价)、`media_docs`(从 docs.modelflare.dev 实时读该模型的请求格式)、`generate_image`、`generate_video` 四个工具,并自带一份 media 技能说明。各模型的参数格式不同,机器人按文档写请求体,工作区里的参考图写成 `workspace:路径` 即可;Key 始终只在本程序里,由本程序带着该机器人用的 Key 调 Modelflare,结果存进机器人工作区的 `media/`,再交付到聊天。
- 生成前确认:直接生成,不打扰你。机器人选了不是默认的模型、要求没说清,都不问:它按最合理的理解生成,再说一句用了什么。只在预计花费超过 $0.5 时(按参考价、张数、视频时长和分辨率估算;视频估不出来也算)先在聊天里问你这次用哪个模型(附提示词、参数、参考价和为什么问)。可以确认、换成别的模型或取消;微信回复编号或模型名,飞书 / 网页点选。10 分钟内没回答就不生成。想每次都确认:机器人设置 → 生图 / 生视频 → 生成前确认 →「每次都问」。
- 联网搜索:代理的 `web_search` 不用 DeepSeek 自带的搜索(它要 DeepSeek 的 Key),经 `amb-web-search` 插件交给本程序搜。默认免费、不用设置:依次试 Exa 的公开 MCP、必应、DuckDuckGo,上次成功的先试,出错的(限流、验证页、必应给出不相干的结果)跳过 10 分钟。设置 → 网络与访问 → 联网搜索 可以换成 Tavily、Exa、博查、智谱(填 Key)或自己的 SearXNG,填了就先用它,出错时退回免费的。Key 和渠道令牌一样存在本机数据库里,代理进程拿不到。桌面版搜索走系统代理;命令行版用 Node 的 fetch(设 `NODE_USE_ENV_PROXY=1` 后认 `HTTPS_PROXY`)。
-- 已授权账号(`src/agent/accounts.ts`):全局一份(设置 › 连接),所有机器人共用,同一个服务可以加多个账号,比如对任何机器人说「看我第一个飞书和第二个飞书的消息」。`amb-connections` 插件把每次工具调用经 bridge 交给本程序,令牌不进代理进程;账号用工具的 `account` 参数选(序号或名字),`connected_accounts` 列出来。有账号的服务才有工具。只读机器人和观察规则不能写,宿主也会再查一次。聊天渠道不在这里,还是每个机器人一个。
+- 聊天渠道账号(`src/core/routes.ts`):微信、飞书、Telegram、Slack、Discord 的账号也是全局的,在设置 › 连接里添加,可以起别名。消息交给哪个机器人:这个人用 `/bot` 选过的 → 账号的默认机器人 → 第一个机器人。`/bot` 列出机器人,发一次 `/bot 名字` 就切换并记住,之后这个会话一直和它聊。每个机器人的系统提示词里都有其他机器人的名单和切换方法,用户问起时答得上来。名单和主人跟着账号走,能用这个账号的人可以和任何机器人聊。账号的 key 是命名空间:升级前的渠道 key 就是原来的机器人 id,登录态、配额、名单、队列都不用搬,默认机器人也是原来那个。删除机器人不影响账号。
+- 已授权账号(`src/agent/accounts.ts`):全局一份(设置 › 连接),所有机器人共用,同一个服务可以加多个账号,比如对任何机器人说「看我第一个飞书和第二个飞书的消息」。`amb-connections` 插件把每次工具调用经 bridge 交给本程序,令牌不进代理进程;账号用工具的 `account` 参数选(序号或名字),`connected_accounts` 列出来。有账号的服务才有工具。只读机器人和观察规则不能写,宿主也会再查一次。聊天渠道账号见下一条。
- **Notion**(`notion.ts`):用户添加时选一键授权或令牌。令牌走 REST API;一键授权用 OAuth + PKCE + 动态注册,回调到本机 `/oauth/notion/callback`,再由本程序调官方远程 MCP(`mcp.notion.com`)的工具。模型看到的是同一套工具:`notion_search`、`notion_read_page`、`notion_query_database`,不是只读的机器人再加 `notion_create_page`、`notion_update_page`。没有删除页面的工具。
- **飞书**(`feishu-account.ts`):和官方 lark-cli 同一套流程:扫码创建个人应用(也可以填已有的自建应用),再设备授权拿用户令牌。只读,工具是 `feishu_list_chats`、`feishu_read_chat`、`feishu_search_messages`。
- 默认图片 / 视频模型:首次设置时和默认文本模型一起选,之后在 设置 → Modelflare 修改;选「自动」时用推荐顺序里第一个不需要参考素材的模型。
diff --git a/docs/development_en.md b/docs/development_en.md
index 52cfa42..79ff014 100644
--- a/docs/development_en.md
+++ b/docs/development_en.md
@@ -4,7 +4,7 @@
This guide is for people who want to run AnyModelBot from source, package it, or contribute. If you only want to use the app, download an installer from [Releases](https://github.com/modelflare-ai/AnyModelBot/releases); see the [README](../README_en.md#-download).
-- A bot = persona + default model + channels (Feishu / WeChat). Scope: personal, single user; each bot maps to one Feishu app.
+- A bot is a persona, a default model and its memory. Accounts are global (Settings › Connections) and shared by all bots, with as many per service as you like. Built for personal use by one person.
- Models come from [Modelflare](https://modelflare.dev/?utm_source=anymodelbot&utm_campaign=amb_readme): on first launch you sign in to (or sign up for) a Modelflare account and the models are listed automatically; you can also paste an API key. Requests go through the bundled [magpie](https://github.com/yetone/magpie) gateway.
- Three ways to run, one codebase: **desktop app (Electron)**, **command line `npm start`**, **Docker**.
@@ -84,7 +84,7 @@ docker run -d --name amb -p 3600:3600 -v amb-data:/data anymodel-bot
docker exec amb cat /data/ui-token # open http://<host>:3600/?token=<token>
```
-Inside the container the console listens on 0.0.0.0, so token access is enforced. Do not expose port 3600 directly to the internet. WeChat QR sign-in is in the chat screen's info panel (click the bot name at the top) → Channels.
+Inside the container the console listens on 0.0.0.0, so token access is enforced. Do not expose port 3600 directly to the internet. WeChat QR sign-in is in Settings › Connections.
## Models (Modelflare)
@@ -97,7 +97,8 @@ Inside the container the console listens on 0.0.0.0, so token access is enforced
- Image / video generation: in agent mode, bots get four tools — `media_models` (available models, defaults, parameter ranges, reference prices), `media_docs` (reads the model's request format live from docs.modelflare.dev), `generate_image` and `generate_video` — plus a bundled media skill. Parameter formats differ per model, so the bot writes the request body from the docs; reference images in the workspace are written as `workspace:path`. The key never leaves the app: the app calls Modelflare with the bot's key, saves results in the bot workspace's `media/`, and delivers them to the chat.
- Confirmation before generation: the image or video is generated right away. A model other than the default, or a loose request, is not a reason to ask: the bot takes the most reasonable reading, generates, and says in one line what it used. The chat asks which model to use (with prompt, parameters, reference price and the reason for asking) only when the estimated cost is above $0.5 (from the reference price, number of images, video length and resolution; a video whose cost cannot be estimated counts too). You can confirm, switch models or cancel — reply with a number or model name on WeChat, or click on Feishu / the web console. With no answer within 10 minutes, nothing is generated. To confirm every time: bot settings → Images / videos → Confirm before generating → "Every time".
- Web search: the agent's `web_search` does not use DeepSeek's built-in search (it needs a DeepSeek key); the `amb-web-search` plugin hands each search to the app. By default it is free and needs no setup: it tries Exa's public MCP, Bing and DuckDuckGo in turn, the last one that worked first, and skips one that fails (rate limit, bot check, Bing returning unrelated results) for 10 minutes. Settings → Network & access → Web search can switch to Tavily, Exa, Bocha or Zhipu (with a key) or your own SearXNG; when set, it is tried first and the free search takes over if it fails. Keys are stored in the local database like channel tokens and never reach the agent process. The desktop app searches through the system proxy; the command-line build uses Node's fetch (it honours `HTTPS_PROXY` with `NODE_USE_ENV_PROXY=1`).
-- Connected accounts (`src/agent/accounts.ts`): one global list (Settings › Connections) shared by all bots, with as many accounts per service as you like, so you can tell any bot "check my first Feishu and my second Feishu". The `amb-connections` plugin hands each tool call to the app over the bridge, so tokens never reach the agent process. A tool's `account` parameter picks the account by number or name, and `connected_accounts` lists them. A service's tools only exist once it has an account. Read-only bots and observing rules can't write, and the host checks this again. Chat channels aren't part of this: each bot still has its own.
+- Chat channel accounts (`src/core/routes.ts`): WeChat, Feishu, Telegram, Slack and Discord accounts are global too. You add them in Settings › Connections and can give them aliases. A message goes to the bot this person picked with `/bot`, then the account's default bot, then the first bot. `/bot` lists the bots; sending `/bot name` once switches and remembers, so the chat stays with that bot. Every bot's system prompt lists the other bots and how to switch, so it can answer when asked. Owners and allow lists belong to the account, so anyone allowed on an account can talk to any bot. An account's key is a namespace: channels from before this change keep the old bot id as their key, so sign-ins, quotas, allow lists and queues don't move, and the default bot stays the same. Deleting a bot doesn't affect accounts.
+- Connected accounts (`src/agent/accounts.ts`): one global list (Settings › Connections) shared by all bots, with as many accounts per service as you like, so you can tell any bot "check my first Feishu and my second Feishu". The `amb-connections` plugin hands each tool call to the app over the bridge, so tokens never reach the agent process. A tool's `account` parameter picks the account by number or name, and `connected_accounts` lists them. A service's tools only exist once it has an account. Read-only bots and observing rules can't write, and the host checks this again. Chat channel accounts are covered in the next item.
- **Notion** (`notion.ts`): when adding an account the user picks one-click authorization or a token. Tokens use the REST API. One-click uses OAuth with PKCE and dynamic registration, calls back to the local `/oauth/notion/callback`, and the app then calls the tools of Notion's remote MCP (`mcp.notion.com`). The model sees the same tools either way: `notion_search`, `notion_read_page` and `notion_query_database`, plus `notion_create_page` and `notion_update_page` for bots that aren't read-only. No tool deletes a page.
- **Feishu** (`feishu-account.ts`): the same flow as the official lark-cli: scan to create a personal app (or enter your own app), then device authorization for a user token. Read-only, with `feishu_list_chats`, `feishu_read_chat` and `feishu_search_messages`.
- Default image / video models: chosen together with the default text model during first-run setup, changeable later in Settings → Modelflare. "Auto" uses the first model in the recommended order that needs no reference material.
diff --git a/src/agent/accounts.ts b/src/agent/accounts.ts
index ed86821..c4c4a12 100644
--- a/src/agent/accounts.ts
+++ b/src/agent/accounts.ts
@@ -6,7 +6,7 @@
* 令牌只留在宿主进程,代理进程经 bridge 调用(amb-connections 插件)。
*
* 这里抛出的 ConnectionError 的文字会直接给模型看:说清楚怎么办,不带令牌。
- * 飞书、微信等聊天渠道是另一回事:渠道是机器人自己的账号身份,还是每个机器人配一个。
+ * 这里是机器人能读写的数据账号。从哪里和机器人聊(微信、飞书等聊天渠道)也是全局账号,见 core/routes.ts。
*/
import crypto from "node:crypto";
import { registerSecret } from "../log.js";
diff --git a/src/agent/feishu-account.ts b/src/agent/feishu-account.ts
index 8bdb694..c7af904 100644
--- a/src/agent/feishu-account.ts
+++ b/src/agent/feishu-account.ts
@@ -1,6 +1,6 @@
/**
* 飞书账号(accounts.ts):用用户身份读这个人能看到的会话和消息,只读。和飞书聊天渠道(channels/feishu)是两回事:
- * 渠道是机器人自己的应用,只能看到发给机器人的消息。
+ * 渠道账号用的是一个机器人应用,只能看到发给这个应用的消息。
*
* 添加账号(和官方 lark-cli 同一套流程):
* 1. 一键授权:用飞书扫码,飞书替用户创建一个个人应用,回 App ID 和 Secret。也可以填已有的自建应用,跳过这一步。
diff --git a/src/agent/host.ts b/src/agent/host.ts
index aa4dbad..50fc323 100644
--- a/src/agent/host.ts
+++ b/src/agent/host.ts
@@ -1037,7 +1037,8 @@ exec "$REAL" "$@"
*/
syncPrompt(force = false): void {
const bot = this.o.store.getBot(this.o.botId);
- const text = botPrompt({ name: bot?.name ?? "", persona: bot?.systemPrompt ?? "", memory: this.settings().memory.enabled });
+ const others = this.o.store.listBots().filter((b) => b.id !== this.o.botId).map((b) => ({ name: b.name, persona: b.systemPrompt }));
+ const text = botPrompt({ name: bot?.name ?? "", persona: bot?.systemPrompt ?? "", memory: this.settings().memory.enabled, others });
if (!force && text === this.promptText) return;
try {
fs.mkdirSync(path.dirname(this.promptFile), { recursive: true, mode: 0o700 });
diff --git a/src/agent/prompts/system.ts b/src/agent/prompts/system.ts
index bb88a3e..5b20993 100644
--- a/src/agent/prompts/system.ts
+++ b/src/agent/prompts/system.ts
@@ -57,6 +57,23 @@ export interface BotPromptInput {
persona: string;
/** 本机器人开着长期记忆 */
memory: boolean;
+ /** 用户的其他机器人:用户问起时它要答得上来,也能指路 */
+ others?: Array<{ name: string; persona: string }>;
+}
+
+/** 其他机器人的名单和怎么切换。只有一个机器人时不写,免得系统提示词多一段没用的话 */
+export function botTeam(others: Array<{ name: string; persona: string }>): string {
+ if (!others.length) return "";
+ const lines = others.map((o) => {
+ const blurb = o.persona.trim().split("\n")[0].slice(0, 60);
+ return `- ${o.name.trim()}${blurb ? `:${blurb}` : ""}`;
+ });
+ return [
+ "# 其他机器人",
+ "用户还有这些机器人,各有各的人设和记忆,和你共用用户授权的账号:",
+ ...lines,
+ "用户问有哪些机器人、某件事该找谁、怎么换时,照这里回答。在微信、飞书这些聊天软件里,发一次 /bot 名字 就换过去了,之后这个会话一直和它聊,不用每句都带;只发 /bot 能看到列表。在 AnyModelBot 的窗口里,在左侧选机器人。你不能替用户切换。",
+ ].join("\n");
}
/** 机器人名字与用户写的人设:放在最后,和前面的聊天规则冲突时以人设为准 */
@@ -70,8 +87,8 @@ export function botIdentity(name: string, persona: string): string {
/**
* 机器人段的全文(宿主写进文件,amb-prompt 插件每次模型请求现读)。只放每个机器人固定的内容,
* 同一机器人的所有会话共用一份系统提示词;按会话变化的(渠道、记忆快照、交接便条)放在每段的第一条消息里。
- * 顺序按变化频率从低到高:聊天规则(随应用升级)→ 记忆说明(随开关)→ 名字与人设(用户随时改)。
+ * 顺序按变化频率从低到高:聊天规则(随应用升级)→ 记忆说明(随开关)→ 其他机器人(增删或改名时)→ 名字与人设(用户随时改)。
*/
export function botPrompt(o: BotPromptInput): string {
- return [CHAT_RULES, o.memory ? MEMORY_GUIDE : "", botIdentity(o.name, o.persona)].filter(Boolean).join("\n\n");
+ return [CHAT_RULES, o.memory ? MEMORY_GUIDE : "", botTeam(o.others ?? []), botIdentity(o.name, o.persona)].filter(Boolean).join("\n\n");
}
diff --git a/src/app.ts b/src/app.ts
index d9535cb..71968bd 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -2,7 +2,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { saveConfigFile, type AppConfig } from "./config.js";
-import { Store, type Bot } from "./store/db.js";
+import { Store, type Bot, type ChannelAccount } from "./store/db.js";
import { OpenAICompatClient, type ModelClient } from "./llm/client.js";
import { BotRuntime } from "./core/runtime.js";
import { KeyedQueue } from "./core/queue.js";
@@ -11,6 +11,7 @@ import { Outbox } from "./core/outbox.js";
import { Delivery, type DeliveryOptions } from "./core/delivery.js";
import { AccessControl } from "./core/access.js";
import { MESSENGERS, MESSENGER_LABEL, isMessenger, type ChannelStatus, type MessengerId } from "./core/types.js";
+import { botForPeer, defaultBotFor } from "./core/routes.js";
import { MagpieSupervisor } from "./magpie/supervisor.js";
import { FeishuChannel } from "./channels/feishu/channel.js";
import { LarkTransport, type FeishuTransport } from "./channels/feishu/transport.js";
@@ -104,7 +105,7 @@ export function appVersion(): string {
export interface AppOptions {
/** 测试注入:替换飞书传输层 */
- feishuTransport?: (bot: Bot) => FeishuTransport;
+ feishuTransport?: (account: { id: string; feishuAppId: string; feishuAppSecret: string }) => FeishuTransport;
/** 测试用:替换 Telegram、Slack、Discord 的传输层 */
messengerTransport?: (id: MessengerId, botId: string, credentials: Record<string, string>) => MessengerTransport;
/** 测试注入:替换 iLink 的 fetch */
@@ -321,11 +322,11 @@ export class App {
/** 渠道登录过期了(微信 -14):"需要你"里一行,去重新扫码 */
private loginAttention(): AttentionItem[] {
const out: AttentionItem[] = [];
- for (const [botId, ch] of this.channels) {
+ for (const [key, ch] of this.channels) {
const st = ch.weixin?.status;
if (st?.state !== "expired") continue;
const subject = tr("app.weixinExpiredSubject");
- out.push({ id: `login:${botId}:weixin`, kind: "login", botId, botName: this.store.getBot(botId)?.name ?? botId, subject, status: "", head: subject, line: "", since: st.since, severity: "err", actions: ["relogin"], channel: "weixin" });
+ out.push({ id: `login:${key}:weixin`, kind: "login", botId: defaultBotFor(this.store, key, "weixin"), botName: this.store.getChannelAccount(key, "weixin")?.label ?? key, subject, status: "", head: subject, line: "", since: st.since, severity: "err", actions: ["relogin"], channel: "weixin" });
}
return out;
}
@@ -478,20 +479,19 @@ export class App {
/** 提醒经机器人发给你:用第一个能发出去的渠道(微信发给扫码的人,飞书发到最近的单聊) */
async pushToOwner(text: string): Promise<boolean> {
- for (const bot of this.store.listBots()) {
- const ch = this.channels.get(bot.id);
+ for (const [key, ch] of this.channels) {
try {
if (ch?.weixin && (await ch.weixin.notifyOwner(text))) return true;
// 飞书:发给主人;还没设主人时发到最近的单聊
- const chat = ch?.feishu ? (this.access.owner(bot.id, "feishu")?.peerId ?? this.store.listConversations(bot.id).find((c) => c.channel === "feishu" && c.kind === "dm")?.peerId) : undefined;
+ const chat = ch?.feishu ? (this.access.owner(key, "feishu")?.peerId ?? this.store.listAccountConversations(key, "feishu").find((c) => c.kind === "dm")?.peerId) : undefined;
if (chat && ch?.feishu?.notify(chat, text)) return true;
// 其他平台:发给主人(连上之后第一个发消息的人)
for (const id of MESSENGERS) {
- const owner = this.access.owner(bot.id, id)?.peerId;
+ const owner = this.access.owner(key, id)?.peerId;
if (owner && ch?.messengers?.[id]?.notify(owner, text)) return true;
}
} catch (e) {
- log.warn("push to owner failed", { bot: bot.id, message: (e as Error).message.slice(0, 200) });
+ log.warn("push to owner failed", { account: key, message: (e as Error).message.slice(0, 200) });
}
}
return false;
@@ -547,7 +547,7 @@ export class App {
async deleteBot(botId: string): Promise<void> {
const bot = this.store.getBot(botId);
this.tasks.dropBot(botId);
- await this.stopBot(botId);
+ // 渠道账号是全局的,不跟着机器人停:之后它们的消息交给别的机器人(core/routes.ts)
await this.agent.stopBot(botId);
if (bot?.settings.budget.enabled && this.account.signedIn) {
await this.account.setBotBudget(botId, bot.name, { ...bot.settings.budget, enabled: false }).catch((e) => log.warn("remove bot key failed", { message: (e as Error).message }));
@@ -608,7 +608,8 @@ export class App {
// 出站队列先开:渠道上线时登记发送函数,上次没发完的消息接着发
this.outbox.start();
this.delivery.start();
- for (const bot of this.store.listBots()) await this.startBot(bot.id);
+ for (const bot of this.store.listBots()) this.adoptBotChannels(bot.id);
+ for (const key of new Set(this.store.listChannelAccounts().map((a) => a.key))) await this.startBot(key);
if (interrupted.length) void this.tellInterrupted(interrupted);
// 后台任务:上次没跑完的记为中断、带着恢复说明接着做(渠道已经上线,结果能发出去);估算花费用的价格目录先读起来
if (this.agent.available) {
@@ -654,7 +655,7 @@ export class App {
const conv = this.store.getConversation(it.conversationId);
if (!conv) continue;
const text = interruptedText(it.preview);
- const ch = this.channels.get(conv.botId);
+ const ch = this.channels.get(conv.account || conv.botId);
let sent = false;
try {
if (conv.channel === "web") {
@@ -808,73 +809,124 @@ export class App {
log.info(`created default bot ${bot.id}`, { feishuAppId: bot.feishuAppId || "(未配置)" });
}
- async startBot(botId: string): Promise<void> {
+ /**
+ * 旧版把渠道存在机器人身上:第一次见到就变成全局账号。key 沿用机器人 id,登录态、配额、名单、队列的数据都不用搬,
+ * 默认回复的还是原来的机器人(core/routes.ts)。飞书凭据搬进账号后清掉机器人上的,移除账号后不会又变回来。
+ */
+ private adoptBotChannels(botId: string): void {
const bot = this.store.getBot(botId);
if (!bot) return;
- registerSecret(bot.feishuAppSecret);
- registerSecret(this.store.getWeixinAccount(botId)?.botToken);
- const ch: BotChannels = this.channels.get(botId) ?? {};
- this.channels.set(botId, ch);
- if (bot.feishuAppId && bot.feishuAppSecret && !ch.feishu) {
- const transport = this.opts.feishuTransport?.(bot) ?? new LarkTransport(bot.feishuAppId, bot.feishuAppSecret);
- ch.feishu = new FeishuChannel(bot.id, transport, this.runtime, this.queue, this.config.feishu.throttleMs, this.outbox, this.store);
+ if (bot.feishuAppId) {
+ const cur = this.store.getChannelAccount(botId, "feishu");
+ this.store.saveChannelAccount({
+ key: botId,
+ channel: "feishu",
+ label: cur?.label ?? this.freeChannelLabel("feishu", bot.name),
+ defaultBot: cur?.defaultBot ?? botId,
+ enabled: cur?.enabled ?? true,
+ credentials: { appId: bot.feishuAppId, appSecret: bot.feishuAppSecret },
+ createdAt: cur?.createdAt ?? Date.now(),
+ });
+ this.store.updateBot(botId, { feishuAppId: "", feishuAppSecret: "" });
+ }
+ if (this.store.getWeixinAccount(botId)) this.ensureChannelAccount(botId, "weixin", bot.name, bot.weixinEnabled);
+ for (const id of MESSENGERS) if (this.store.getMessengerAccount(botId, id)) this.ensureChannelAccount(botId, id, bot.name);
+ }
+
+ /** 新账号的默认名字:同一个渠道里不重复,也不能全是数字(用户说名字时要能选到唯一一个) */
+ private freeChannelLabel(channel: string, wanted: string): string {
+ const raw = wanted.trim().slice(0, 76);
+ const fallback = channel === "weixin" ? t("app.weixin_account_name") : channel === "feishu" ? t("app.feishu_account_name") : (MESSENGER_LABEL[channel as MessengerId] ?? channel);
+ const base = !raw || /^\d+$/.test(raw) ? fallback : raw;
+ const taken = new Set(this.store.listChannelAccounts(channel).map((a) => a.label.toLowerCase()));
+ if (!taken.has(base.toLowerCase())) return base;
+ for (let n = 2; ; n++) if (!taken.has(`${base} ${n}`.toLowerCase())) return `${base} ${n}`;
+ }
+
+ private ensureChannelAccount(key: string, channel: string, label: string, enabled = true): ChannelAccount {
+ const cur = this.store.getChannelAccount(key, channel);
+ if (cur) return cur;
+ const account: ChannelAccount = { key, channel, label: this.freeChannelLabel(channel, label), defaultBot: defaultBotFor(this.store, key, channel), enabled, credentials: {}, createdAt: Date.now() };
+ this.store.saveChannelAccount(account);
+ return account;
+ }
+
+ /** 启动一个 key 下的所有渠道账号(升级前同一个 key 可能有好几个渠道) */
+ async startBot(key: string): Promise<void> {
+ this.adoptBotChannels(key);
+ const ch: BotChannels = this.channels.get(key) ?? {};
+ this.channels.set(key, ch);
+ const route = (channel: string) => (peer: string) => botForPeer(this.store, key, channel, peer);
+ const nameOf = (channel: string) => this.store.getChannelAccount(key, channel)?.label ?? key;
+
+ const fsAccount = this.store.getChannelAccount(key, "feishu");
+ const { appId, appSecret } = fsAccount?.credentials ?? {};
+ if (fsAccount?.enabled && appId && appSecret && !ch.feishu) {
+ registerSecret(appSecret);
+ const transport = this.opts.feishuTransport?.({ id: key, feishuAppId: appId, feishuAppSecret: appSecret }) ?? new LarkTransport(appId, appSecret);
+ ch.feishu = new FeishuChannel(key, transport, this.runtime, this.queue, this.config.feishu.throttleMs, this.outbox, this.store);
ch.feishu.delivery = this.delivery;
+ ch.feishu.route = route("feishu");
// 读不了飞书的历史消息:离线时发来的补不上,提示一次
- ch.feishu.onHistoryDenied = () => this.notice("warn", t("app.feishu_history_denied", { name: this.store.getBot(bot.id)?.name ?? bot.name }));
+ ch.feishu.onHistoryDenied = () => this.notice("warn", t("app.feishu_history_denied", { name: nameOf("feishu") }));
// 代理自己醒来的一轮(后台命令结束):经出站队列回复到这个会话最近收到的那条消息
const fs = ch.feishu;
- this.runtime.registerReplier(bot.id, "feishu", (conv, handle, key) => (handle?.messageId ? { out: fs.followUp(conv.peerId, handle.messageId, key) } : undefined));
+ this.runtime.registerReplier(key, "feishu", (conv, handle, wakeKey) => (handle?.messageId ? { out: fs.followUp(conv.peerId, handle.messageId, wakeKey, conv.botId) } : undefined));
ch.feishuError = undefined;
const feishu = ch.feishu;
detached(() => feishu.start()).catch((e) => {
ch.feishuError = (e as Error).message;
- this.notice("warn", t("app.feishu_failed", { name: bot.name, message: ch.feishuError }));
+ this.notice("warn", t("app.feishu_failed", { name: nameOf("feishu"), message: ch.feishuError }));
});
- log.info(`bot ${bot.id}: feishu starting`, { appId: bot.feishuAppId, secret: mask(bot.feishuAppSecret) });
+ log.info(`account ${key}: feishu starting`, { appId, secret: mask(appSecret) });
}
- if (bot.weixinEnabled && !ch.weixin) {
- ch.weixin = new WeixinChannel(bot.id, this.store, this.runtime, this.queue, {
+
+ registerSecret(this.store.getWeixinAccount(key)?.botToken);
+ if (this.store.getChannelAccount(key, "weixin")?.enabled && !ch.weixin) {
+ ch.weixin = new WeixinChannel(key, this.store, this.runtime, this.queue, {
fetchImpl: this.opts.weixinFetch,
cdnBaseUrl: this.config.weixin.cdnBaseUrl,
pollTimeoutMs: this.opts.weixinPollTimeoutMs,
outbox: this.outbox,
delivery: this.delivery,
});
+ ch.weixin.route = route("weixin");
ch.weixin.onExpired = () => {
- this.notice("warn", t("app.weixin_expired", { name: bot.name }));
+ this.notice("warn", t("app.weixin_expired", { name: nameOf("weixin") }));
this.attention.kick();
};
const wx = ch.weixin;
// 代理自己醒来的一轮:经出站队列发给这个微信用户(发送时才查 24 小时窗口和配额)
- this.runtime.registerReplier(bot.id, "weixin", (conv, _handle, key) => ({ out: wx.followUp(conv.peerId, key) }));
+ this.runtime.registerReplier(key, "weixin", (conv, _handle, wakeKey) => ({ out: wx.followUp(conv.peerId, wakeKey, conv.botId) }));
detached(() => wx.start());
}
- for (const id of MESSENGERS) this.startMessenger(bot, id, ch);
+ for (const id of MESSENGERS) this.startMessenger(key, id, ch);
}
/** 填了凭据、还没在跑的平台:连上 */
- private startMessenger(bot: Bot, id: MessengerId, ch: BotChannels): void {
- const acct = this.store.getMessengerAccount(bot.id, id);
- if (!acct || ch.messengers?.[id]) return;
+ private startMessenger(key: string, id: MessengerId, ch: BotChannels): void {
+ const acct = this.store.getMessengerAccount(key, id);
+ if (!acct || ch.messengers?.[id] || this.store.getChannelAccount(key, id)?.enabled === false) return;
for (const secret of Object.values(acct.credentials)) registerSecret(secret);
- const transport = this.opts.messengerTransport?.(id, bot.id, acct.credentials) ?? createTransport(id, bot.id, acct.credentials, this.store);
- const channel = new MessengerChannel(bot.id, transport, this.runtime, this.queue, this.outbox);
+ const transport = this.opts.messengerTransport?.(id, key, acct.credentials) ?? createTransport(id, key, acct.credentials, this.store);
+ const channel = new MessengerChannel(key, transport, this.runtime, this.queue, this.outbox);
channel.delivery = this.delivery;
+ channel.route = (peer) => botForPeer(this.store, key, id, peer);
channel.onFatal = (detail) => {
(ch.messengerErrors ??= {})[id] = detail;
- this.notice("warn", t("app.messenger_failed", { name: this.store.getBot(bot.id)?.name ?? bot.name, channel: MESSENGER_LABEL[id], message: detail }));
+ this.notice("warn", t("app.messenger_failed", { name: this.store.getChannelAccount(key, id)?.label ?? key, channel: MESSENGER_LABEL[id], message: detail }));
};
(ch.messengers ??= {})[id] = channel;
if (ch.messengerErrors) delete ch.messengerErrors[id];
// 代理自己醒来的一轮(后台命令结束):经出站队列发到这个会话
- this.runtime.registerReplier(bot.id, id, (conv, _handle, key) => ({ out: channel.followUp(conv.peerId, key) }));
+ this.runtime.registerReplier(key, id, (conv, _handle, wakeKey) => ({ out: channel.followUp(conv.peerId, wakeKey, conv.botId) }));
detached(() => channel.start()).catch((e) => channel.onFatal?.((e as Error).message));
- log.info(`bot ${bot.id}: ${id} starting`);
+ log.info(`account ${key}: ${id} starting`);
}
- private async stopMessenger(botId: string, id: MessengerId): Promise<void> {
- const ch = this.channels.get(botId);
- this.runtime.registerReplier(botId, id, undefined);
+ private async stopMessenger(key: string, id: MessengerId): Promise<void> {
+ const ch = this.channels.get(key);
+ this.runtime.registerReplier(key, id, undefined);
await ch?.messengers?.[id]?.stop().catch(() => {});
if (ch?.messengers) delete ch.messengers[id];
if (ch?.messengerErrors) delete ch.messengerErrors[id];
@@ -884,14 +936,14 @@ export class App {
* 连接(或改凭据):留空的凭据沿用已保存的。凭据被平台拒绝就报错、不保存;一时连不上平台照样保存,渠道自己会重试。
* 换了一个机器人(凭据变了):主人对不上了,连上后第一个发消息的人成为主人;Telegram 的收取位置也作废。
*/
- async connectMessenger(botId: string, id: MessengerId, input: Record<string, unknown>): Promise<void> {
- const old = this.store.getMessengerAccount(botId, id);
+ async connectMessenger(key: string, id: MessengerId, input: Record<string, unknown>): Promise<void> {
+ const old = this.store.getMessengerAccount(key, id);
const credentials: Record<string, string> = {};
for (const field of MESSENGER_FIELDS[id]) {
credentials[field] = String(input[field] ?? "").trim() || (old?.credentials[field] ?? "");
if (!credentials[field]) throw new PlatformError(t("channel.messengerMissing", { channel: MESSENGER_LABEL[id] }), true);
}
- const transport = this.opts.messengerTransport?.(id, botId, credentials) ?? createTransport(id, botId, credentials, this.store);
+ const transport = this.opts.messengerTransport?.(id, key, credentials) ?? createTransport(id, key, credentials, this.store);
let name = old?.name ?? "";
try {
name = (await transport.verify?.())?.name ?? name;
@@ -900,57 +952,134 @@ export class App {
log.warn("couldn't verify the credentials now, saving anyway", { channel: id, message: (e as Error).message.slice(0, 200) });
}
const changed = MESSENGER_FIELDS[id].some((f) => f !== "appToken" && credentials[f] !== old?.credentials[f]);
- await this.stopMessenger(botId, id);
+ await this.stopMessenger(key, id);
if (changed) {
- this.access.resetOwner(botId, id);
- if (id === "telegram") this.store.deleteKV(telegramOffsetKey(botId));
+ this.access.resetOwner(key, id);
+ if (id === "telegram") this.store.deleteKV(telegramOffsetKey(key));
}
- this.store.saveMessengerAccount({ botId, channel: id, credentials, name });
- await this.startBot(botId);
+ this.store.saveMessengerAccount({ botId: key, channel: id, credentials, name });
+ this.ensureChannelAccount(key, id, name || MESSENGER_LABEL[id]);
+ await this.startBot(key);
}
- async disconnectMessenger(botId: string, id: MessengerId): Promise<void> {
- await this.stopMessenger(botId, id);
- this.access.resetOwner(botId, id);
- this.store.deleteMessengerAccount(botId, id);
- if (id === "telegram") this.store.deleteKV(telegramOffsetKey(botId));
+ async disconnectMessenger(key: string, id: MessengerId): Promise<void> {
+ await this.stopMessenger(key, id);
+ this.access.resetOwner(key, id);
+ this.store.deleteMessengerAccount(key, id);
+ this.store.deleteChannelAccount(key, id);
+ if (id === "telegram") this.store.deleteKV(telegramOffsetKey(key));
}
- /** 信息面板的一行:状态、平台上的名字、已保存凭据的掩码(界面显示"留空不修改") */
- private messengerStatus(botId: string, id: MessengerId): ChannelStatus & { account?: { name: string; saved: Record<string, string> } } {
- const acct = this.store.getMessengerAccount(botId, id);
+ /** 连接(或改凭据)飞书应用:Secret 留空沿用已保存的;App ID 留空就是移除。换了应用:单聊会话都是新的,连上后第一个发消息的人成为主人 */
+ async connectFeishu(key: string, appId: string, appSecret: string): Promise<void> {
+ if (!appId) return this.removeFeishu(key);
+ const cur = this.store.getChannelAccount(key, "feishu");
+ if (appId !== cur?.credentials.appId) this.access.resetOwner(key, "feishu");
+ const base = this.ensureChannelAccount(key, "feishu", t("app.feishu_account_name"));
+ this.store.saveChannelAccount({ ...base, credentials: { appId, appSecret: appSecret || cur?.credentials.appSecret || "" } });
+ await this.stopFeishu(key);
+ await this.startBot(key);
+ }
+
+ private async stopFeishu(key: string): Promise<void> {
+ const ch = this.channels.get(key);
+ this.runtime.registerReplier(key, "feishu", undefined);
+ await ch?.feishu?.stop().catch(() => {});
+ if (ch) {
+ ch.feishu = undefined;
+ ch.feishuError = undefined;
+ }
+ }
+
+ private async removeFeishu(key: string): Promise<void> {
+ await this.stopFeishu(key);
+ this.access.resetOwner(key, "feishu");
+ this.store.deleteChannelAccount(key, "feishu");
+ }
+
+ /** 全局渠道账号的列表(设置 › 连接):别名、默认机器人、状态。序号按渠道数,和用户说的「第二个微信」一致 */
+ channelAccounts() {
+ const seen: Record<string, number> = {};
+ return this.store.listChannelAccounts().map((a) => {
+ seen[a.channel] = (seen[a.channel] ?? 0) + 1;
+ const status = this.channelStatus(a.key) as unknown as Record<string, ChannelStatus>;
+ return {
+ key: a.key,
+ channel: a.channel,
+ number: seen[a.channel],
+ label: a.label,
+ defaultBot: defaultBotFor(this.store, a.key, a.channel),
+ enabled: a.enabled,
+ status: status[a.channel],
+ requests: this.store.listAccess({ botId: a.key, channel: a.channel, status: "pending" }).length,
+ };
+ });
+ }
+
+ /** 改别名、默认机器人、开关。别名在同一个渠道里不能重复,也不能全是数字 */
+ async updateChannelAccount(key: string, channel: string, patch: { label?: string; defaultBot?: string; enabled?: boolean }): Promise<"ok" | "missing" | "invalid" | "taken" | "no-bot"> {
+ const cur = this.store.getChannelAccount(key, channel);
+ if (!cur) return "missing";
+ const next = { ...cur };
+ if (patch.label !== undefined) {
+ const name = patch.label.trim().slice(0, 80);
+ if (!name || /^\d+$/.test(name)) return "invalid";
+ if (this.store.listChannelAccounts(channel).some((a) => a.key !== key && a.label.toLowerCase() === name.toLowerCase())) return "taken";
+ next.label = name;
+ }
+ if (patch.defaultBot !== undefined) {
+ if (!this.store.getBot(patch.defaultBot)) return "no-bot";
+ next.defaultBot = patch.defaultBot;
+ }
+ if (patch.enabled !== undefined) next.enabled = patch.enabled;
+ this.store.saveChannelAccount(next);
+ if (patch.enabled !== undefined && patch.enabled !== cur.enabled) await this.restartBot(key);
+ return "ok";
+ }
+
+ /** 移除一个渠道账号:退出登录,删掉它的凭据和名单 */
+ async removeChannelAccount(key: string, channel: string): Promise<void> {
+ if (channel === "feishu") await this.removeFeishu(key);
+ else if (channel === "weixin") await this.weixinLogout(key);
+ else if (isMessenger(channel)) await this.disconnectMessenger(key, channel);
+ for (const e of this.store.listAccess({ botId: key, channel })) this.access.remove(e.id);
+ }
+
+ /** 设置页的一行:状态、平台上的名字、已保存凭据的掩码(界面显示"留空不修改") */
+ private messengerStatus(key: string, id: MessengerId): ChannelStatus & { account?: { name: string; saved: Record<string, string> } } {
+ const acct = this.store.getMessengerAccount(key, id);
if (!acct) return { state: "disabled", since: 0 };
- const ch = this.channels.get(botId);
+ const ch = this.channels.get(key);
const error = ch?.messengerErrors?.[id];
const st: ChannelStatus = error ? { state: "error", detail: error, since: Date.now() } : ch?.messengers?.[id]?.status ?? { state: "disabled", since: 0 };
return { ...st, account: { name: acct.name, saved: Object.fromEntries(Object.entries(acct.credentials).map(([k, v]) => [k, mask(v)])) } };
}
- async stopBot(botId: string): Promise<void> {
- const ch = this.channels.get(botId);
+ async stopBot(key: string): Promise<void> {
+ const ch = this.channels.get(key);
if (!ch) return;
ch.weixinLogin?.cancel();
- this.runtime.registerReplier(botId, "feishu", undefined);
- this.runtime.registerReplier(botId, "weixin", undefined);
- for (const id of MESSENGERS) await this.stopMessenger(botId, id);
+ this.runtime.registerReplier(key, "feishu", undefined);
+ this.runtime.registerReplier(key, "weixin", undefined);
+ for (const id of MESSENGERS) await this.stopMessenger(key, id);
await ch.feishu?.stop().catch(() => {});
await ch.weixin?.stop().catch(() => {});
- this.channels.delete(botId);
+ this.channels.delete(key);
}
- async restartBot(botId: string): Promise<void> {
- await this.stopBot(botId);
- await this.startBot(botId);
+ async restartBot(key: string): Promise<void> {
+ await this.stopBot(key);
+ await this.startBot(key);
}
// ---------- 微信扫码 ----------
- startWeixinLogin(botId: string): WeixinLogin {
- const ch = this.channels.get(botId) ?? {};
- this.channels.set(botId, ch);
+ startWeixinLogin(key: string): WeixinLogin {
+ const ch = this.channels.get(key) ?? {};
+ this.channels.set(key, ch);
ch.weixinLogin?.cancel();
const login = new WeixinLogin({
apiBaseUrl: this.config.weixin.apiBaseUrl,
- pngPath: path.join(this.config.dataDir, "weixin", `${botId}-login-qr.png`),
+ pngPath: path.join(this.config.dataDir, "weixin", `${key}-login-qr.png`),
fetchImpl: this.opts.weixinFetch,
printTerminal: this.opts.printQrToTerminal ?? true,
pollDelayMs: this.opts.weixinFetch ? 50 : 1000,
@@ -958,42 +1087,44 @@ export class App {
ch.weixinLogin = login;
void login.run().then(async (res) => {
if (!res) return;
- // 换了一个微信扫码:原来的主人留在允许名单里(可在机器人设置里移除),不会被拦在外面
- 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");
+ // 换了一个微信扫码:原来的主人留在允许名单里(可以移除),不会被拦在外面
+ const prevOwner = this.store.getWeixinAccount(key)?.ownerUserId;
+ this.store.saveWeixinAccount({ botId: key, botToken: res.botToken, ilinkBotId: res.ilinkBotId, baseUrl: res.baseUrl, ownerUserId: res.userId });
+ if (prevOwner && prevOwner !== res.userId) this.access.allow(key, "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 });
+ if (res.userId) this.access.resetOwner(key, "weixin", { keep: true });
+ const account = this.ensureChannelAccount(key, "weixin", t("app.weixin_account_name"));
+ if (!account.enabled) this.store.saveChannelAccount({ ...account, enabled: true });
await ch.weixin?.stop();
ch.weixin = undefined;
- await this.startBot(botId);
- this.notice("info", t("app.weixin_connected", { name: bot?.name ?? botId }));
+ await this.startBot(key);
+ this.notice("info", t("app.weixin_connected", { name: account.label }));
});
return login;
}
- async weixinLogout(botId: string): Promise<void> {
- const ch = this.channels.get(botId);
+ async weixinLogout(key: string): Promise<void> {
+ const ch = this.channels.get(key);
await ch?.weixin?.stop();
if (ch) ch.weixin = undefined;
- this.store.deleteWeixinAccount(botId);
- await this.startBot(botId);
+ this.runtime.registerReplier(key, "weixin", undefined);
+ this.store.deleteWeixinAccount(key);
+ this.store.deleteChannelAccount(key, "weixin");
}
- channelStatus(botId: string): { feishu: ChannelStatus; weixin: ChannelStatus & { login?: unknown; quota?: unknown } } & Record<MessengerId, ChannelStatus> {
- const bot = this.store.getBot(botId);
- const ch = this.channels.get(botId);
- const feishu: ChannelStatus = !bot?.feishuAppId
+ channelStatus(key: string): { feishu: ChannelStatus; weixin: ChannelStatus & { login?: unknown; quota?: unknown } } & Record<MessengerId, ChannelStatus> {
+ const ch = this.channels.get(key);
+ const fsAccount = this.store.getChannelAccount(key, "feishu");
+ const feishu: ChannelStatus & { account?: { appId: string; saved: { appSecret: string } } } = !fsAccount?.credentials.appId
? { state: "disabled", detail: t("channel.feishu_no_credentials"), since: 0 }
: ch?.feishuError
? { state: "error", detail: ch.feishuError, since: Date.now() }
: ch?.feishu?.status ?? { state: "disabled", since: 0 };
- const acct = this.store.getWeixinAccount(botId);
+ if (fsAccount?.credentials.appId) feishu.account = { appId: fsAccount.credentials.appId, saved: { appSecret: mask(fsAccount.credentials.appSecret) } };
+ const acct = this.store.getWeixinAccount(key);
const wx = ch?.weixin?.status ?? (acct ? { state: "disabled" as const, since: 0 } : { state: "login_required" as const, detail: t("channel.wx_login_required"), since: 0 });
const quota = ch?.weixin
- ? this.store.listWeixinPeers(botId).map((p) => ({ userId: p.userId, remaining: ch.weixin!.quota.remaining(p.userId), windowStartedAt: p.windowStartedAt }))
+ ? this.store.listWeixinPeers(key).map((p) => ({ userId: p.userId, remaining: ch.weixin!.quota.remaining(p.userId), windowStartedAt: p.windowStartedAt }))
: [];
return {
feishu,
@@ -1003,9 +1134,9 @@ export class App {
login: ch?.weixinLogin?.snapshot,
quota,
},
- telegram: this.messengerStatus(botId, "telegram"),
- slack: this.messengerStatus(botId, "slack"),
- discord: this.messengerStatus(botId, "discord"),
+ telegram: this.messengerStatus(key, "telegram"),
+ slack: this.messengerStatus(key, "slack"),
+ discord: this.messengerStatus(key, "discord"),
};
}
}
diff --git a/src/channels/feishu/card.ts b/src/channels/feishu/card.ts
index 3ef05ae..6b33104 100644
--- a/src/channels/feishu/card.ts
+++ b/src/channels/feishu/card.ts
@@ -93,6 +93,7 @@ export async function deliverFeishu(transport: FeishuTransport, row: OutboxRow,
export interface FeishuOutbox {
outbox: Outbox;
botId: string;
+ account?: string;
chatId: string;
key: string;
ttlMs?: number;
@@ -166,8 +167,8 @@ export class FeishuReply implements ReplySession {
/** 交给出站队列(先落库再发,等第一次发送结束);没有队列就直接发 */
private async post(kind: OutboxKind, body: OutboxBody, role: string, ttlMs?: number): Promise<void> {
if (this.out) {
- const { outbox, botId, chatId, key } = this.out;
- await outbox.send({ id: `fs:${botId}:${key}:${role}`, botId, channel: "feishu", peerId: chatId, kind, body, replyTo: this.replyTo, ttlMs: ttlMs ?? this.out.ttlMs });
+ const { outbox, botId, account, chatId, key } = this.out;
+ await outbox.send({ id: `fs:${botId}:${key}:${role}`, botId, account, channel: "feishu", peerId: chatId, kind, body, replyTo: this.replyTo, ttlMs: ttlMs ?? this.out.ttlMs });
return;
}
const row = { id: crypto.randomUUID(), kind, body, replyTo: this.replyTo, progress: 0, attempts: 0 } as OutboxRow;
diff --git a/src/channels/feishu/channel.ts b/src/channels/feishu/channel.ts
index af69d9f..bb11eb4 100644
--- a/src/channels/feishu/channel.ts
+++ b/src/channels/feishu/channel.ts
@@ -72,9 +72,14 @@ export class FeishuChannel {
private unregister: (() => void) | undefined;
/** 正在补离线时漏掉的消息 */
private catching: Promise<number> | undefined;
+ /** 这个会话的消息交给哪个机器人(app.ts 按 core/routes.ts 设置);没设置时账号 key 就是机器人 id */
+ route: ((chatId: string) => string) | undefined;
+ private botOf(chatId: string): string {
+ return this.route?.(chatId) ?? this.account;
+ }
constructor(
- private botId: string,
+ private account: string,
private transport: FeishuTransport,
private runtime: BotRuntime,
private queue: KeyedQueue,
@@ -92,16 +97,16 @@ export class FeishuChannel {
async start(): Promise<void> {
// 上线:出站队列里这个机器人的飞书消息(含上次没发完的)由这里发
- this.unregister ??= this.outbox.register(this.botId, "feishu", (row, progress) => deliverFeishu(this.transport, row, progress));
+ this.unregister ??= this.outbox.register(this.account, "feishu", (row, progress) => deliverFeishu(this.transport, row, progress));
await this.transport.start(
(ev) => this.onMessage(ev),
(state, detail) => {
this.status = { state, detail, since: Date.now() };
- this.log.info(`bot ${this.botId} ws ${state}`, detail ? { detail } : undefined);
+ this.log.info(`bot ${this.account} ws ${state}`, detail ? { detail } : undefined);
// 连上(启动、断线重连):长连接不补推离线时的事件,自己去会话历史里补
if (state === "connected") void this.catchUp().catch((e) => this.log.warn("feishu catch-up failed", { message: (e as Error).message.slice(0, 200) }));
},
- (a) => this.runtime.cardAction(this.botId, a.value, `feishu:${a.operatorOpenId}`),
+ (a) => this.runtime.cardAction(this.account, a.value, `feishu:${a.operatorOpenId}`),
);
}
@@ -120,7 +125,8 @@ export class FeishuChannel {
const inbound: InboundEvent = {
id: ev.messageId,
channel: "feishu",
- botId: this.botId,
+ botId: this.botOf(ev.chatId),
+ account: this.account,
conversation: { kind: "dm", id: ev.chatId },
sender: { id: ev.senderOpenId },
parts: feishuParts(ev),
@@ -131,19 +137,19 @@ export class FeishuChannel {
};
// 人在:排着的主动消息(免打扰、每天上限)不用再等,排在这次的回复前面
const delivery = this.delivery;
- if (delivery) this.outbox.release(this.botId, "feishu", ev.chatId, (rows) => delivery.combine(rows));
+ if (delivery) this.outbox.releasePeer("feishu", ev.chatId, (rows) => delivery.combine(rows), this.account);
// 审批/提问回复在入队前处理(正在进行的回合正等着它)
// 没处理掉但带 ack 的(前一条还在处理):先说一声,消息照常入队
const intercepted = this.runtime.interceptReply(inbound);
if (intercepted.ack) {
- const ack = new FeishuReply(this.transport, ev.messageId, this.throttleMs, { outbox: this.outbox, botId: this.botId, chatId: ev.chatId, key: `${ev.messageId}:ack`, ttlMs: 10 * 60_000 });
+ const ack = new FeishuReply(this.transport, ev.messageId, this.throttleMs, { outbox: this.outbox, botId: this.botOf(ev.chatId), account: this.account, chatId: ev.chatId, key: `${ev.messageId}:ack`, ttlMs: 10 * 60_000 });
const p = ack.apply({ type: "text", text: intercepted.ack }).catch((e) => this.log.warn("ack failed", { message: (e as Error).message }));
this.pending.add(p);
void p.finally(() => this.pending.delete(p));
}
if (intercepted.handled) return true;
- const p = this.queue.run(`feishu:${this.botId}:${ev.chatId}`, async () => {
- const reply = new FeishuReply(this.transport, ev.messageId, this.throttleMs, { outbox: this.outbox, botId: this.botId, chatId: ev.chatId, key: ev.messageId });
+ const p = this.queue.run(`feishu:${this.account}:${ev.chatId}`, async () => {
+ const reply = new FeishuReply(this.transport, ev.messageId, this.throttleMs, { outbox: this.outbox, botId: this.botOf(ev.chatId), account: this.account, chatId: ev.chatId, key: ev.messageId });
try {
await this.runtime.handle(inbound, reply);
} catch (e) {
@@ -158,7 +164,7 @@ export class FeishuChannel {
/** 这个会话见到的最后一条消息(离线补消息从它之后开始;存在 KV 里,重启也在) */
private seenKey(chatId: string): string {
- return `feishu-seen:${this.botId}:${chatId}`;
+ return `feishu-seen:${this.account}:${chatId}`;
}
private seen(chatId: string): { at: number; id: string } | undefined {
try {
@@ -189,7 +195,7 @@ export class FeishuChannel {
const list = this.transport.listMessages?.bind(this.transport);
if (!store || !list) return 0;
let fed = 0;
- const convs = store.listConversations(this.botId).filter((c) => c.channel === "feishu" && c.updatedAt >= now - CATCH_UP_ACTIVE_MS);
+ const convs = store.listAccountConversations(this.account, "feishu").filter((c) => c.updatedAt >= now - CATCH_UP_ACTIVE_MS);
for (const c of convs) {
// 见到的最后一条之后;还没记过(升级前的会话)就从最后一次来往之后
const seen = this.seen(c.peerId);
@@ -202,25 +208,25 @@ export class FeishuChannel {
this.historyDenied(e.message);
return fed;
}
- this.log.warn("feishu catch-up: could not read the chat history", { bot: this.botId, message: (e as Error).message.slice(0, 200) });
+ this.log.warn("feishu catch-up: could not read the chat history", { bot: this.account, message: (e as Error).message.slice(0, 200) });
continue;
}
store.deleteKV(this.deniedKey);
for (const ev of missed.slice(-CATCH_UP_MAX)) if (ev.messageId !== seen?.id && this.onMessage({ ...ev, chatId: ev.chatId || c.peerId })) fed++;
}
- if (fed) this.log.info("caught up on feishu messages sent while offline", { bot: this.botId, count: fed });
+ if (fed) this.log.info("caught up on feishu messages sent while offline", { bot: this.account, count: fed });
return fed;
}
private get deniedKey(): string {
- return `feishu-history-denied:${this.botId}`;
+ return `feishu-history-denied:${this.account}`;
}
/** 读不了历史消息:日志和提示各一次(读得了之后再没权限会再提示) */
private historyDenied(detail: string): void {
if (this.store?.getKV(this.deniedKey)) return;
this.store?.setKV(this.deniedKey, String(Date.now()));
- this.log.warn("feishu catch-up: the app may not read chat history; messages sent while offline are not caught up", { bot: this.botId, detail: detail.slice(0, 200) });
+ this.log.warn("feishu catch-up: the app may not read chat history; messages sent while offline are not caught up", { bot: this.account, detail: detail.slice(0, 200) });
this.onHistoryDenied?.();
}
@@ -228,8 +234,8 @@ export class FeishuChannel {
* 主动发到一个飞书会话的回复(代理自己醒来的一轮:后台命令结束):回复用户最近的那条消息(replyTo 存在会话的 KV 里,重启也在),
* 和普通回复一样经出站队列,id 由 key 推出。
*/
- followUp(chatId: string, replyTo: string, key: string): ReplySession {
- return new FeishuReply(this.transport, replyTo, this.throttleMs, { outbox: this.outbox, botId: this.botId, chatId, key });
+ followUp(chatId: string, replyTo: string, key: string, botId?: string): ReplySession {
+ return new FeishuReply(this.transport, replyTo, this.throttleMs, { outbox: this.outbox, botId: botId ?? this.botOf(chatId), account: this.account, chatId, key });
}
async idle(): Promise<void> {
@@ -243,8 +249,8 @@ export class FeishuChannel {
*/
notify(chatId: string, text: string, id?: string): boolean {
if (!this.transport.sendText) return false;
- const key = id ?? `notice:${this.botId}:feishu:${stableId(`${chatId}:${text}`, Math.floor(Date.now() / 60_000), 16)}`;
- void this.outbox.send({ id: key, botId: this.botId, channel: "feishu", peerId: chatId, kind: "notice", body: { text } });
+ const key = id ?? `notice:${this.account}:feishu:${stableId(`${chatId}:${text}`, Math.floor(Date.now() / 60_000), 16)}`;
+ void this.outbox.send({ id: key, botId: this.botOf(chatId), account: this.account, channel: "feishu", peerId: chatId, kind: "notice", body: { text } });
return true;
}
}
diff --git a/src/channels/messenger/channel.ts b/src/channels/messenger/channel.ts
index badb54d..bd46f7a 100644
--- a/src/channels/messenger/channel.ts
+++ b/src/channels/messenger/channel.ts
@@ -68,6 +68,7 @@ export async function deliverMessenger(transport: MessengerTransport, row: Outbo
export interface MessengerOutbox {
outbox: Outbox;
botId: string;
+ account?: string;
key: string;
ttlMs?: number;
}
@@ -182,8 +183,8 @@ export class MessengerReply implements ReplySession {
/** 交给出站队列(先落库再发,等第一次发送结束);没有队列就直接发(单元测试) */
private async post(kind: OutboxKind, body: OutboxBody, role: string, ttlMs?: number): Promise<void> {
if (this.out) {
- const { outbox, botId, key } = this.out;
- await outbox.send({ id: `${this.transport.id}:${botId}:${key}:${role}`, botId, channel: this.transport.id, peerId: this.chatId, kind, body, ttlMs: ttlMs ?? this.out.ttlMs });
+ const { outbox, botId, account, key } = this.out;
+ await outbox.send({ id: `${this.transport.id}:${botId}:${key}:${role}`, botId, account, channel: this.transport.id, peerId: this.chatId, kind, body, ttlMs: ttlMs ?? this.out.ttlMs });
return;
}
const row = { id: `${role}`, kind, body, peerId: this.chatId, replyTo: "", progress: 0, attempts: 0 } as OutboxRow;
@@ -232,7 +233,7 @@ export class MessengerChannel {
private running = false;
constructor(
- private botId: string,
+ private account: string,
private transport: MessengerTransport,
private runtime: BotRuntime,
private queue: KeyedQueue,
@@ -242,6 +243,12 @@ export class MessengerChannel {
this.log = logger(transport.id);
}
+ /** 这个会话的消息交给哪个机器人(app.ts 按 core/routes.ts 设置);没设置时账号 key 就是机器人 id */
+ route: ((chatId: string) => string) | undefined;
+ private botOf(chatId: string): string {
+ return this.route?.(chatId) ?? this.account;
+ }
+
private get id() {
return this.transport.id;
}
@@ -249,7 +256,7 @@ export class MessengerChannel {
async start(): Promise<void> {
this.running = true;
// 上线:出站队列里这个机器人在这个平台上的消息(含上次没发完的)由这里发
- this.unregister ??= this.outbox.register(this.botId, this.id, async (row, progress) => {
+ this.unregister ??= this.outbox.register(this.account, this.id, async (row, progress) => {
if (!this.running) throw new Later(tr("channel.laterNotRunning"));
await deliverMessenger(this.transport, row, progress);
});
@@ -258,7 +265,7 @@ export class MessengerChannel {
(state, detail, fatal) => {
if (state === this.status.state && detail === this.status.detail) return;
this.status = { state, detail, since: Date.now() };
- this.log.info(`bot ${this.botId} ${state}`, detail ? { detail } : undefined);
+ this.log.info(`bot ${this.account} ${state}`, detail ? { detail } : undefined);
if (fatal) this.onFatal?.(detail ?? "");
},
);
@@ -280,7 +287,8 @@ export class MessengerChannel {
const ev: InboundEvent = {
id: m.id,
channel: this.id,
- botId: this.botId,
+ botId: this.botOf(m.chatId),
+ account: this.account,
conversation: { kind: "dm", id: m.chatId },
sender: { id: m.senderId, ...(m.senderName ? { name: m.senderName } : {}) },
parts: messengerParts(m),
@@ -289,7 +297,7 @@ export class MessengerChannel {
};
// 人在:排着的主动消息(免打扰、每天上限)不用再等,排在这次的回复前面
const delivery = this.delivery;
- if (delivery) this.outbox.release(this.botId, this.id, m.chatId, (rows) => delivery.combine(rows));
+ if (delivery) this.outbox.releasePeer(this.id, m.chatId, (rows) => delivery.combine(rows), this.account);
// 审批/提问回复、准入在入队前处理(正在进行的回合正等着它);没处理掉但带 ack 的:先说一声,消息照常入队
const intercepted = this.runtime.interceptReply(ev);
if (intercepted.ack) {
@@ -298,7 +306,7 @@ export class MessengerChannel {
}
if (intercepted.handled) return true;
this.track(
- this.queue.run(`${this.id}:${this.botId}:${m.chatId}`, async () => {
+ this.queue.run(`${this.id}:${this.account}:${m.chatId}`, async () => {
const reply = this.reply(m.chatId, m.id);
try {
if (m.files.length) ev.parts = messengerParts(m, await this.download(m));
@@ -312,8 +320,8 @@ export class MessengerChannel {
return true;
}
- private reply(chatId: string, key: string, ttlMs?: number): MessengerReply {
- return new MessengerReply(this.transport, chatId, this.throttleMs, { outbox: this.outbox, botId: this.botId, key, ttlMs });
+ private reply(chatId: string, key: string, ttlMs?: number, botId?: string): MessengerReply {
+ return new MessengerReply(this.transport, chatId, this.throttleMs, { outbox: this.outbox, botId: botId ?? this.botOf(chatId), account: this.account, key, ttlMs });
}
private track(p: Promise<void>): void {
@@ -337,15 +345,15 @@ export class MessengerChannel {
}
/** 代理自己醒来的一轮(后台命令结束):和普通回复一样经出站队列,id 由 key 推出 */
- followUp(chatId: string, key: string): ReplySession {
- return this.reply(chatId, key);
+ followUp(chatId: string, key: string, botId?: string): ReplySession {
+ return this.reply(chatId, key, undefined, botId);
}
/** 主动发一条通知到单聊(使用请求、批准结果、余额提醒):进出站队列;id 不给时同样的内容一分钟内只发一次 */
notify(chatId: string, text: string, id?: string): boolean {
if (!chatId) return false;
- const key = id ?? `notice:${this.botId}:${this.id}:${stableId(`${chatId}:${text}`, Math.floor(Date.now() / 60_000), 16)}`;
- void this.outbox.send({ id: key, botId: this.botId, channel: this.id, peerId: chatId, kind: "notice", body: { text } });
+ const key = id ?? `notice:${this.account}:${this.id}:${stableId(`${chatId}:${text}`, Math.floor(Date.now() / 60_000), 16)}`;
+ void this.outbox.send({ id: key, botId: this.botOf(chatId), account: this.account, channel: this.id, peerId: chatId, kind: "notice", body: { text } });
return true;
}
diff --git a/src/channels/weixin/channel.ts b/src/channels/weixin/channel.ts
index 5bf5fa3..3177a8f 100644
--- a/src/channels/weixin/channel.ts
+++ b/src/channels/weixin/channel.ts
@@ -191,6 +191,7 @@ export async function deliverWeixin(client: IlinkClient, quota: WeixinQuota, row
export interface WeixinOutbox {
outbox: Outbox;
botId: string;
+ account?: string;
key: string;
ttlMs?: number;
}
@@ -258,8 +259,8 @@ export class WeixinReply implements ReplySession {
this.typingTimer = undefined;
}
if (this.out) {
- const { outbox, botId, key } = this.out;
- await outbox.send({ id: `wx:${botId}:${key}:${role}`, botId, channel: "weixin", peerId: this.userId, kind, body, ttlMs: ttlMs ?? this.out.ttlMs });
+ const { outbox, botId, account, key } = this.out;
+ await outbox.send({ id: `wx:${botId}:${key}:${role}`, botId, account, channel: "weixin", peerId: this.userId, kind, body, ttlMs: ttlMs ?? this.out.ttlMs });
return;
}
const row = { id: crypto.randomUUID(), peerId: this.userId, kind, body, progress: 0, attempts: 0 } as OutboxRow;
@@ -317,16 +318,16 @@ export class WeixinChannel {
onExpired: ((botId: string) => void) | undefined;
constructor(
- private botId: string,
+ private account: string,
private store: Store,
private runtime: BotRuntime,
private queue: KeyedQueue,
private opts: { fetchImpl?: typeof fetch; cdnBaseUrl?: string; pollTimeoutMs?: number; retryDelayMs?: number; backoffMs?: number; outbox?: Outbox; delivery?: Delivery } = {},
) {
- this.quota = new WeixinQuota(store, botId);
+ this.quota = new WeixinQuota(store, account);
// 聊天回复给主动消息(进行中的任务的结果等)留出配额
const delivery = opts.delivery;
- if (delivery) this.quota.reserver = (userId) => delivery.reserved(botId, "weixin", userId);
+ if (delivery) this.quota.reserver = (userId) => delivery.reserved(this.botOf(userId), "weixin", userId);
if (opts.outbox) this.outbox = opts.outbox;
else {
this.outbox = new Outbox(store);
@@ -334,13 +335,19 @@ export class WeixinChannel {
}
}
+ /** 这个人的消息交给哪个机器人(app.ts 按 core/routes.ts 设置);没设置时账号 key 就是机器人 id */
+ route: ((userId: string) => string) | undefined;
+ private botOf(userId: string): string {
+ return this.route?.(userId) ?? this.account;
+ }
+
get running(): boolean {
return !!this.loop;
}
start(): void {
if (this.loop) return;
- const acct = this.store.getWeixinAccount(this.botId);
+ const acct = this.store.getWeixinAccount(this.account);
if (!acct) {
this.st = { state: "login_required", since: Date.now() };
return;
@@ -349,12 +356,12 @@ export class WeixinChannel {
this.abort = new AbortController();
this.loop = this.run(this.abort.signal).finally(() => (this.loop = undefined));
// 上线:出站队列里这个机器人的微信消息(含上次没发完的)由这里发
- this.unregister = this.outbox.register(this.botId, "weixin", (row, progress) => this.deliver(row, progress));
+ this.unregister = this.outbox.register(this.account, "weixin", (row, progress) => this.deliver(row, progress));
}
private async deliver(row: OutboxRow, progress: (n: number) => void): Promise<void> {
if (!this.client) throw new Later(tr("channel.laterNotRunning"));
- if ((this.store.getWeixinAccount(this.botId)?.pausedUntil ?? 0) > Date.now()) throw new Later(tr("channel.laterExpired"));
+ if ((this.store.getWeixinAccount(this.account)?.pausedUntil ?? 0) > Date.now()) throw new Later(tr("channel.laterExpired"));
try {
await deliverWeixin(this.client, this.quota, row, progress);
} catch (e) {
@@ -369,27 +376,27 @@ export class WeixinChannel {
*/
tell(userId: string, text: string, id: string): boolean {
if (!this.client || !this.quota.open(userId) || this.quota.remaining(userId) <= 0) return false;
- void this.outbox.send({ id, botId: this.botId, channel: "weixin", peerId: userId, kind: "notice", body: { text, raw: true } });
+ void this.outbox.send({ id, botId: this.botOf(userId), account: this.account, channel: "weixin", peerId: userId, kind: "notice", body: { text, raw: true } });
return true;
}
/** 主动发给某个微信用户(余额提醒、重启后的提醒):同 tell;同样的内容一分钟内只发一次 */
async notify(userId: string, text: string): Promise<boolean> {
- return !!userId && this.tell(userId, text, `notice:${this.botId}:weixin:${stableId(`${userId}:${text}`, Math.floor(Date.now() / 60_000), 16)}`);
+ return !!userId && this.tell(userId, text, `notice:${this.account}:weixin:${stableId(`${userId}:${text}`, Math.floor(Date.now() / 60_000), 16)}`);
}
/** 主动提醒:发给扫码登录的那个微信用户 */
async notifyOwner(text: string): Promise<boolean> {
- return this.notify(this.store.getWeixinAccount(this.botId)?.ownerUserId ?? "", text);
+ return this.notify(this.store.getWeixinAccount(this.account)?.ownerUserId ?? "", text);
}
/**
* 主动发到一个微信会话的回复(代理自己醒来的一轮:后台命令结束):和普通回复一样经出站队列,id 由 key 推出;
* 会话凭证、24 小时窗口和配额在发送时才查(deliverWeixin),发不出去就留着,等对方下次发消息时先发。
*/
- followUp(userId: string, key: string): ReplySession {
- const token = this.store.getWeixinPeer(this.botId, userId)?.contextToken ?? "";
- return new WeixinReply(this.client!, userId, token, this.quota, { outbox: this.outbox, botId: this.botId, key });
+ followUp(userId: string, key: string, botId?: string): ReplySession {
+ const token = this.store.getWeixinPeer(this.account, userId)?.contextToken ?? "";
+ return new WeixinReply(this.client!, userId, token, this.quota, { outbox: this.outbox, botId: botId ?? this.botOf(userId), account: this.account, key });
}
async stop(): Promise<void> {
@@ -415,7 +422,7 @@ export class WeixinChannel {
let failures = 0;
this.st = { state: "connecting", since: Date.now() };
while (!signal.aborted) {
- const acct = this.store.getWeixinAccount(this.botId);
+ const acct = this.store.getWeixinAccount(this.account);
if (!acct) {
this.st = { state: "login_required", since: Date.now() };
return;
@@ -429,15 +436,15 @@ export class WeixinChannel {
const resp = await this.client!.getUpdates(acct.cursor, this.opts.pollTimeoutMs ?? 35_000, signal);
failures = 0;
if (this.st.state !== "connected") this.st = { state: "connected", since: Date.now() };
- if (resp.get_updates_buf) this.store.setWeixinCursor(this.botId, resp.get_updates_buf);
+ if (resp.get_updates_buf) this.store.setWeixinCursor(this.account, resp.get_updates_buf);
for (const m of resp.msgs ?? []) this.onMessage(m);
} catch (e) {
if (signal.aborted) return;
if (e instanceof WeixinApiError && e.sessionExpired) {
- this.log.warn(`bot ${this.botId}: iLink session expired (-14), pausing 1h; re-login required`);
- this.store.setWeixinPaused(this.botId, Date.now() + SESSION_PAUSE_MS);
+ this.log.warn(`bot ${this.account}: iLink session expired (-14), pausing 1h; re-login required`);
+ this.store.setWeixinPaused(this.account, Date.now() + SESSION_PAUSE_MS);
this.st = { state: "expired", since: Date.now() };
- this.onExpired?.(this.botId);
+ this.onExpired?.(this.account);
continue;
}
failures++;
@@ -457,15 +464,16 @@ export class WeixinChannel {
const delivery = this.opts.delivery;
// 回的是续期提醒(「ok」):先认出来(之后放出留着的消息,最近发的一条就不是提醒了)
const said = weixinParts(m.item_list).map((p) => (p.type === "text" ? p.text : "")).join("").trim();
- const ack = said ? delivery?.ack(this.botId, "weixin", userId, said) : undefined;
+ const ack = said ? delivery?.ack(this.botOf(userId), "weixin", userId, said) : undefined;
const peer = this.quota.onInbound(userId, m.context_token ?? "");
// 对方又发消息了(24 小时窗口和配额重新开始):之前留着没发的、排着的主动消息先发,合成一条(「你不在时:…」或摘要),排在这次的回复前面
- const released = this.outbox.release(this.botId, "weixin", userId, (rows) => (delivery ? delivery.combine(rows) : combineHeld(rows)));
+ const released = this.outbox.releasePeer("weixin", userId, (rows) => (delivery ? delivery.combine(rows) : combineHeld(rows)), this.account);
if (ack) return this.acked(id, userId, peer.contextToken, said, released ? "" : ack);
const ev: InboundEvent = {
id,
channel: "weixin",
- botId: this.botId,
+ botId: this.botOf(userId),
+ account: this.account,
conversation: { kind: "dm", id: userId },
sender: { id: userId },
parts: weixinParts(m.item_list),
@@ -476,15 +484,15 @@ export class WeixinChannel {
// 没处理掉但带 ack 的(前一条还在处理):先说一声,消息照常入队
const intercepted = this.runtime.interceptReply(ev);
if (intercepted.ack) {
- const ack = new WeixinReply(this.client!, userId, peer.contextToken, this.quota, { outbox: this.outbox, botId: this.botId, key: `${id}:ack`, ttlMs: SHORT_TTL_MS });
+ const ack = new WeixinReply(this.client!, userId, peer.contextToken, this.quota, { outbox: this.outbox, botId: this.botOf(userId), account: this.account, key: `${id}:ack`, ttlMs: SHORT_TTL_MS });
const p = ack.apply({ type: "text", text: intercepted.ack }).catch((e) => this.log.warn("ack failed", { message: (e as Error).message }));
this.pending.add(p);
void p.finally(() => this.pending.delete(p));
}
if (intercepted.handled) return;
const media = mediaItems(m.item_list);
- const p = this.queue.run(`weixin:${this.botId}:${userId}`, async () => {
- const reply = new WeixinReply(this.client!, userId, this.store.getWeixinPeer(this.botId, userId)?.contextToken ?? peer.contextToken, this.quota, { outbox: this.outbox, botId: this.botId, key: id });
+ const p = this.queue.run(`weixin:${this.account}:${userId}`, async () => {
+ const reply = new WeixinReply(this.client!, userId, this.store.getWeixinPeer(this.account, userId)?.contextToken ?? peer.contextToken, this.quota, { outbox: this.outbox, botId: this.botOf(userId), account: this.account, key: id });
try {
if (media.length) ev.parts = weixinParts(m.item_list, await this.download(media));
await this.runtime.handle(ev, reply);
@@ -501,11 +509,12 @@ export class WeixinChannel {
* 对方回了续期提醒(「ok」):窗口已经重新开始,不进模型;记进会话历史,回一句(留着的消息刚放出去时它们就是回应,不再多说)
*/
private acked(id: string, userId: string, contextToken: string, said: string, text: string): void {
- const conv = this.store.ensureConversation(this.botId, "weixin", userId);
+ const conv = this.store.ensureConversation(this.botOf(userId), "weixin", userId);
+ if (conv.account !== this.account) this.store.setConversationAccount(conv.id, this.account);
this.store.addMessage(conv.id, "user", said);
if (!text) return;
this.store.addMessage(conv.id, "assistant", text);
- const reply = new WeixinReply(this.client!, userId, contextToken, this.quota, { outbox: this.outbox, botId: this.botId, key: `${id}:ack` });
+ const reply = new WeixinReply(this.client!, userId, contextToken, this.quota, { outbox: this.outbox, botId: this.botOf(userId), account: this.account, key: `${id}:ack` });
const p = reply.apply({ type: "text", text }).catch((e) => this.log.warn("nudge ack failed", { message: (e as Error).message }));
this.pending.add(p);
void p.finally(() => this.pending.delete(p));
diff --git a/src/core/access.ts b/src/core/access.ts
index f17486f..4ea8847 100644
--- a/src/core/access.ts
+++ b/src/core/access.ts
@@ -57,6 +57,9 @@ export function whoText(e: Pick<AccessEntry, "channel" | "peerId" | "senderId" |
const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
+/** 名单和主人跟着渠道账号走(core/routes.ts):能用这个账号的人,可以和任何一个机器人聊 */
+const accountOf = (ev: InboundEvent): string => ev.account ?? ev.botId;
+
export class AccessControl {
constructor(
private store: Store,
@@ -79,7 +82,7 @@ export class AccessControl {
private isOwner(ev: InboundEvent): boolean {
if (ev.channel === "web") return true;
- return this.owner(ev.botId, ev.channel)?.peerId === ev.conversation.id;
+ return this.owner(accountOf(ev), ev.channel)?.peerId === ev.conversation.id;
}
/** 只判断,不登记(runtime.handle 里的兜底检查) */
@@ -89,7 +92,7 @@ export class AccessControl {
// 群聊:目前没有渠道接入群聊,保持原样;接入时要在这里加规则(例如只响应主人 @ 机器人)
if (ev.conversation.kind === "group") return true;
if (this.isOwner(ev)) return true;
- const s = this.store.getAccess(ev.botId, ev.channel, ev.conversation.id)?.status;
+ const s = this.store.getAccess(accountOf(ev), ev.channel, ev.conversation.id)?.status;
return s === "allowed" || s === "owner";
}
@@ -100,12 +103,12 @@ export class AccessControl {
admit(ev: InboundEvent): { ok: true } | { ok: false; reply?: string } {
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);
+ let e = this.store.getAccess(accountOf(ev), ev.channel, ev.conversation.id);
if (e?.status === "denied") return { ok: false };
if (!e) {
e = this.store.putAccess({
id: crypto.randomUUID(),
- botId: ev.botId,
+ botId: accountOf(ev),
channel: ev.channel,
peerId: ev.conversation.id,
senderId: ev.sender.id,
@@ -137,8 +140,8 @@ export class AccessControl {
* 他的这条消息照常处理。拒绝过的人不算。
*/
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 (ev.channel === "web" || ev.conversation.kind === "group" || this.owner(accountOf(ev), ev.channel)) return false;
+ const cur = this.store.getAccess(accountOf(ev), 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 };
@@ -146,7 +149,7 @@ export class AccessControl {
else
this.store.putAccess({
id: crypto.randomUUID(),
- botId: ev.botId,
+ botId: accountOf(ev),
channel: ev.channel,
peerId: ev.conversation.id,
senderId: ev.sender.id,
@@ -159,7 +162,7 @@ export class AccessControl {
notifiedAt: 0,
...decided,
});
- log.info("access owner claimed by the first message", { bot: ev.botId, channel: ev.channel, peer: shortPeer(ev.conversation.id) });
+ log.info("access owner claimed by the first message", { bot: accountOf(ev), channel: ev.channel, peer: shortPeer(ev.conversation.id) });
return true;
}
@@ -172,7 +175,7 @@ export class AccessControl {
}
const bot = this.store.getBot(e.botId);
const said = e.text ? tr("access.said", { text: clip(e.text, 60) }) : "";
- const text = tr("access.ownerNotice", { bot: bot?.name ?? e.botId, who: whoText(e), said, code: e.code });
+ const text = tr("access.ownerNotice", { bot: this.store.getChannelAccount(e.botId, e.channel)?.label ?? bot?.name ?? e.botId, who: whoText(e), said, code: e.code });
let sent = false;
for (const ch of ACCESS_CHANNELS) {
const o = this.owner(e.botId, ch);
@@ -198,7 +201,7 @@ export class AccessControl {
handleReply(ev: InboundEvent): { handled: boolean; ack?: string } {
const m = /^(同意|允许|批准|通过|y|yes|ok|拒绝|不同意|n|no)\s*[#::]?\s*(\d{4})$/i.exec(eventText(ev).trim());
if (!m || !this.isOwner(ev)) return { handled: false };
- const e = this.store.pendingAccessByCode(ev.botId, m[2]);
+ const e = this.store.pendingAccessByCode(accountOf(ev), m[2]);
if (!e) return { handled: false };
const allow = !/^(拒绝|不同意|n|no)$/i.test(m[1]);
this.decide(e.id, allow, `${ev.channel}:${ev.sender.id}`);
diff --git a/src/core/delivery.ts b/src/core/delivery.ts
index ebb5901..18b4560 100644
--- a/src/core/delivery.ts
+++ b/src/core/delivery.ts
@@ -19,6 +19,7 @@
import path from "node:path";
import type { BotSettings } from "../agent/settings.js";
import type { OutboxKind, OutboxPurpose, OutboxRow, Store } from "../store/db.js";
+import { botForPeer } from "./routes.js";
import type { HeldGroup, Outbox } from "./outbox.js";
import { DEFAULT_QUIET, fmtWhen, inQuiet, minuteOf, nextAt, quietEnd, quietStart, startOfDay, systemTimeZone, type QuietHours } from "./quiet.js";
import { QUOTA_WINDOW_MS, WeixinQuota } from "../channels/weixin/quota.js";
@@ -311,7 +312,7 @@ export class Delivery {
/** 用户刚发过消息(人醒着):免打扰不拦 */
private awake(p: Peer, now: number): boolean {
let last = this.store.lastUserMessageAt(p.conversationId);
- if (p.channel === "weixin") last = Math.max(last, this.store.getWeixinPeer(p.botId, p.peerId)?.windowStartedAt ?? 0);
+ if (p.channel === "weixin") last = Math.max(last, this.store.getWeixinPeer(this.store.getConversation(p.conversationId)?.account || p.botId, p.peerId)?.windowStartedAt ?? 0);
return last > now - AWAKE_MS && last <= now + 1000;
}
@@ -428,11 +429,15 @@ export class Delivery {
const now = this.now();
const tz = this.timeZone;
let next = now + NUDGE_TICK_MS;
- for (const bot of this.store.listBots()) {
- const st = this.settingsOf(bot.id);
- if (!bot.weixinEnabled || !st.nudge || this.paused(bot.id)) continue;
- const quota = new WeixinQuota(this.store, bot.id, () => now);
- for (const peer of this.store.listWeixinPeers(bot.id)) {
+ // 微信账号是全局的:按账号走一遍联系人,每个人的提醒看他现在在和哪个机器人聊(用它的免打扰和开关)
+ for (const account of this.store.weixinPeerAccounts()) {
+ const row = this.store.getChannelAccount(account, "weixin");
+ if (!(row ? row.enabled : this.store.getBot(account)?.weixinEnabled)) continue;
+ const quota = new WeixinQuota(this.store, account, () => now);
+ for (const peer of this.store.listWeixinPeers(account)) {
+ const botId = botForPeer(this.store, account, "weixin", peer.userId);
+ const st = this.settingsOf(botId);
+ if (!st.nudge || this.paused(botId)) continue;
const close = peer.windowStartedAt + QUOTA_WINDOW_MS;
if (!peer.contextToken || close <= now + NUDGE_LATEST_MS) continue;
const at = nudgeAt(peer.windowStartedAt, close, st.quiet, tz);
@@ -441,15 +446,15 @@ export class Delivery {
continue;
}
if (inQuiet(now, st.quiet, tz)) continue;
- const id = Delivery.nudgeId(bot.id, peer.userId, peer.windowStartedAt);
+ const id = Delivery.nudgeId(botId, peer.userId, peer.windowStartedAt);
if (this.store.getOutbox(id) || quota.remaining(peer.userId) <= 0) continue;
- const p = peerOf(bot.id, "weixin", peer.userId);
+ const p = peerOf(botId, "weixin", peer.userId);
const items = this.upcoming(p, close);
if (!items.length) continue;
const { text, noun } = nudgeText(items, now, tz);
- void this.o.outbox.send({ id, botId: bot.id, channel: "weixin", peerId: peer.userId, kind: "text", body: { text, raw: true }, purpose: "nudge", subject: noun, ttlMs: close - now });
+ void this.o.outbox.send({ id, botId, account, channel: "weixin", peerId: peer.userId, kind: "text", body: { text, raw: true }, purpose: "nudge", subject: noun, ttlMs: close - now });
if (this.store.getConversation(p.conversationId)) this.store.addMessage(p.conversationId, "assistant", text);
- log.info("weixin window nudge", { bot: bot.id, items: items.length, closesInMin: Math.round((close - now) / 60_000) });
+ log.info("weixin window nudge", { bot: botId, items: items.length, closesInMin: Math.round((close - now) / 60_000) });
}
}
this.arm(next - now);
diff --git a/src/core/outbox.ts b/src/core/outbox.ts
index 9657f55..4bd183a 100644
--- a/src/core/outbox.ts
+++ b/src/core/outbox.ts
@@ -48,6 +48,8 @@ export const HOLD_TTL_MS = 7 * 86400_000;
export interface OutboxInput {
id: string;
botId: string;
+ /** 走哪个渠道账号;不给就用这个会话最近的账号(主动消息:任务结果、规则提醒) */
+ account?: string;
channel: PushChannel;
/** 微信:用户 id;飞书和其他平台:单聊的 chat id */
peerId: string;
@@ -163,9 +165,9 @@ export class Outbox {
return (this.opts.now ?? Date.now)();
}
- /** 渠道上线时登记自己的发送函数,返回注销函数(渠道停下时调用;没登记的消息等着) */
- register(botId: string, channel: string, deliver: Deliver): () => void {
- const key = `${botId}:${channel}`;
+ /** 渠道上线时登记自己的发送函数(按渠道账号),返回注销函数(渠道停下时调用;没登记的消息等着) */
+ register(account: string, channel: string, deliver: Deliver): () => void {
+ const key = `${account}:${channel}`;
this.handlers.set(key, deliver);
this.kick();
return () => {
@@ -185,6 +187,7 @@ export class Outbox {
const fresh = this.store.insertOutbox({
id: input.id,
botId: input.botId,
+ account: input.account ?? this.store.getConversation(conversationId)?.account ?? "",
channel: input.channel,
conversationId,
peerId: input.peerId,
@@ -269,6 +272,13 @@ export class Outbox {
return live.length;
}
+ /** 对方发消息了:他和所有机器人的留言都放回队列(用 /bot 切换过的话,留言可能属于别的机器人)。account 也试一遍:单元测试里可能没有机器人 */
+ releasePeer(channel: string, peerId: string, combine: ((rows: OutboxRow[]) => HeldGroup[]) | undefined, account: string): number {
+ let n = 0;
+ for (const id of new Set([...this.store.listBots().map((b) => b.id), account])) n += this.release(id, channel, peerId, combine);
+ return n;
+ }
+
/** 每组第一条放回队列(换成合并后的内容),其余标记 merged;排着的从现在起重新算有效期 */
private apply(groups: HeldGroup[], now: number, reason: string): void {
for (const g of groups) {
@@ -352,7 +362,7 @@ export class Outbox {
this.kick();
continue;
}
- const deliver = this.handlers.get(`${row.botId}:${row.channel}`);
+ const deliver = this.handlers.get(`${row.account || row.botId}:${row.channel}`);
if (row.due > now || !deliver) {
// 渠道没上线:等它注册;到了过期时间也要醒来标记 gone
next = Math.min(next, deliver ? row.due : row.expiresAt);
diff --git a/src/core/routes.ts b/src/core/routes.ts
new file mode 100644
index 0000000..26e14cd
--- /dev/null
+++ b/src/core/routes.ts
@@ -0,0 +1,41 @@
+/**
+ * 聊天渠道的账号是全局的,所有机器人共用(设置 › 连接)。一个人从某个账号发来的消息交给哪个机器人:
+ * 1. 这个人在这个账号上用 /bot 选过的机器人;
+ * 2. 账号的默认机器人;
+ * 3. 默认机器人被删了:第一个机器人。
+ *
+ * 账号的 key 是命名空间:登录态、配额、名单、Telegram 收取位置都按 key 存。
+ * 旧版的渠道存在机器人身上,升级时 key 直接用机器人 id(app.ts adoptBotChannels),这些数据都不用搬,默认机器人还是原来那个。
+ */
+import type { Store } from "../store/db.js";
+
+const routeKey = (account: string, channel: string, peer: string) => `channel-route:${account}:${channel}:${peer}`;
+
+export function botForPeer(store: Store, account: string, channel: string, peer: string): string {
+ const chosen = store.getKV(routeKey(account, channel, peer));
+ if (chosen && store.getBot(chosen)) return chosen;
+ return defaultBotFor(store, account, channel);
+}
+
+export function defaultBotFor(store: Store, account: string, channel: string): string {
+ const fallback = store.getChannelAccount(account, channel)?.defaultBot;
+ if (fallback && store.getBot(fallback)) return fallback;
+ if (store.getBot(account)) return account;
+ return store.listBots()[0]?.id ?? account;
+}
+
+export function setBotForPeer(store: Store, account: string, channel: string, peer: string, botId: string): void {
+ store.setKV(routeKey(account, channel, peer), botId);
+}
+
+/** 按序号或名字找机器人(/bot 用):序号是 listBots 里的位置;名字先精确,再找唯一一个包含它的 */
+export function findBot(store: Store, input: string): { id: string; name: string } | undefined {
+ const bots = store.listBots();
+ const raw = input.trim();
+ if (/^\d+$/.test(raw)) return bots[Number(raw) - 1];
+ const lower = raw.toLowerCase();
+ const exact = bots.filter((b) => b.name.toLowerCase() === lower);
+ if (exact.length === 1) return exact[0];
+ const near = bots.filter((b) => b.name.toLowerCase().includes(lower));
+ return near.length === 1 ? near[0] : undefined;
+}
diff --git a/src/core/runtime.ts b/src/core/runtime.ts
index c5fcc42..3dff4cd 100644
--- a/src/core/runtime.ts
+++ b/src/core/runtime.ts
@@ -2,6 +2,7 @@ import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import type { ChannelId, InboundEvent, ReplySession } from "./types.js";
+import { findBot, setBotForPeer } from "./routes.js";
import { KeyedQueue } from "./queue.js";
import { eventText } from "./types.js";
import { acceptsImages, type ModelClient, type ChatMessage } from "../llm/client.js";
@@ -206,10 +207,10 @@ export class BotRuntime {
if (opts.agent) opts.agent.onWake = (botId, convId) => void this.wake(botId, convId).catch((e) => log.warn("wake-up turn failed", { message: (e as Error).message }));
}
- /** 渠道登记怎么主动往它的会话里发消息(代理自己醒来的一轮用);botId 为 "*" 时对所有机器人有效 */
- registerReplier(botId: string, channel: ChannelId, fn: Replier | undefined): void {
- if (fn) this.repliers.set(`${botId}:${channel}`, fn);
- else this.repliers.delete(`${botId}:${channel}`);
+ /** 渠道登记怎么主动往它的会话里发消息(代理自己醒来的一轮用):按渠道账号;"*" 时对所有账号有效 */
+ registerReplier(account: string, channel: ChannelId, fn: Replier | undefined): void {
+ if (fn) this.repliers.set(`${account}:${channel}`, fn);
+ else this.repliers.delete(`${account}:${channel}`);
}
/** 应用退出前调用(App.stop):之后失败的回合留下重启标记,由下次启动告诉用户 */
@@ -276,6 +277,8 @@ export class BotRuntime {
const bot = store.getBot(ev.botId);
if (!bot) throw new Error(`unknown bot ${ev.botId}`);
const conv = store.ensureConversation(bot.id, ev.channel, ev.conversation.id, ev.sender.name || ev.sender.id, ev.conversation.kind === "group" ? "group" : "dm");
+ // 回复和之后的主动消息走这个账号
+ if (ev.account && conv.account !== ev.account) store.setConversationAccount(conv.id, ev.account);
const t: Inflight = { botId: bot.id, since: Date.now(), abort: new AbortController(), release: KeyedQueue.releaser() };
const link = () => t.abort.abort();
if (opts.signal?.aborted) link();
@@ -467,6 +470,9 @@ export class BotRuntime {
if (paired?.handled) return paired;
const text = eventText(ev);
const convId = `${ev.botId}:${ev.channel}:${ev.conversation.id}`;
+ // /bot:换这个会话和哪个机器人聊(渠道账号是全局的,所有机器人共用)。不碰模型,不进队列
+ const switching = ev.account ? /^\/bot(?:\s+(.+))?$/i.exec(text.trim()) : null;
+ if (switching && ev.account) return { handled: true, ack: this.switchBot(ev, ev.account, switching[1]) };
// /status、/help 只读、不碰模型和代理进程:不进会话队列,不会排在一个卡住或正在启动代理的回合后面
const cmd = text.trim().toLowerCase();
if (cmd === "/status" || cmd === "/help") {
@@ -530,7 +536,7 @@ export class BotRuntime {
const ps = a?.available ? pwshStatusLine(pwshProbe.snapshot()) : "";
const turn = a?.turnsInProgress.get(convId);
const busy = turn ? [busyLine(turn.since, turn.lastProgress, turn.activity.steps, !!a?.canSteer(convId))] : [];
- const who = this.opts.access ? [this.opts.access.policyLine(botId)] : [];
+ const who = this.opts.access ? [this.opts.access.policyLine(this.opts.store.getConversation(convId)?.account || botId)] : [];
// 这个会话有后台任务在进行时说一句(没有就不说)
const working = a?.tasks?.working(convId) ?? [];
const bg = working.length ? [t("runtime.backgroundTasks", { list: working.map((x) => t("runtime.backgroundTask", { title: x.title, stage: x.stage.label })).join(t("runtime.listSep")) })] : [];
@@ -552,7 +558,9 @@ export class BotRuntime {
cardAction(botId: string, value: Record<string, string>, by: string): { toast: string; ok: boolean } {
const agent = this.opts.agent;
const row = agent && value?.id ? this.opts.store.getApproval(String(value.id)) : undefined;
- if (!agent || !row || row.botId !== botId) return { toast: t("runtime.requestMissing"), ok: false };
+ // 卡片从渠道账号发回来:看这条请求所在的会话是不是走这个账号
+ const owner = row && (this.opts.store.getConversation(row.conversationId)?.account || row.botId);
+ if (!agent || !row || owner !== botId) return { toast: t("runtime.requestMissing"), ok: false };
if (row.status !== "pending" && value.amb === "question" && row.taskId) {
// 后台任务按默认回答先做完了、提问撤回了,卡片上的按钮还点得到:当作迟到的回答交给任务(同引用那条提问)
const opt = (questionsOf(row)[0]?.options ?? [])[Number(value.option) - 1]?.label;
@@ -773,7 +781,7 @@ export class BotRuntime {
} catch {
handle = undefined;
}
- const r = (this.repliers.get(`${botId}:${conv.channel}`) ?? this.repliers.get(`*:${conv.channel}`))?.(conv, handle, `wake:${wakeId}`);
+ const r = (this.repliers.get(`${conv.account || botId}:${conv.channel}`) ?? this.repliers.get(`*:${conv.channel}`))?.(conv, handle, `wake:${wakeId}`);
if (!r) log.warn("no way to reply in this conversation; the wake-up reply is only kept in its history", { bot: botId, conversationId: convId, channel: conv.channel });
const out: ReplySession = r?.out ?? { apply: async () => undefined };
const fl: Inflight = { botId, since: Date.now(), abort: new AbortController(), userStored: true };
@@ -842,6 +850,19 @@ export class BotRuntime {
}
/** 返回 null 表示不是已知命令,按普通消息处理。 */
+ private switchBot(ev: InboundEvent, account: string, wanted: string | undefined): string {
+ const { store } = this.opts;
+ if (!wanted?.trim()) {
+ const list = store.listBots().map((b, i) => `${i + 1}. ${b.name}${b.id === ev.botId ? t("runtime.botCurrent") : ""}`).join("\n");
+ return t("runtime.botList", { list });
+ }
+ const pick = findBot(store, wanted);
+ if (!pick) return t("runtime.botMissing", { name: wanted.trim().slice(0, 40) });
+ setBotForPeer(store, account, ev.channel, ev.conversation.id, pick.id);
+ log.info("conversation switched to another bot", { channel: ev.channel, bot: pick.id });
+ return t("runtime.botSwitched", { name: pick.name });
+ }
+
private async command(text: string, convId: string, convModel: string, botModel: string, botId: string): Promise<string | null> {
const [cmd, ...rest] = text.trim().split(/\s+/);
const arg = rest.join(" ");
diff --git a/src/core/types.ts b/src/core/types.ts
index cb348aa..08e5fd0 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -41,7 +41,10 @@ export interface InboundEvent {
/** 平台消息 ID,用于去重 */
id: string;
channel: ChannelId;
+ /** 回复这条消息的机器人(渠道按 core/routes.ts 选好) */
botId: string;
+ /** 消息从哪个全局渠道账号进来;网页没有 */
+ account?: string;
conversation: { kind: "dm" | "group"; id: string };
sender: { id: string; name?: string };
parts: Part[];
diff --git a/src/i18n/messages/app.ts b/src/i18n/messages/app.ts
index 87c86c7..16ec821 100644
--- a/src/i18n/messages/app.ts
+++ b/src/i18n/messages/app.ts
@@ -8,11 +8,13 @@ export const zh = {
// 第一次启动时建的机器人(按当时的语言)
default_bot_name: "我的助手",
default_bot_prompt: "你是一个乐于助人的中文助手,回答简洁准确。",
- feishu_failed: "机器人「{name}」飞书长连接启动失败:{message}",
- messenger_failed: "机器人「{name}」连不上 {channel},请在信息面板检查凭据:{message}",
- feishu_history_denied: "机器人「{name}」读不到飞书的历史消息,离线时发来的消息补不上。在飞书开放平台给应用开通 im:message.history:readonly 权限即可。",
- weixin_expired: "机器人「{name}」微信登录已过期,请在信息面板的「渠道」里重新扫码",
- weixin_connected: "机器人「{name}」微信已连接",
+ feishu_failed: "飞书账号「{name}」长连接启动失败:{message}",
+ messenger_failed: "{channel} 账号「{name}」连不上,请在 设置 › 连接 里检查凭据:{message}",
+ feishu_history_denied: "飞书账号「{name}」读不到飞书的历史消息,离线时发来的消息补不上。在飞书开放平台给应用开通 im:message.history:readonly 权限即可。",
+ weixin_expired: "微信账号「{name}」登录已过期,请在 设置 › 连接 里重新扫码",
+ weixin_connected: "微信账号「{name}」已连接",
+ weixin_account_name: "微信",
+ feishu_account_name: "飞书",
// 收到的消息里图片 / 文件 / 语音的占位(core/types.ts eventText)
media_image: "图片",
media_file: "文件",
@@ -34,11 +36,13 @@ export const en: Catalog<typeof zh> = {
magpie_failed: "magpie failed to start: {message}",
default_bot_name: "My Assistant",
default_bot_prompt: "You are a helpful assistant. Answer concisely and accurately.",
- feishu_failed: "Bot \"{name}\": Feishu long connection failed to start: {message}",
- messenger_failed: "Bot \"{name}\" can't connect to {channel}. Check its credentials in the info panel: {message}",
- feishu_history_denied: "Bot \"{name}\" can't read Feishu message history, so messages sent while it was offline can't be caught up. Grant the app the im:message.history:readonly scope in the Feishu Open Platform.",
- weixin_expired: "Bot \"{name}\": WeChat sign-in expired. Scan the QR code again under Channels in the info panel",
- weixin_connected: "Bot \"{name}\": WeChat connected",
+ feishu_failed: "Feishu account \"{name}\": long connection failed to start: {message}",
+ messenger_failed: "{channel} account \"{name}\" can't connect. Check its credentials in Settings > Connections: {message}",
+ feishu_history_denied: "Feishu account \"{name}\" can't read Feishu message history, so messages sent while it was offline can't be caught up. Grant the app the im:message.history:readonly scope in the Feishu Open Platform.",
+ weixin_expired: "WeChat account \"{name}\": sign-in expired. Scan the QR code again in Settings > Connections",
+ weixin_connected: "WeChat account \"{name}\" connected",
+ weixin_account_name: "WeChat",
+ feishu_account_name: "Feishu",
media_image: "Image",
media_file: "File",
media_video: "Video",
diff --git a/src/i18n/messages/runtime.ts b/src/i18n/messages/runtime.ts
index b652bc6..82393fb 100644
--- a/src/i18n/messages/runtime.ts
+++ b/src/i18n/messages/runtime.ts
@@ -8,12 +8,17 @@ export const zh = {
"/model <编号或模型名> — 切换当前会话的模型",
"/reset — 清空当前会话的上下文(代理模式下同时开启新的代理会话;长期记忆保留)",
"/new — 开始新的一段对话:旧对话归档并生成交接便条,长期记忆保留",
+ "/bot — 看有哪些机器人,/bot <编号或名字> — 换一个机器人聊(聊天软件里才有)",
"/status — 查看当前模型、代理状态和正在处理的消息走到了哪一步",
"/stop — 中止正在处理的消息(只停这个会话,机器人的其它会话照常进行)",
"/tasks — 列出这个会话的后台任务和规则",
"/stop <编号> — 停止 /tasks 里的一个后台任务或规则",
"/help — 显示本帮助",
].join("\n"),
+ botList: "可以聊的机器人:\n{list}\n\n发 /bot <编号或名字> 换一个。",
+ botCurrent: "(现在)",
+ botMissing: "没找到机器人「{name}」。发 /bot 看看有哪些。",
+ botSwitched: "好的,现在是 {name} 在和你聊。",
noModels: "没有可用模型:请先连接 Modelflare(设置 → Modelflare)",
startingNote: "(代理还在启动,这条消息先由模型直接回答;启动完成后会自动用回代理。)",
emptyReply: "(模型没有返回内容)",
@@ -109,12 +114,17 @@ export const en: Catalog<typeof zh> = {
"/model <number or name> — switch the model for this conversation",
"/reset — clear this conversation's context (in agent mode, also starts a new agent session; long-term memory is kept)",
"/new — start a new conversation: the old one is archived with a handoff note; long-term memory is kept",
+ "/bot — list the bots; /bot <number or name> — talk to a different bot (in chat apps only)",
"/status — show the current model, the agent's state and how far the message in progress has got",
"/stop — stop the message in progress (only this conversation; the bot's other conversations carry on)",
"/tasks — list this conversation's background tasks and rules",
"/stop <number> — stop a background task or rule listed by /tasks",
"/help — show this help",
].join("\n"),
+ botList: "Bots you can talk to:\n{list}\n\nSend /bot <number or name> to switch.",
+ botCurrent: " (now)",
+ botMissing: "There's no bot \"{name}\". Send /bot to see them.",
+ botSwitched: "OK, you're now talking to {name}.",
noModels: "No models available: connect Modelflare first (Settings → Modelflare)",
startingNote: "(The agent is still starting, so the model answered this message directly; the agent takes over automatically once it's ready.)",
emptyReply: "(The model returned nothing)",
diff --git a/src/store/db.ts b/src/store/db.ts
index f82bfc6..97ae77f 100644
--- a/src/store/db.ts
+++ b/src/store/db.ts
@@ -32,10 +32,26 @@ export interface Conversation {
model: string;
/** dm 或 group(群聊使用群记忆) */
kind: "dm" | "group";
+ /** 最近一条消息从哪个渠道账号进来,回复和主动消息走它;空 = 账号 key 就是机器人 id(升级前的会话) */
+ account: string;
createdAt: number;
updatedAt: number;
}
+/** 全局渠道账号(设置 › 连接),所有机器人共用;见 core/routes.ts */
+export interface ChannelAccount {
+ key: string;
+ channel: string;
+ /** 别名:同一个渠道里不重复 */
+ label: string;
+ /** 没用 /bot 选过时,消息交给哪个机器人 */
+ defaultBot: string;
+ enabled: boolean;
+ /** 飞书的 appId / appSecret;微信和其他平台的凭据在各自的表里 */
+ credentials: Record<string, string>;
+ createdAt: number;
+}
+
export interface Message {
id: number;
conversationId: string;
@@ -189,6 +205,8 @@ export interface OutboxRow {
id: string;
seq: number;
botId: string;
+ /** 走哪个渠道账号;空 = 账号 key 就是 botId(升级前的消息) */
+ account: string;
channel: string;
/** 排序单位:同一会话按 seq 依次发送 */
conversationId: string;
@@ -463,6 +481,10 @@ CREATE TABLE IF NOT EXISTS weixin_peers (
bot_id TEXT NOT NULL, user_id TEXT NOT NULL, context_token TEXT NOT NULL DEFAULT '',
quota_remaining INTEGER NOT NULL DEFAULT 0, window_started_at INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (bot_id, user_id));
+CREATE TABLE IF NOT EXISTS channel_accounts (
+ key TEXT NOT NULL, channel TEXT NOT NULL, label TEXT NOT NULL DEFAULT '', default_bot TEXT NOT NULL DEFAULT '',
+ enabled INTEGER NOT NULL DEFAULT 1, credentials TEXT NOT NULL DEFAULT '{}', created_at INTEGER NOT NULL,
+ PRIMARY KEY (key, channel));
CREATE TABLE IF NOT EXISTS messenger_accounts (
bot_id TEXT NOT NULL, channel TEXT NOT NULL, credentials TEXT NOT NULL, name TEXT NOT NULL DEFAULT '',
updated_at INTEGER NOT NULL, PRIMARY KEY (bot_id, channel));
@@ -539,6 +561,9 @@ CREATE INDEX IF NOT EXISTS run_inputs_run ON run_inputs(run_id, taken_at);
const COLUMNS: Array<[string, string, string]> = [
["bots", "settings", "TEXT NOT NULL DEFAULT '{}'"],
["conversations", "kind", "TEXT NOT NULL DEFAULT 'dm'"],
+ // 全局渠道账号(core/routes.ts)
+ ["conversations", "account", "TEXT NOT NULL DEFAULT ''"],
+ ["outbox", "account", "TEXT NOT NULL DEFAULT ''"],
// 代理回合的活动记录(JSON 数组,见 agent/activity.ts);只在助手消息上
["messages", "activity", "TEXT NOT NULL DEFAULT ''"],
// 模型在回合中间说的话、交付的文件(JSON 字符串数组);只在助手消息上
@@ -703,11 +728,8 @@ export class Store {
for (const c of convs) this.db.prepare("DELETE FROM messages WHERE conversation_id = ?").run(String(c.id));
this.db.prepare("DELETE FROM agent_segments WHERE conversation_id IN (SELECT id FROM conversations WHERE bot_id = ?)").run(id);
this.db.prepare("DELETE FROM conversations WHERE bot_id = ?").run(id);
- this.db.prepare("DELETE FROM weixin_accounts WHERE bot_id = ?").run(id);
- this.db.prepare("DELETE FROM weixin_peers WHERE bot_id = ?").run(id);
- this.db.prepare("DELETE FROM messenger_accounts WHERE bot_id = ?").run(id);
+ // 渠道账号(登录态、名单)是全局的,不跟着机器人删;这个机器人原来的账号改由别的机器人回复(core/routes.ts)
this.db.prepare("DELETE FROM agent_sessions WHERE bot_id = ?").run(id);
- this.db.prepare("DELETE FROM access WHERE bot_id = ?").run(id);
this.db.prepare("DELETE FROM outbox WHERE bot_id = ?").run(id);
this.db.prepare("DELETE FROM run_inputs WHERE task_id IN (SELECT id FROM tasks WHERE bot_id = ?)").run(id);
this.db.prepare("DELETE FROM run_inputs WHERE rule_id IN (SELECT id FROM rules WHERE bot_id = ?)").run(id);
@@ -720,6 +742,7 @@ export class Store {
// ---------- conversations ----------
private toConv(r: Row): Conversation {
return {
+ account: String(r.account ?? ""),
id: String(r.id),
botId: String(r.bot_id),
channel: String(r.channel),
@@ -746,6 +769,50 @@ export class Store {
.run(id, botId, channel, peerId, title, kind, now, now);
return this.getConversation(id)!;
}
+ setConversationAccount(id: string, account: string): void {
+ this.db.prepare("UPDATE conversations SET account = ? WHERE id = ?").run(account, id);
+ }
+ /** 这个渠道账号上的会话(可能属于不同的机器人);account 为空的是升级前的会话,账号 key 就是机器人 id */
+ listAccountConversations(account: string, channel: string): Conversation[] {
+ const rows = this.db.prepare("SELECT * FROM conversations WHERE channel = ? AND (account = ? OR (account = '' AND bot_id = ?)) ORDER BY updated_at DESC").all(channel, account, account) as Row[];
+ return rows.map((r) => this.toConv(r));
+ }
+
+ private toChannelAccount(r: Row): ChannelAccount {
+ let credentials: Record<string, string> = {};
+ try {
+ credentials = JSON.parse(String(r.credentials || "{}"));
+ } catch {
+ credentials = {};
+ }
+ return { key: String(r.key), channel: String(r.channel), label: String(r.label), defaultBot: String(r.default_bot), enabled: Number(r.enabled) === 1, credentials, createdAt: Number(r.created_at) };
+ }
+ listChannelAccounts(channel?: string): ChannelAccount[] {
+ const rows = (channel
+ ? this.db.prepare("SELECT * FROM channel_accounts WHERE channel = ? ORDER BY created_at, rowid").all(channel)
+ : this.db.prepare("SELECT * FROM channel_accounts ORDER BY created_at, rowid").all()) as Row[];
+ return rows.map((r) => this.toChannelAccount(r));
+ }
+ getChannelAccount(key: string, channel: string): ChannelAccount | undefined {
+ const r = this.db.prepare("SELECT * FROM channel_accounts WHERE key = ? AND channel = ?").get(key, channel) as Row | undefined;
+ return r ? this.toChannelAccount(r) : undefined;
+ }
+ saveChannelAccount(a: ChannelAccount): void {
+ this.db
+ .prepare(
+ `INSERT INTO channel_accounts(key, channel, label, default_bot, enabled, credentials, created_at) VALUES(?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(key, channel) DO UPDATE SET label = excluded.label, default_bot = excluded.default_bot, enabled = excluded.enabled, credentials = excluded.credentials`,
+ )
+ .run(a.key, a.channel, a.label, a.defaultBot, a.enabled ? 1 : 0, JSON.stringify(a.credentials), a.createdAt);
+ }
+ deleteChannelAccount(key: string, channel: string): void {
+ this.db.prepare("DELETE FROM channel_accounts WHERE key = ? AND channel = ?").run(key, channel);
+ }
+ /** 有微信联系人的账号(每个账号一份,续期提醒按它走) */
+ weixinPeerAccounts(): string[] {
+ return (this.db.prepare("SELECT DISTINCT bot_id FROM weixin_peers").all() as Row[]).map((r) => String(r.bot_id));
+ }
+
getConversation(id: string): Conversation | undefined {
const r = this.db.prepare("SELECT * FROM conversations WHERE id = ?").get(id) as Row | undefined;
return r ? this.toConv(r) : undefined;
@@ -1133,22 +1200,23 @@ export class Store {
ref: String(r.ref ?? ""),
reason: String(r.reason ?? ""),
mergedInto: String(r.merged_into ?? ""),
+ account: String(r.account ?? ""),
seenAt: Number(r.seen_at ?? 0),
};
}
/** 同一 id 只写一次;返回是否是新写入的 */
insertOutbox(
o: Pick<OutboxRow, "id" | "botId" | "channel" | "conversationId" | "peerId" | "kind" | "body" | "replyTo" | "due" | "createdAt" | "expiresAt"> &
- Partial<Pick<OutboxRow, "status" | "purpose" | "subject" | "ref" | "reason">>,
+ Partial<Pick<OutboxRow, "status" | "purpose" | "subject" | "ref" | "reason" | "account">>,
): boolean {
const res = this.db
.prepare(
- `INSERT OR IGNORE INTO outbox(id, seq, bot_id, channel, conversation_id, peer_id, kind, body, reply_to, due, created_at, updated_at, expires_at, status, purpose, subject, ref, reason)
- VALUES(?, (SELECT IFNULL(MAX(seq), 0) + 1 FROM outbox), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ `INSERT OR IGNORE INTO outbox(id, seq, bot_id, channel, conversation_id, peer_id, kind, body, reply_to, due, created_at, updated_at, expires_at, status, purpose, subject, ref, reason, account)
+ VALUES(?, (SELECT IFNULL(MAX(seq), 0) + 1 FROM outbox), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
o.id, o.botId, o.channel, o.conversationId, o.peerId, o.kind, JSON.stringify(o.body), o.replyTo, o.due, o.createdAt, o.createdAt, o.expiresAt,
- o.status ?? "pending", o.purpose ?? "", o.subject ?? "", o.ref ?? "", o.reason ?? "",
+ o.status ?? "pending", o.purpose ?? "", o.subject ?? "", o.ref ?? "", o.reason ?? "", o.account ?? "",
);
return Number(res.changes) > 0;
}
diff --git a/src/web/server.ts b/src/web/server.ts
index 9849f74..7b40fe0 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -5,10 +5,10 @@ import crypto from "node:crypto";
import { createRequire } from "node:module";
import { appVersion, type App } from "../app.js";
import type { InboundEvent, OutboundOp, ReplySession } from "../core/types.js";
-import { MESSENGERS, eventText, isMessenger, isPushChannel } from "../core/types.js";
+import { eventText, isMessenger, isPushChannel } from "../core/types.js";
import type { PlatformError } from "../channels/messenger/transport.js";
import { findAppRoot } from "../magpie/supervisor.js";
-import { logFilePath, logger, mask, readLogTail, registerSecret } from "../log.js";
+import { logFilePath, logger, readLogTail, registerSecret } from "../log.js";
import { diagnosticsReport, safeStatus, testAgent, testModel } from "../diagnostics.js";
import { ZOOMS, normalizeLowBalance, saveConfigFile } from "../config.js";
import { ApiError } from "../account/client.js";
@@ -118,9 +118,6 @@ function publicBot(b: NonNullable<ReturnType<App["store"]["getBot"]>>) {
name: b.name,
systemPrompt: b.systemPrompt,
defaultModel: b.defaultModel,
- feishuAppId: b.feishuAppId,
- feishuAppSecretMasked: mask(b.feishuAppSecret),
- weixinEnabled: b.weixinEnabled,
settings: b.settings,
createdAt: b.createdAt,
updatedAt: b.updatedAt,
@@ -493,6 +490,117 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
return send(res, 200, { ...app.agent.status(), busy: [...new Set([...live.bots(), ...app.runtime.busyBots()])], background: app.tasks.background(), attention: items.length, needs: app.attention.byBot(items) });
}
// —— 需要你(3b):所有机器人里在等人的事,和对它们的操作 ——
+ // 全局渠道账号(设置 › 连接):所有机器人共用,消息交给哪个机器人见 core/routes.ts。key 只是账号的命名空间
+ if (seg[0] === "channel-accounts") {
+ if (seg.length === 1 && m === "GET") return send(res, 200, { accounts: app.channelAccounts() });
+ if (p === "/channel-accounts/new-key" && m === "POST") return send(res, 200, { key: `acct_${crypto.randomBytes(6).toString("hex")}` });
+ const id = decodeURIComponent(seg[1] ?? "");
+ if (!/^[\w-]{1,80}$/.test(id)) throw new HttpError(404, "not found");
+ const sub = seg.slice(2).join("/");
+ if (sub === "channels" && m === "GET") return send(res, 200, app.channelStatus(id));
+ if (seg.length === 4 && seg[3] === "settings" && m === "PUT") {
+ const b = await readJson(req);
+ const r = await app.updateChannelAccount(id, seg[2], {
+ ...(b.label !== undefined ? { label: String(b.label) } : {}),
+ ...(b.defaultBot !== undefined ? { defaultBot: String(b.defaultBot) } : {}),
+ ...(b.enabled !== undefined ? { enabled: !!b.enabled } : {}),
+ });
+ if (r === "taken") throw new HttpError(400, tr("web.accountNameTaken"));
+ if (r === "invalid") throw new HttpError(400, tr("web.badAccountName"));
+ if (r !== "ok") throw new HttpError(404, tr("web.recordNotFound"));
+ return send(res, 200, { accounts: app.channelAccounts() });
+ }
+ if (sub === "access" && m === "GET") {
+ const v = app.access.view(id);
+ const owner = (ch: AccessChannel) => {
+ const o = v.owners[ch];
+ 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), via: o.via };
+ };
+ return send(res, 200, {
+ policy: v.policy,
+ owners: Object.fromEntries(ACCESS_CHANNELS.map((ch) => [ch, owner(ch)])),
+ requests: v.requests.map(publicAccess),
+ entries: v.entries.filter((e) => e.status !== "owner").map(publicAccess),
+ });
+ }
+ if (seg[2] === "access" && seg.length === 5 && m === "POST") {
+ const entry = app.store.getAccessById(decodeURIComponent(seg[3]));
+ if (!entry || entry.botId !== id) throw new HttpError(404, tr("web.recordNotFound"));
+ if (seg[4] === "approve" || seg[4] === "deny") {
+ const r = app.access.decide(entry.id, seg[4] === "approve", "web");
+ if (!r) throw new HttpError(409, tr("web.requestAlreadyHandled"));
+ return send(res, 200, { entry: publicAccess(r) });
+ }
+ }
+ // 更换主人:清掉"第一个发消息"的主人,下一个发单聊消息的人成为主人(扫码登录的微信要重新扫码)
+ if (seg[2] === "access" && seg[3] === "owner" && seg.length === 5 && m === "DELETE") {
+ const ch = seg[4];
+ if (!isPushChannel(ch)) throw new HttpError(404, tr("web.noSuchChannel"));
+ if (app.access.owner(id, ch)?.via === "login") throw new HttpError(409, tr("web.weixinOwnerRescan"));
+ 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]));
+ if (!entry || entry.botId !== id) throw new HttpError(404, tr("web.recordNotFound"));
+ app.access.remove(entry.id);
+ return send(res, 200, { ok: true });
+ }
+ if (sub === "feishu" && m === "PUT") {
+ const b = await readJson(req);
+ await app.connectFeishu(id, String(b.appId ?? "").trim(), String(b.appSecret ?? "").trim());
+ return send(res, 200, app.channelStatus(id));
+ }
+ if (sub === "feishu" && m === "DELETE") {
+ await app.removeChannelAccount(id, "feishu");
+ return send(res, 200, app.channelStatus(id));
+ }
+ if (isMessenger(sub) && m === "PUT") {
+ try {
+ await app.connectMessenger(id, sub, await readJson(req));
+ } catch (e) {
+ if ((e as PlatformError).rejected) throw new HttpError(400, (e as Error).message);
+ throw e;
+ }
+ return send(res, 200, app.channelStatus(id));
+ }
+ if (isMessenger(sub) && m === "DELETE") {
+ await app.removeChannelAccount(id, sub);
+ return send(res, 200, app.channelStatus(id));
+ }
+ if (sub === "weixin" && m === "PUT") {
+ const b = await readJson(req);
+ await app.updateChannelAccount(id, "weixin", { enabled: !!b.enabled });
+ return send(res, 200, app.channelStatus(id));
+ }
+ if (sub === "weixin/login" && m === "POST") {
+ const login = app.startWeixinLogin(id);
+ // 等待二维码就绪(最多 10 秒)
+ const t0 = Date.now();
+ while (login.snapshot.state === "idle" || login.snapshot.state === "fetching") {
+ if (Date.now() - t0 > 10_000) break;
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ return send(res, 200, login.snapshot);
+ }
+ if (sub === "weixin/login" && m === "GET") return send(res, 200, app.channels.get(id)?.weixinLogin?.snapshot ?? { state: "idle" });
+ if (sub === "weixin/verify" && m === "POST") {
+ const b = await readJson(req);
+ app.channels.get(id)?.weixinLogin?.submitVerifyCode(String(b.code ?? ""));
+ return send(res, 200, { ok: true });
+ }
+ if (sub === "weixin/cancel" && m === "POST") {
+ app.channels.get(id)?.weixinLogin?.cancel();
+ return send(res, 200, { ok: true });
+ }
+ if (sub === "weixin/logout" && m === "POST") {
+ await app.removeChannelAccount(id, "weixin");
+ return send(res, 200, app.channelStatus(id));
+ }
+ throw new HttpError(405, "method not allowed");
+ }
// 已授权账号(设置 › 连接):全局一份,所有机器人共用。令牌不出现在任何回复里
if (seg[0] === "connections") {
const c = app.connections;
@@ -790,7 +898,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
const derived = deriveGuide({
conversations: app.store.listConversations(),
bots,
- channelBound: (id) => !!app.store.getWeixinAccount(id) || MESSENGERS.some((c) => !!app.store.getMessengerAccount(id, c)),
+ channelBound: () => app.store.listChannelAccounts().length > 0,
// 机器人自己的记忆,或所有机器人共享的团队记忆,有一条就算记下过
memoryCount: (id) =>
[{ kind: "bot" as const, id }, { kind: "team" as const, id: "" }].reduce((n, s) => n + app.agent.memory.entries(s).length + app.agent.memory.topics(s).length, 0),
@@ -914,7 +1022,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
const bot = id ? app.store.getBot(id) : undefined;
if (!bot) throw new HttpError(404, t("web.botNotFound"));
if (seg.length === 2) {
- if (m === "GET") return send(res, 200, { bot: publicBot(bot), channels: app.channelStatus(id) });
+ if (m === "GET") return send(res, 200, { bot: publicBot(bot) });
if (m === "PUT") {
const b = await readJson(req);
const next = app.store.updateBot(id, {
@@ -930,7 +1038,6 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
}
}
const sub = seg.slice(2).join("/");
- if (sub === "channels" && m === "GET") return send(res, 200, app.channelStatus(id));
if (sub === "settings" && m === "GET") return send(res, 200, { settings: bot.settings, computerUse: app.agent.computerUse(id) });
if (sub === "settings" && m === "PUT") {
const b = await readJson(req);
@@ -995,103 +1102,6 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
}
}
// —— 谁能使用:主人、允许名单、使用请求 ——
- if (sub === "access" && m === "GET") {
- const v = app.access.view(id);
- const owner = (ch: AccessChannel) => {
- const o = v.owners[ch];
- 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), via: o.via };
- };
- return send(res, 200, {
- policy: v.policy,
- owners: Object.fromEntries(ACCESS_CHANNELS.map((ch) => [ch, owner(ch)])),
- requests: v.requests.map(publicAccess),
- entries: v.entries.filter((e) => e.status !== "owner").map(publicAccess),
- });
- }
- if (seg[2] === "access" && seg.length === 5 && m === "POST") {
- const entry = app.store.getAccessById(decodeURIComponent(seg[3]));
- if (!entry || entry.botId !== id) throw new HttpError(404, tr("web.recordNotFound"));
- if (seg[4] === "approve" || seg[4] === "deny") {
- const r = app.access.decide(entry.id, seg[4] === "approve", "web");
- if (!r) throw new HttpError(409, tr("web.requestAlreadyHandled"));
- return send(res, 200, { entry: publicAccess(r) });
- }
- }
- // 更换主人:清掉"第一个发消息"的主人,下一个发单聊消息的人成为主人(扫码登录的微信要重新扫码)
- if (seg[2] === "access" && seg[3] === "owner" && seg.length === 5 && m === "DELETE") {
- const ch = seg[4];
- if (!isPushChannel(ch)) throw new HttpError(404, tr("web.noSuchChannel"));
- if (app.access.owner(id, ch)?.via === "login") throw new HttpError(409, tr("web.weixinOwnerRescan"));
- 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]));
- if (!entry || entry.botId !== id) throw new HttpError(404, tr("web.recordNotFound"));
- app.access.remove(entry.id);
- 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));
- }
- if (isMessenger(sub) && m === "PUT") {
- try {
- await app.connectMessenger(id, sub, await readJson(req));
- } catch (e) {
- if ((e as PlatformError).rejected) throw new HttpError(400, (e as Error).message);
- throw e;
- }
- return send(res, 200, app.channelStatus(id));
- }
- if (isMessenger(sub) && m === "DELETE") {
- await app.disconnectMessenger(id, sub);
- return send(res, 200, app.channelStatus(id));
- }
- if (sub === "weixin" && m === "PUT") {
- const b = await readJson(req);
- app.store.updateBot(id, { weixinEnabled: !!b.enabled });
- await app.restartBot(id);
- return send(res, 200, app.channelStatus(id));
- }
- if (sub === "weixin/login" && m === "POST") {
- const login = app.startWeixinLogin(id);
- // 等待二维码就绪(最多 10 秒)
- const t0 = Date.now();
- while (login.snapshot.state === "idle" || login.snapshot.state === "fetching") {
- if (Date.now() - t0 > 10_000) break;
- await new Promise((r) => setTimeout(r, 50));
- }
- return send(res, 200, login.snapshot);
- }
- if (sub === "weixin/login" && m === "GET") return send(res, 200, app.channels.get(id)?.weixinLogin?.snapshot ?? { state: "idle" });
- if (sub === "weixin/verify" && m === "POST") {
- const b = await readJson(req);
- app.channels.get(id)?.weixinLogin?.submitVerifyCode(String(b.code ?? ""));
- return send(res, 200, { ok: true });
- }
- if (sub === "weixin/cancel" && m === "POST") {
- app.channels.get(id)?.weixinLogin?.cancel();
- return send(res, 200, { ok: true });
- }
- if (sub === "weixin/logout" && m === "POST") {
- await app.weixinLogout(id);
- return send(res, 200, app.channelStatus(id));
- }
if (sub === "chat" && m === "GET") {
const conv = app.store.getConversation(consoleConvId(id));
// 进行中的消息由 live 显示(用户消息、到目前为止的回复与步骤);它开始之后存下的消息先不列,免得重复
diff --git a/test/access.e2e.test.ts b/test/access.e2e.test.ts
index c04a617..3f5bf11 100644
--- a/test/access.e2e.test.ts
+++ b/test/access.e2e.test.ts
@@ -55,8 +55,8 @@ beforeAll(async () => {
delete process.env.FEISHU_APP_SECRET;
base = app.web!.url.replace(/\/$/, "");
// 扫码登录:扫码的是 [email protected]
- await api("/bots/default/weixin/login", { method: "POST", body: {} });
- await until(async () => (await api("/bots/default/channels")).json.weixin.state === "connected", 8000);
+ await api("/channel-accounts/default/weixin/login", { method: "POST", body: {} });
+ await until(async () => (await api("/channel-accounts/default/channels")).json.weixin.state === "connected", 8000);
});
afterAll(async () => {
@@ -70,7 +70,7 @@ describe("微信:只有主人和允许的人", () => {
ilink.push(OWNER, "你好");
await until(() => to(OWNER).length >= 1, 8000);
expect(to(OWNER)[0]).toBe("[mock-a] 你说:你好");
- const acc = await api("/bots/default/access");
+ const acc = await api("/channel-accounts/default/access");
expect(acc.json.owners.weixin).toMatchObject({ via: "login" });
expect(acc.json.policy).toBe("owner-allowlist");
});
@@ -85,11 +85,11 @@ describe("微信:只有主人和允许的人", () => {
const notice = to(OWNER).at(-1)!;
expect(notice).toContain("我是张三");
code = /同意 (\d{4})/.exec(notice)![1];
- const acc = await api("/bots/default/access");
+ const acc = await api("/channel-accounts/default/access");
expect(acc.json.requests).toEqual([expect.objectContaining({ channel: "weixin", code, text: "我是张三,想借用一下", status: "pending", requests: 1 })]);
// 再发:不再回复、不再通知主人,模型一直没被调用
ilink.push("[email protected]", "在吗?");
- await until(async () => (await api("/bots/default/access")).json.requests[0]?.requests === 2, 8000);
+ await until(async () => (await api("/channel-accounts/default/access")).json.requests[0]?.requests === 2, 8000);
await app.channels.get("default")!.weixin!.idle();
expect(to("[email protected]")).toHaveLength(1);
expect(to(OWNER).at(-1)).toBe(notice);
@@ -106,7 +106,7 @@ describe("微信:只有主人和允许的人", () => {
ilink.push("[email protected]", "现在呢");
await until(() => to("[email protected]").length >= 3, 8000);
expect(to("[email protected]")[2]).toBe("[mock-a] 你说:现在呢");
- const acc = await api("/bots/default/access");
+ const acc = await api("/channel-accounts/default/access");
expect(acc.json.requests).toEqual([]);
expect(acc.json.entries).toEqual(expect.arrayContaining([expect.objectContaining({ channel: "weixin", status: "allowed", source: "request" })]));
});
@@ -114,13 +114,13 @@ describe("微信:只有主人和允许的人", () => {
it("在应用里拒绝:对方之后发什么都不回;在应用里批准、再移除:又被拦下", async () => {
ilink.push("[email protected]", "hi");
ilink.push("[email protected]", "hello");
- await until(async () => (await api("/bots/default/access")).json.requests.length === 2, 8000);
- const reqs = (await api("/bots/default/access")).json.requests as any[];
+ await until(async () => (await api("/channel-accounts/default/access")).json.requests.length === 2, 8000);
+ const reqs = (await api("/channel-accounts/default/access")).json.requests as any[];
const li = reqs.find((r) => r.text === "hi");
const wang = reqs.find((r) => r.text === "hello");
- expect((await api(`/bots/default/access/${li.id}/deny`, { method: "POST", body: {} })).json.entry.status).toBe("denied");
- expect((await api(`/bots/default/access/${wang.id}/approve`, { method: "POST", body: {} })).json.entry.status).toBe("allowed");
- expect((await api(`/bots/default/access/${wang.id}/approve`, { method: "POST", body: {} })).status).toBe(409);
+ expect((await api(`/channel-accounts/default/access/${li.id}/deny`, { method: "POST", body: {} })).json.entry.status).toBe("denied");
+ expect((await api(`/channel-accounts/default/access/${wang.id}/approve`, { method: "POST", body: {} })).json.entry.status).toBe("allowed");
+ expect((await api(`/channel-accounts/default/access/${wang.id}/approve`, { method: "POST", body: {} })).status).toBe(409);
await until(() => to("[email protected]").length >= 2, 8000);
expect(to("[email protected]")).toEqual([refusalText(), approvedText()]);
@@ -132,9 +132,9 @@ describe("微信:只有主人和允许的人", () => {
expect(to("[email protected]")).toEqual([refusalText()]);
expect(llm.calls.length).toBe(calls + 1);
- expect((await api(`/bots/default/access/${wang.id}`, { method: "DELETE" })).status).toBe(200);
+ expect((await api(`/channel-accounts/default/access/${wang.id}`, { method: "DELETE" })).status).toBe(200);
ilink.push("[email protected]", "还能用吗");
- await until(async () => (await api("/bots/default/access")).json.requests.length === 1, 8000);
+ await until(async () => (await api("/channel-accounts/default/access")).json.requests.length === 1, 8000);
await app.channels.get("default")!.weixin!.idle();
expect(to("[email protected]")).toHaveLength(4);
expect(to("[email protected]")[3]).toBe(refusalText());
@@ -148,7 +148,7 @@ describe("微信:只有主人和允许的人", () => {
});
it("升级:升级前已在对话的人自动在允许名单里,能继续用,可以移除", async () => {
- const acc = await api("/bots/default/access");
+ const acc = await api("/channel-accounts/default/access");
const old = acc.json.entries.filter((e: any) => e.source === "migration");
expect(old.map((e: any) => e.channel).sort()).toEqual(["feishu", "weixin"]);
ilink.push("[email protected]", "我还能用吗");
@@ -162,13 +162,13 @@ describe("飞书:第一个发消息的人成为主人", () => {
// 模拟过了一小时:上面的请求通知不占这里的限额
app.store.db.prepare("UPDATE access SET notified_at = 0").run();
const ch = app.channels.get("default")!.feishu!;
- expect((await api("/bots/default/access")).json.owners.feishu).toBeNull();
+ expect((await api("/channel-accounts/default/access")).json.owners.feishu).toBeNull();
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.texts.length).toBe(texts);
- const acc = (await api("/bots/default/access")).json;
+ const acc = (await api("/channel-accounts/default/access")).json;
expect(acc.owners.feishu).toEqual({ via: "first-message", peer: "oc_boss", name: "ou_boss" });
expect(acc.requests.filter((r: any) => r.channel === "feishu")).toEqual([]);
@@ -193,13 +193,13 @@ describe("飞书:第一个发消息的人成为主人", () => {
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();
+ expect((await api("/channel-accounts/default/access/owner/weixin", { method: "DELETE" })).status).toBe(409);
+ expect((await api("/channel-accounts/default/access/owner/feishu", { method: "DELETE" })).status).toBe(200);
+ expect((await api("/channel-accounts/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" });
+ expect((await api("/channel-accounts/default/access")).json.owners.feishu).toMatchObject({ via: "first-message", peer: "oc_me" });
// 原来的主人要重新申请;被允许的同事照常能用
feishu.onMessage!(feishuEvent("我还是主人吗", { chatId: "oc_boss", senderOpenId: "ou_boss" }));
await ch.idle();
diff --git a/test/channel-accounts.e2e.test.ts b/test/channel-accounts.e2e.test.ts
new file mode 100644
index 0000000..3fcbd8c
--- /dev/null
+++ b/test/channel-accounts.e2e.test.ts
@@ -0,0 +1,279 @@
+/**
+ * 全局渠道账号端到端:真实 App/Web(外部模型端点模式)+ 假传输层。
+ * 一个账号所有机器人共用,发一次 /bot 就切换并记住;同一个渠道可以加多个账号;别名;名单跟着账号;删机器人不影响账号;升级时老数据不用搬。
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { botPrompt, botTeam } from "../src/agent/prompts/index.js";
+import { App } from "../src/app.js";
+import { loadConfig } from "../src/config.js";
+import { botForPeer, defaultBotFor, findBot, setBotForPeer } from "../src/core/routes.js";
+import { Store } from "../src/store/db.js";
+import { FakeFeishu, FakeMessenger, messengerEvent, mockOpenAI } from "./helpers.js";
+
+let llm: Awaited<ReturnType<typeof mockOpenAI>>;
+let app: App;
+let base: string;
+/** 账号 key → 假 Telegram(检查凭据和真正连上用的是两个对象,留最后建的) */
+const fakes = new Map<string, FakeMessenger>();
+let secondBot = "";
+
+async function api(p: string, init: { method?: string; body?: unknown } = {}) {
+ const res = await fetch(base + "/amb/api" + p, {
+ method: init.method ?? "GET",
+ headers: init.body !== undefined ? { "content-type": "application/json" } : {},
+ body: init.body !== undefined ? JSON.stringify(init.body) : undefined,
+ });
+ return { status: res.status, json: (await res.json().catch(() => ({}))) as any };
+}
+const say = async (key: string, chatId: string, text: string) => {
+ fakes.get(key)!.onMessage!(messengerEvent(text, { chatId, senderId: chatId, senderName: chatId }));
+ await app.channels.get(key)!.messengers!.telegram!.idle();
+};
+const shown = (key: string, chatId: string) => fakes.get(key)!.lastShown(chatId);
+const account = async (key: string) => (await api("/channel-accounts")).json.accounts.find((a: any) => a.key === key);
+
+beforeAll(async () => {
+ llm = await mockOpenAI({ key: "gw-key" });
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-channel-accounts-"));
+ const config = loadConfig({ dataDir, env: { AMB_MAGPIE_BASE_URL: llm.url + "/v1", AMB_MAGPIE_API_KEY: "gw-key", AMB_UI_PORT: "0", AMB_AGENT: "off" } });
+ app = new App(config, {
+ printQrToTerminal: false,
+ feishuTransport: () => new FakeFeishu(),
+ messengerTransport: (id, key) => {
+ const f = new FakeMessenger(id);
+ fakes.set(key, f);
+ return f;
+ },
+ });
+ await app.start();
+ base = app.web!.url.replace(/\/$/, "");
+ await api("/bots/default", { method: "PUT", body: { defaultModel: "mock-a" } });
+ const second = await api("/bots", { method: "POST", body: { name: "阿紫", defaultModel: "mock-b" } });
+ secondBot = second.json.bot.id;
+});
+
+afterAll(async () => {
+ await app?.stop();
+ await llm?.close();
+});
+
+describe("一个账号,所有机器人共用", () => {
+ it("新账号:要一个 key,连上才真的存;默认由第一个机器人回复", async () => {
+ const { key } = (await api("/channel-accounts/new-key", { method: "POST", body: {} })).json;
+ expect(key).toMatch(/^acct_/);
+ expect(await account(key)).toBeUndefined();
+ expect((await api(`/channel-accounts/${key}/telegram`, { method: "PUT", body: { token: "1:SECRET-TOKEN-VALUE" } })).status).toBe(200);
+ const a = await account(key);
+ expect(a).toMatchObject({ channel: "telegram", number: 1, defaultBot: "default", enabled: true });
+ expect(JSON.stringify((await api("/channel-accounts")).json)).not.toContain("SECRET-TOKEN-VALUE");
+ await say(key, "boss", "你好");
+ expect(shown(key, "boss")).toBe("[mock-a] 你说:你好");
+ });
+
+ it("/bot 列出所有机器人,标出现在是哪个,不碰模型", async () => {
+ const key = (await api("/channel-accounts")).json.accounts[0].key;
+ const before = llm.calls.length;
+ await say(key, "boss", "/bot");
+ const text = shown(key, "boss")!;
+ expect(text).toMatch(/1\. .*(现在)/);
+ expect(text).toContain("2. 阿紫");
+ expect(llm.calls.length).toBe(before);
+ });
+
+ it("发一次 /bot 名字:切换并记住,之后不用每句都带", async () => {
+ const key = (await api("/channel-accounts")).json.accounts[0].key;
+ await say(key, "boss", "/bot 阿紫");
+ expect(shown(key, "boss")).toContain("阿紫");
+ await say(key, "boss", "第一句");
+ expect(shown(key, "boss")).toBe("[mock-b] 你说:第一句");
+ await say(key, "boss", "第二句");
+ expect(shown(key, "boss")).toBe("[mock-b] 你说:第二句");
+ // 会话归新机器人,记着走哪个账号
+ const conv = app.store.getConversation(`${secondBot}:telegram:boss`)!;
+ expect(conv.account).toBe(key);
+ expect(app.store.listMessages(conv.id).map((m) => m.content)).toContain("第二句");
+ // 重启后还记得
+ await app.restartBot(key);
+ await say(key, "boss", "重启后");
+ expect(shown(key, "boss")).toBe("[mock-b] 你说:重启后");
+ // 序号也能切回去
+ await say(key, "boss", "/bot 1");
+ await say(key, "boss", "回来了");
+ expect(shown(key, "boss")).toBe("[mock-a] 你说:回来了");
+ });
+
+ it("没这个机器人:说清楚,不换", async () => {
+ const key = (await api("/channel-accounts")).json.accounts[0].key;
+ await say(key, "boss", "/bot 不存在的");
+ expect(shown(key, "boss")).toContain("没找到");
+ await say(key, "boss", "还是原来的");
+ expect(shown(key, "boss")).toBe("[mock-a] 你说:还是原来的");
+ });
+
+ it("名单跟着账号:主人切到别的机器人也不用再申请", async () => {
+ const key = (await api("/channel-accounts")).json.accounts[0].key;
+ await say(key, "boss", "/bot 阿紫");
+ await say(key, "boss", "还能用吗");
+ expect(shown(key, "boss")).toBe("[mock-b] 你说:还能用吗");
+ const access = (await api(`/channel-accounts/${key}/access`)).json;
+ expect(access.owners.telegram).toMatchObject({ peer: "boss" });
+ expect(access.requests).toEqual([]);
+ await say(key, "boss", "/bot 1");
+ });
+
+ it("主动消息走这个账号(渠道换了机器人也不串)", async () => {
+ const key = (await api("/channel-accounts")).json.accounts[0].key;
+ await app.channels.get(key)!.messengers!.telegram!.notify("boss", "通知一下", "notice:test");
+ await app.channels.get(key)!.messengers!.telegram!.idle();
+ const row = app.store.getOutbox("notice:test")!;
+ expect(row.account).toBe(key);
+ expect(row.botId).toBe("default");
+ expect(row.status).toBe("sent");
+ expect(fakes.get(key)!.lastShown("boss")).toBe("通知一下");
+ });
+
+ it("/help 里有 /bot", async () => {
+ const key = (await api("/channel-accounts")).json.accounts[0].key;
+ await say(key, "boss", "/help");
+ expect(shown(key, "boss")).toContain("/bot");
+ });
+});
+
+describe("同一个渠道多个账号", () => {
+ it("第二个账号:序号往后排,默认名字不重复,可以指定别的默认机器人", async () => {
+ const first = (await api("/channel-accounts")).json.accounts[0];
+ const { key } = (await api("/channel-accounts/new-key", { method: "POST", body: {} })).json;
+ await api(`/channel-accounts/${key}/telegram`, { method: "PUT", body: { token: "2:OTHER" } });
+ const a = await account(key);
+ expect(a.number).toBe(2);
+ expect(a.label).not.toBe(first.label);
+ expect((await api(`/channel-accounts/${key}/telegram/settings`, { method: "PUT", body: { defaultBot: secondBot } })).status).toBe(200);
+ await say(key, "fan", "你是谁");
+ expect(shown(key, "fan")).toBe("[mock-b] 你说:你是谁");
+ // 另一个账号的主人是分开的
+ expect((await api(`/channel-accounts/${key}/access`)).json.owners.telegram).toMatchObject({ peer: "fan" });
+ expect((await api(`/channel-accounts/${first.key}/access`)).json.owners.telegram).toMatchObject({ peer: "boss" });
+ });
+
+ it("别名:同一个渠道不能重复(不分大小写),不能为空或全是数字;默认机器人要存在", async () => {
+ const [a, b] = (await api("/channel-accounts")).json.accounts;
+ const set = (key: string, body: unknown) => api(`/channel-accounts/${key}/telegram/settings`, { method: "PUT", body });
+ expect((await set(a.key, { label: "Work" })).status).toBe(200);
+ expect((await set(b.key, { label: "work" })).status).toBe(400);
+ expect((await set(b.key, { label: " " })).status).toBe(400);
+ expect((await set(b.key, { label: "2" })).status).toBe(400);
+ expect((await set(b.key, { defaultBot: "nobody" })).status).toBe(404);
+ expect((await set(a.key, { label: "WORK" })).status).toBe(200);
+ expect((await account(a.key)).label).toBe("WORK");
+ expect((await set("nope", { label: "x" })).status).toBe(404);
+ });
+
+ it("移除账号:连接断开,凭据和名单都清掉,机器人和聊天记录都在", async () => {
+ const accounts = (await api("/channel-accounts")).json.accounts;
+ const { key } = accounts[1];
+ const fake = fakes.get(key)!;
+ expect((await api(`/channel-accounts/${key}/telegram`, { method: "DELETE" })).status).toBe(200);
+ expect(fake.stopped).toBe(1);
+ expect(await account(key)).toBeUndefined();
+ expect(app.store.getMessengerAccount(key, "telegram")).toBeUndefined();
+ expect(app.store.listAccess({ botId: key, channel: "telegram" })).toEqual([]);
+ expect(app.store.getBot(secondBot)).toBeTruthy();
+ expect(app.store.getConversation(`${secondBot}:telegram:fan`)).toBeTruthy();
+ });
+});
+
+describe("删除机器人", () => {
+ it("账号不受影响:选过它的人回到默认机器人,账号的默认机器人没了就用第一个", async () => {
+ const third = (await api("/bots", { method: "POST", body: { name: "小橙", defaultModel: "mock-b" } })).json.bot.id;
+ const { key } = (await api("/channel-accounts")).json.accounts[0];
+ const fake = fakes.get(key)!;
+ await say(key, "boss", "/bot 小橙");
+ await say(key, "boss", "在吗");
+ expect(shown(key, "boss")).toBe("[mock-b] 你说:在吗");
+ await api(`/channel-accounts/${key}/telegram/settings`, { method: "PUT", body: { defaultBot: third } });
+ expect((await api(`/bots/${third}`, { method: "DELETE" })).status).toBe(200);
+ expect(fake.stopped).toBe(0);
+ expect((await account(key)).defaultBot).toBe("default");
+ await say(key, "boss", "还在");
+ expect(shown(key, "boss")).toBe("[mock-a] 你说:还在");
+ });
+});
+
+describe("升级:老数据变成全局账号", () => {
+ it("机器人上的飞书、微信、其他平台:key 沿用机器人 id,默认机器人是它自己,名字不撞车", async () => {
+ const bot = app.store.createBot({ id: "old-bot", name: "WORK", systemPrompt: "", feishuAppId: "cli_old", feishuAppSecret: "old-secret", weixinEnabled: false });
+ app.store.saveWeixinAccount({ botId: bot.id, botToken: "t", ilinkBotId: "i", baseUrl: "http://127.0.0.1:1", ownerUserId: "me" });
+ app.store.saveMessengerAccount({ botId: bot.id, channel: "telegram", credentials: { token: "3:OLD" }, name: "" });
+ await app.startBot(bot.id);
+ const rows = app.store.listChannelAccounts().filter((a) => a.key === bot.id);
+ expect(rows.map((a) => a.channel).sort()).toEqual(["feishu", "telegram", "weixin"]);
+ expect(rows.every((a) => a.defaultBot === bot.id)).toBe(true);
+ // 飞书凭据搬进账号,机器人上清掉,移除账号后不会又变回来
+ expect(app.store.getBot(bot.id)!.feishuAppId).toBe("");
+ expect(app.store.getChannelAccount(bot.id, "feishu")!.credentials).toEqual({ appId: "cli_old", appSecret: "old-secret" });
+ // 微信关着的还是关着
+ expect(app.store.getChannelAccount(bot.id, "weixin")!.enabled).toBe(false);
+ expect(app.channels.get(bot.id)!.weixin).toBeUndefined();
+ // 已经有账号叫 WORK:Telegram 的默认名字让开
+ expect(app.store.getChannelAccount(bot.id, "telegram")!.label).toBe("WORK 2");
+ expect((await api(`/channel-accounts/${bot.id}/channels`)).json.feishu.account).toEqual({ appId: "cli_old", saved: { appSecret: "****cret" } });
+ await api(`/channel-accounts/${bot.id}/feishu`, { method: "DELETE" });
+ await app.restartBot(bot.id);
+ expect(app.store.getChannelAccount(bot.id, "feishu")).toBeUndefined();
+ await api(`/channel-accounts/${bot.id}/telegram`, { method: "DELETE" });
+ await api(`/channel-accounts/${bot.id}/weixin/logout`, { method: "POST", body: {} });
+ });
+});
+
+describe("分发规则", () => {
+ const store = () => {
+ const s = new Store(":memory:");
+ for (const [id, name] of [["a", "小蓝"], ["b", "小绿"], ["c", "小绿茶"]]) s.createBot({ id, name, systemPrompt: "", feishuAppId: "", feishuAppSecret: "", weixinEnabled: false });
+ return s;
+ };
+
+ it("这个人选过的 → 账号的默认机器人 → key 同名的机器人 → 第一个机器人", () => {
+ const s = store();
+ expect(botForPeer(s, "nothing", "telegram", "p")).toBe("a");
+ expect(botForPeer(s, "b", "telegram", "p")).toBe("b");
+ s.saveChannelAccount({ key: "k", channel: "telegram", label: "x", defaultBot: "c", enabled: true, credentials: {}, createdAt: 1 });
+ expect(defaultBotFor(s, "k", "telegram")).toBe("c");
+ expect(botForPeer(s, "k", "telegram", "p")).toBe("c");
+ setBotForPeer(s, "k", "telegram", "p", "b");
+ expect(botForPeer(s, "k", "telegram", "p")).toBe("b");
+ // 别人、别的账号不受影响
+ expect(botForPeer(s, "k", "telegram", "q")).toBe("c");
+ s.deleteBot("b");
+ expect(botForPeer(s, "k", "telegram", "p")).toBe("c");
+ s.deleteBot("c");
+ expect(botForPeer(s, "k", "telegram", "p")).toBe("a");
+ });
+
+ it("按序号或名字找机器人;名字模糊时不猜", () => {
+ const s = store();
+ expect(findBot(s, "2")?.id).toBe("b");
+ expect(findBot(s, "9")).toBeUndefined();
+ expect(findBot(s, "小绿")?.id).toBe("b");
+ expect(findBot(s, "绿茶")?.id).toBe("c");
+ expect(findBot(s, "小")).toBeUndefined();
+ expect(findBot(s, "没有")).toBeUndefined();
+ });
+});
+
+describe("每个机器人都知道有哪些机器人", () => {
+ const others = [{ name: "阿紫", persona: "写代码的助手。\n第二行不要" }, { name: "小橙", persona: "" }];
+
+ it("系统提示词里有其他机器人的名单和切换方法;只有一个机器人时不写", () => {
+ const text = botPrompt({ name: "小蓝", persona: "", memory: false, others });
+ expect(text).toContain("阿紫:写代码的助手。");
+ expect(text).not.toContain("第二行不要");
+ expect(text).toContain("- 小橙");
+ expect(text).toContain("/bot");
+ expect(text).toContain("不用每句都带");
+ expect(botTeam([])).toBe("");
+ expect(botPrompt({ name: "小蓝", persona: "", memory: false })).not.toContain("其他机器人");
+ });
+});
diff --git a/test/e2e.test.ts b/test/e2e.test.ts
index 06bdb50..19f2bf3 100644
--- a/test/e2e.test.ts
+++ b/test/e2e.test.ts
@@ -104,12 +104,12 @@ describe("飞书 E2E", () => {
describe("微信 E2E", () => {
it("界面扫码登录 → 长轮询收消息 → 输入状态 → 一次性回复", async () => {
- const st0 = await api("/bots/default/channels");
+ const st0 = await api("/channel-accounts/default/channels");
expect(st0.json.weixin.state).toBe("login_required");
- const start = await api("/bots/default/weixin/login", { method: "POST", body: {} });
+ const start = await api("/channel-accounts/default/weixin/login", { method: "POST", body: {} });
expect(start.status).toBe(200);
expect(start.json.qrDataUrl).toMatch(/^data:image\/png;base64,/);
- await until(async () => (await api("/bots/default/channels")).json.weixin.state === "connected", 8000);
+ await until(async () => (await api("/channel-accounts/default/channels")).json.weixin.state === "connected", 8000);
expect(fs.existsSync(path.join(dataDir, "weixin", "default-login-qr.png"))).toBe(true);
const acct = app.store.getWeixinAccount("default")!;
expect(acct.ilinkBotId).toBe("[email protected]");
@@ -124,7 +124,7 @@ describe("微信 E2E", () => {
expect(ilink.state.typing).toContain(1);
await until(() => ilink.state.typing.includes(2));
expect(ilink.state.authSeen).toContain("Bearer tok-secret-123");
- const st = await api("/bots/default/channels");
+ const st = await api("/channel-accounts/default/channels");
expect(st.json.weixin.quota[0]).toMatchObject({ userId: "[email protected]", remaining: 9 });
expect(app.store.getWeixinAccount("default")!.cursor).toMatch(/^cur-/);
});
@@ -188,7 +188,7 @@ describe("微信 E2E", () => {
});
it("会话过期 -14 → 暂停并提示重新扫码", async () => {
ilink.state.expireNext = true;
- await until(async () => (await api("/bots/default/channels")).json.weixin.state === "expired", 8000);
+ await until(async () => (await api("/channel-accounts/default/channels")).json.weixin.state === "expired", 8000);
expect(app.store.getWeixinAccount("default")!.pausedUntil).toBeGreaterThan(Date.now());
const s = await api("/status");
expect(s.json.notices.some((n: any) => n.text.includes("重新扫码"))).toBe(true);
@@ -230,11 +230,12 @@ describe("Web 界面 / API", () => {
expect((await api(`/bots/${id}`)).json.bot.settings.paused).toBe(true);
expect((await api(`/bots/${id}/settings`, { method: "PUT", body: { paused: false } })).json.settings.paused).toBe(false);
expect((await api("/bots/default")).json.bot.settings.avatar).toBe("blue");
- const f = await api(`/bots/${id}/feishu`, { method: "PUT", body: { appId: "cli_x", appSecret: "very-secret-value" } });
+ const f = await api(`/channel-accounts/${id}/feishu`, { method: "PUT", body: { appId: "cli_x", appSecret: "very-secret-value" } });
expect(f.status).toBe(200);
- const g = await api(`/bots/${id}`);
+ const g = await api(`/channel-accounts/${id}/channels`);
expect(JSON.stringify(g.json)).not.toContain("very-secret-value");
- expect(g.json.bot.feishuAppSecretMasked).toBe("****alue");
+ expect(g.json.feishu.account).toEqual({ appId: "cli_x", saved: { appSecret: "****alue" } });
+ expect(JSON.stringify((await api("/channel-accounts")).json)).not.toContain("very-secret-value");
const chat = await api(`/bots/${id}/chat`, { method: "POST", body: { text: "hi" } });
expect(chat.json.reply).toBe("[mock-b] 你说:hi");
const convs = await api(`/conversations?bot=${id}`);
diff --git a/test/messenger.e2e.test.ts b/test/messenger.e2e.test.ts
index ca5d6d9..042b681 100644
--- a/test/messenger.e2e.test.ts
+++ b/test/messenger.e2e.test.ts
@@ -64,22 +64,22 @@ afterAll(async () => {
describe("连接", () => {
it("凭据被拒:报错、不保存", async () => {
rejectNext = "telegram getMe: 401 Unauthorized";
- const r = await api("/bots/default/telegram", { method: "PUT", body: { token: "bad" } });
+ const r = await api("/channel-accounts/default/telegram", { method: "PUT", body: { token: "bad" } });
expect(r.status).toBe(400);
expect(r.json.error ?? r.json.message).toContain("401");
expect(app.store.getMessengerAccount("default", "telegram")).toBeUndefined();
});
it("没填全:报错", async () => {
- const r = await api("/bots/default/slack", { method: "PUT", body: { botToken: "xoxb-1" } });
+ const r = await api("/channel-accounts/default/slack", { method: "PUT", body: { botToken: "xoxb-1" } });
expect(r.status).toBe(400);
});
it("连上:状态在线、显示平台上的名字;状态里没有完整的 token", async () => {
- const r = await api("/bots/default/telegram", { method: "PUT", body: { token: "123456:SECRETSECRETSECRET" } });
+ const r = await api("/channel-accounts/default/telegram", { method: "PUT", body: { token: "123456:SECRETSECRETSECRET" } });
expect(r.status).toBe(200);
- await until(async () => (await api("/bots/default/channels")).json.telegram.state === "connected");
- const st = (await api("/bots/default/channels")).json;
+ await until(async () => (await api("/channel-accounts/default/channels")).json.telegram.state === "connected");
+ const st = (await api("/channel-accounts/default/channels")).json;
expect(st.telegram.account.name).toBe("@fake_bot");
expect(JSON.stringify(st)).not.toContain("SECRETSECRETSECRET");
expect(st.discord.state).toBe("disabled");
@@ -88,11 +88,11 @@ describe("连接", () => {
});
it("不是平台的路径不受理;Slack 留空的 token 沿用已保存的", async () => {
- await api("/bots/default/slack", { method: "PUT", body: { botToken: "xoxb-1", appToken: "xapp-1" } });
+ await api("/channel-accounts/default/slack", { method: "PUT", body: { botToken: "xoxb-1", appToken: "xapp-1" } });
created.length = 0;
- expect((await api("/bots/default/slack", { method: "PUT", body: { appToken: "xapp-2" } })).status).toBe(200);
+ expect((await api("/channel-accounts/default/slack", { method: "PUT", body: { appToken: "xapp-2" } })).status).toBe(200);
expect(created.at(-1)).toMatchObject({ id: "slack", credentials: { botToken: "xoxb-1", appToken: "xapp-2" } });
- await api("/bots/default/slack", { method: "DELETE" });
+ await api("/channel-accounts/default/slack", { method: "DELETE" });
});
it("重启后接着连(凭据在库里);stopBot 会停掉", async () => {
@@ -106,10 +106,10 @@ describe("连接", () => {
describe("对话", () => {
it("第一个发消息的人成为主人,流式显示并写成最终回复", async () => {
- expect((await api("/bots/default/access")).json.owners.telegram).toBeNull();
+ expect((await api("/channel-accounts/default/access")).json.owners.telegram).toBeNull();
await say("telegram", "我是老板", { chatId: "boss", senderId: "boss", senderName: "Boss" });
expect(fakes.get("telegram")!.lastShown("boss")).toBe("[mock-a] 你说:我是老板");
- expect((await api("/bots/default/access")).json.owners.telegram).toEqual({ via: "first-message", peer: "boss", name: "Boss" });
+ expect((await api("/channel-accounts/default/access")).json.owners.telegram).toEqual({ via: "first-message", peer: "boss", name: "Boss" });
const conv = app.store.getConversation("default:telegram:boss");
expect(conv?.channel).toBe("telegram");
});
@@ -157,30 +157,30 @@ describe("对话", () => {
expect(await app.pushToOwner("余额不足")).toBe(true);
await channel("telegram").idle();
expect(f.lastShown("boss")).toContain("余额不足");
- expect((await api("/bots/default/access/owner/telegram", { method: "DELETE" })).status).toBe(200);
+ expect((await api("/channel-accounts/default/access/owner/telegram", { method: "DELETE" })).status).toBe(200);
await say("telegram", "换我", { chatId: "new", senderId: "new", senderName: "New" });
- expect((await api("/bots/default/access")).json.owners.telegram).toMatchObject({ peer: "new" });
+ expect((await api("/channel-accounts/default/access")).json.owners.telegram).toMatchObject({ peer: "new" });
});
it("断开:渠道停下、凭据清掉、主人清掉", async () => {
const f = fakes.get("telegram")!;
- expect((await api("/bots/default/telegram", { method: "DELETE" })).status).toBe(200);
+ expect((await api("/channel-accounts/default/telegram", { method: "DELETE" })).status).toBe(200);
expect(f.stopped).toBe(1);
expect(app.store.getMessengerAccount("default", "telegram")).toBeUndefined();
- const st = (await api("/bots/default/channels")).json;
+ const st = (await api("/channel-accounts/default/channels")).json;
expect(st.telegram.state).toBe("disabled");
expect(st.telegram.account).toBeUndefined();
- expect((await api("/bots/default/access")).json.owners.telegram).toBeNull();
+ expect((await api("/channel-accounts/default/access")).json.owners.telegram).toBeNull();
});
});
describe("连不上(凭据失效)", () => {
it("信息面板显示原因", async () => {
- await api("/bots/default/discord", { method: "PUT", body: { token: "t" } });
+ await api("/channel-accounts/default/discord", { method: "PUT", body: { token: "t" } });
const f = fakes.get("discord")!;
await until(() => !!f.onState);
f.onState!("error", "the bot token was rejected", true);
- const st = (await api("/bots/default/channels")).json.discord;
+ const st = (await api("/channel-accounts/default/channels")).json.discord;
expect(st).toMatchObject({ state: "error", detail: "the bot token was rejected" });
});
});
diff --git a/test/recovery.test.ts b/test/recovery.test.ts
index 081e4ad..a0bdf58 100644
--- a/test/recovery.test.ts
+++ b/test/recovery.test.ts
@@ -211,7 +211,8 @@ describe("App 启动时告诉用户", () => {
await until(() => ilink.state.sent.length >= 1 && feishu.sent.length >= 1);
expect(app.store.listMessages("default:web:console").map((m) => [m.role, m.content])).toEqual([["assistant", "上次的消息「网页里的长任务」因为应用重启没有处理完,请重新发送。"]]);
expect(ilink.state.sent).toEqual([{ to: "[email protected]", contextToken: "ctx-alice", text: "上次的消息「微信里的长任务」因为应用重启没有处理完,请重新发送。" }]);
- expect(app.store.getWeixinPeer("default", "[email protected]")!.quotaRemaining).toBe(9);
+ // 先发出去,再扣配额:等它扣完
+ await until(() => app.store.getWeixinPeer("default", "[email protected]")!.quotaRemaining === 9);
expect(feishu.sent).toEqual([{ chatId: "oc_x", text: "上次的消息「飞书里的长任务」因为应用重启没有处理完,请重新发送。" }]);
expect(app.store.listKV("inflight:")).toEqual([]);
expect(llm.calls).toEqual([]);
diff --git a/ui/locales/en/guide.js b/ui/locales/en/guide.js
index 9c349b0..78da652 100644
--- a/ui/locales/en/guide.js
+++ b/ui/locales/en/guide.js
@@ -55,9 +55,9 @@ export default {
weixin: {
title: "Connect {name} to WeChat",
desc: "Scan a QR code, then message it directly in WeChat. No new app to install, and it's online whenever your computer is on.",
- how: ["Click the bot's name at the top to open the info panel", "Under “Channels”, click “WeChat” → “Scan to log in”", "Scan the code with WeChat and confirm on your phone"],
- note: "WeChat's rule: for each message you send, it can reply up to 10 times within 24 hours. For Feishu, Telegram, Slack or Discord, enter its credentials in the same place.",
- doneText: "Send it a message in WeChat: same bot, same memory.",
+ how: ["Click the bot's name at the top to open the info panel, then “Manage chat channels”", "On the WeChat row, click “Add account” → “Scan to log in”", "Scan the code with WeChat and confirm on your phone"],
+ note: "WeChat's rule: for each message you send, it can reply up to 10 times within 24 hours. For Feishu, Telegram, Slack or Discord, add an account in the same place. All bots share accounts, and you can send /bot and a name in a chat to switch bots.",
+ doneText: "Send it a message in WeChat. To talk to a different bot, send /bot.",
},
hands: {
title: "Put it to work",
diff --git a/ui/locales/en/info.js b/ui/locales/en/info.js
index e2061c2..c542d78 100644
--- a/ui/locales/en/info.js
+++ b/ui/locales/en/info.js
@@ -5,6 +5,9 @@ export default {
closeTitle: "Close (⌘⇧I)",
closeAria: "Close info panel",
channels: "Channels",
+ channelsDefault: "This bot replies by default",
+ channelsManage: "Manage chat channels",
+ channelsSub: "All bots share these accounts. Add them in Settings > Connections",
approvals: "Pending approvals",
due: "Expires {time}",
noApprovals: "No pending approvals",
diff --git a/ui/locales/en/settings.js b/ui/locales/en/settings.js
index bee165e..39f8aff 100644
--- a/ui/locales/en/settings.js
+++ b/ui/locales/en/settings.js
@@ -13,7 +13,18 @@ export default {
about: "About",
},
connections: {
- feishu: "Feishu",
+ feishu: "Feishu messages",
+ channelSub: "Shared by all bots, and you can add several accounts. Send /bot and a name once in a chat to talk to a different bot",
+ channelKeys: "{channel} channel chat connection account bot /bot",
+ addAccount: "Add account",
+ manage: "Manage",
+ defaultIs: "{bot} replies by default",
+ requests: "{count} access requests",
+ addChannelTitle: "Add a {channel} account",
+ defaultBot: "Default bot",
+ defaultBotHint: "It answers new chats. Send /bot in a chat to see the bots, and /bot and a name once to switch; that chat stays with the new bot.",
+ removeAccount: "Remove this account",
+ removeChannelBody: "No bot will be able to send or receive through this account, and its allow list is cleared. Chat history is kept.",
notionSub: "Shared by all bots, and you can add several accounts. Read-only bots can only read, and no bot can delete pages",
feishuSub: "Shared by all bots, and you can add several accounts. Reads your chats and messages as you, read-only",
notionKeys: "notion notes docs database connection account authorize",
diff --git a/ui/locales/zh-CN/guide.js b/ui/locales/zh-CN/guide.js
index f77e523..5017c5b 100644
--- a/ui/locales/zh-CN/guide.js
+++ b/ui/locales/zh-CN/guide.js
@@ -59,9 +59,9 @@ export default {
weixin: {
title: "把{name}接到微信",
desc: "扫码后,在微信里直接私聊它,不用装新 App。电脑开着,它就在线。",
- how: ["点顶部的机器人名字,打开信息面板", "在「渠道」里点「微信」→「扫码登录」", "用微信扫码,在手机上确认"],
- note: "微信的规定:你每发一条消息,它 24 小时内最多回 10 条。用飞书、Telegram、Slack、Discord 的话,在同一处填对应的凭据。",
- doneText: "在微信里给它发条消息试试:同一个机器人,同一份记忆。",
+ how: ["点顶部的机器人名字,打开信息面板,点「管理聊天渠道」", "在「微信」那一行点「添加账号」→「扫码登录」", "用微信扫码,在手机上确认"],
+ note: "微信的规定:你每发一条消息,它 24 小时内最多回 10 条。用飞书、Telegram、Slack、Discord 的话,在同一处添加账号。账号所有机器人共用,聊天时发 /bot 名字 换一个机器人。",
+ doneText: "在微信里给它发条消息试试。想换一个机器人聊,发 /bot。",
},
hands: {
title: "让它动手做件事",
diff --git a/ui/locales/zh-CN/info.js b/ui/locales/zh-CN/info.js
index 485d800..27c5682 100644
--- a/ui/locales/zh-CN/info.js
+++ b/ui/locales/zh-CN/info.js
@@ -5,6 +5,9 @@ export default {
closeTitle: "关闭(⌘⇧I)",
closeAria: "关闭信息面板",
channels: "渠道",
+ channelsDefault: "默认由这个机器人回复",
+ channelsManage: "管理聊天渠道",
+ channelsSub: "微信、飞书等账号所有机器人共用,在 设置 › 连接 里添加",
approvals: "待审批",
/** 审批卡片的截止时刻(HH:MM) */
due: "截止 {time}",
diff --git a/ui/locales/zh-CN/settings.js b/ui/locales/zh-CN/settings.js
index ca1cbb8..96368d8 100644
--- a/ui/locales/zh-CN/settings.js
+++ b/ui/locales/zh-CN/settings.js
@@ -13,7 +13,18 @@ export default {
about: "关于",
},
connections: {
- feishu: "飞书",
+ feishu: "飞书消息",
+ channelSub: "所有机器人共用,可以加多个账号。聊天时发一次 /bot 名字,就换一个机器人聊",
+ channelKeys: "{channel} 渠道 聊天 连接 账号 机器人 /bot",
+ addAccount: "添加账号",
+ manage: "管理",
+ defaultIs: "默认由 {bot} 回复",
+ requests: "{count} 个使用请求",
+ addChannelTitle: "添加{channel}账号",
+ defaultBot: "默认机器人",
+ defaultBotHint: "新会话先由它回复。聊天时发 /bot 看有哪些机器人,发一次 /bot 名字就换过去,之后这个会话一直和它聊。",
+ removeAccount: "移除这个账号",
+ removeChannelBody: "所有机器人都不能再从这个账号收发消息,它的允许名单也会清掉。聊天记录保留。",
notionSub: "所有机器人共用,可以加多个账号。只读机器人只能读取,机器人都不能删除页面",
feishuSub: "所有机器人共用,可以加多个账号。用你的身份读会话和消息,只读",
notionKeys: "notion 笔记 文档 数据库 连接 账号 授权",
diff --git a/ui/main.js b/ui/main.js
index bc13749..bfb938a 100644
--- a/ui/main.js
+++ b/ui/main.js
@@ -284,10 +284,7 @@ function App() {
};
const openNeeds = () => go("/needs");
// 「需要你」里的重新扫码:去这个机器人的对话,打开信息面板(渠道在最上面)
- const relogin = (id) => {
- openChat(id);
- setInfoOpen(true);
- };
+ const relogin = () => openSettings("connections");
useEffect(() => {
if (route.view !== "settings") setSettingsQ("");
}, [route.view]);
@@ -403,7 +400,7 @@ function App() {
onCommit=${(v) => setPrefs({ panelW: v })} />`}
${shownPanel && html`<div class=${`panel-scrim${panelFx.leaving ? " leaving" : ""}`} onClick=${() => setInfoOpen(false)}></div>`}
${shownPanel && html`<${InfoPanel} key=${shownPanel.id} bot=${shownPanel} leaving=${panelFx.leaving} onClose=${() => setInfoOpen(false)}
- onOpenBotSettings=${() => openBotSettings(shownPanel.id)} onOpenChat=${() => setInfoOpen(false)} />`}
+ onOpenBotSettings=${() => openBotSettings(shownPanel.id)} onOpenChat=${() => setInfoOpen(false)} onOpenConnections=${() => openSettings("connections")} />`}
<${CoachMark} bot=${view === "chat" ? bot : null} view=${view} infoOpen=${!!panelBot} />
${palette && html`<${Palette} commands=${commands} onClose=${() => setPalette(false)} />`}
<${DialogHost} />
diff --git a/ui/screens/bot-settings.js b/ui/screens/bot-settings.js
index cdc436e..7dc7b31 100644
--- a/ui/screens/bot-settings.js
+++ b/ui/screens/bot-settings.js
@@ -7,8 +7,6 @@ import { api } from "../lib/api.js";
import { confirmSheet, failed, saved } from "../lib/store.js";
import { usd } from "../lib/links.js";
import { perms, fullWarning, confirmPermission } from "../lib/perms.js";
-import { channelName, sourceLabel } from "../lib/access.js";
-import { fmtAgo } from "../lib/format.js";
import { t } from "../lib/i18n.js";
import { RuleEditor } from "../components/rules.js";
@@ -90,66 +88,6 @@ function BudgetRows({ bot, budget, account, onSaved, onOpenSettings }) {
* 谁能使用:只有主人和允许名单里的人。主人 = 扫码登录的微信 / 连上之后第一个发消息的人,后者可以更换(下一个发消息的人成为主人)。
* 允许名单和拒绝过的人可以移除(移除后他再发消息会重新申请)。没有的项不显示。
*/
-function AccessRows({ botId }) {
- const [d, setD] = useState(null);
- const load = () => api(`/bots/${botId}/access`).then(setD).catch(failed);
- useEffect(() => {
- load();
- }, [botId]);
- const call = async (path, method) => {
- try {
- await api(`/bots/${botId}/access/${path}`, method === "DELETE" ? { method } : { method, body: {} });
- saved();
- load();
- } catch (e) {
- failed(e);
- }
- };
- const remove = async (e) => {
- const denied = e.status === "denied";
- if (!(await confirmSheet({
- title: t(denied ? "botSettings.access.removeDeniedTitle" : "botSettings.access.revokeTitle", { who: e.who }),
- body: t(denied ? "botSettings.access.removeDeniedBody" : "botSettings.access.revokeBody"),
- confirmLabel: t("botSettings.access.remove"),
- danger: !denied,
- }))) return;
- call(encodeURIComponent(e.id), "DELETE");
- };
- const resetOwner = async (ch, o) => {
- const name = channelName(ch);
- if (!(await confirmSheet({ title: t("botSettings.access.resetOwnerTitle", { channel: name }), body: t("botSettings.access.resetOwnerBody", { channel: name, who: o.name }), confirmLabel: t("botSettings.access.reset"), danger: true }))) return;
- call(`owner/${ch}`, "DELETE");
- };
- if (!d) return html`<div class="list-head">${t("botSettings.access.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];
- return o && html`<${Row} id=${`access-${ch}`} name=${t("botSettings.access.owner", { channel: channelName(ch) })}>
- <span class="val">${o.name}</span>
- ${o.via !== "login" && html`<button type="button" class="text" onClick=${() => resetOwner(ch, o)}>${t("botSettings.access.reset")}</button>`}
- <//>`;
- };
- return html`<div class="list-head">${t("botSettings.access.head")}</div>
- <div class="list">
- <${Row} id="access" name=${t("botSettings.access.policy")} />
- ${["weixin", "feishu", "telegram", "slack", "discord"].map((ch) => owner(ch))}
- </div>
- ${allowed.length > 0 && html`<div class="list-head">${t("botSettings.access.allowed")}<span class="badge count">${allowed.length}</span></div>
- <div class="list">
- ${allowed.map((e) => html`<${Row} key=${e.id} id=${`access-${e.id}`} name=${e.who} sub=${[sourceLabel(e.source), e.decidedAt ? fmtAgo(e.decidedAt) : ""].filter(Boolean).join(" · ")}>
- <button type="button" class="text danger" onClick=${() => remove(e)}>${t("botSettings.access.remove")}</button>
- <//>`)}
- </div>`}
- ${denied.length > 0 && html`<div class="list-head">${t("botSettings.access.denied")}</div>
- <div class="list">
- ${denied.map((e) => html`<${Row} key=${e.id} id=${`access-${e.id}`} name=${e.who} sub=${t("botSettings.access.deniedSub", { when: fmtAgo(e.decidedAt) })}>
- <button type="button" class="text accent" onClick=${() => call(`${encodeURIComponent(e.id)}/approve`, "POST")}>${t("botSettings.access.allow")}</button>
- <button type="button" class="text" onClick=${() => remove(e)}>${t("botSettings.access.remove")}</button>
- <//>`)}
- </div>`}`;
-}
-
export function BotSettingsScreen({ bot, section, models, modelsError, reloadModels, defaultModel, account, onOpenSettings, onBack, onBotUpdated, onDeleted }) {
const [d, setD] = useState(null);
const [name, setName] = useState(bot.name);
@@ -262,7 +200,6 @@ export function BotSettingsScreen({ bot, section, models, modelsError, reloadMod
</div>
${s.permission === "full" && html`<${Notice} tone="red">${fullWarning()}<//>`}
- <${AccessRows} botId=${bot.id} />
<div class="list-head">${t("botSettings.memory.head")}</div>
<div class="list">
@@ -297,9 +234,9 @@ export function BotSettingsScreen({ bot, section, models, modelsError, reloadMod
onChange=${(v) => put({ quietHours: { to: v } })} />`}
<${Switch} label=${t("botSettings.proactive.quiet")} value=${s.quietHours.enabled} onChange=${(v) => put({ quietHours: { enabled: v } })} />
<//>
- ${bot.weixinEnabled && html`<${Row} id="nudge" name=${t("botSettings.proactive.nudge")} sub=${t("botSettings.proactive.nudgeSub")}>
+ <${Row} id="nudge" name=${t("botSettings.proactive.nudge")} sub=${t("botSettings.proactive.nudgeSub")}>
<${Switch} label=${t("botSettings.proactive.nudge")} value=${s.nudge} onChange=${(v) => put({ nudge: v })} />
- <//>`}
+ <//>
<${Row} id="rules" name=${t("botSettings.proactive.rules")} sub=${rules && rules.length ? t("botSettings.proactive.rulesCount", { count: rules.length }) : t("botSettings.proactive.rulesSub")}>
<button type="button" class="btn" onClick=${() => setNewRule(true)}>${t("botSettings.proactive.newRule")}</button>
<//>
diff --git a/ui/screens/connections.js b/ui/screens/connections.js
index 98b110b..c9997f6 100644
--- a/ui/screens/connections.js
+++ b/ui/screens/connections.js
@@ -1,10 +1,15 @@
-// 设置 › 连接:已授权账号。全局一份,所有机器人共用;同一个服务可以加多个账号。
-// 用户可以对任何机器人说「看我第一个飞书和第二个飞书的消息」,序号就是这里显示的序号。
-// 令牌不会回到界面:接口只给名字、序号和状态(src/agent/accounts.ts)。
+// 设置 › 连接:全局一份,所有机器人共用;同一个服务可以加多个账号,都能起别名。两类账号:
+// - 聊天渠道(微信、飞书、Telegram、Slack、Discord):从这里和机器人聊。账号有一个默认机器人,聊天时发一次 /bot 名字
+// 就换过去,之后这个会话一直和它聊(src/core/routes.ts)。
+// - 数据账号(Notion、飞书消息):机器人能读写的账号。可以对任何机器人说「看我第一个飞书和第二个飞书的消息」,
+// 序号就是这里显示的序号(src/agent/accounts.ts)。
+// 令牌不会回到界面:接口只给名字、序号、状态和掩码。
import { useEffect, useRef, useState } from "preact/hooks";
-import { html, Sheet, Spinner } from "../components/ui.js";
+import { html, Badge, Button, MenuButton, Sheet, Skeleton, Spinner } from "../components/ui.js";
import { api } from "../lib/api.js";
-import { confirmSheet, failed, saved } from "../lib/store.js";
+import { channelName, sourceLabel } from "../lib/access.js";
+import { fmtAgo, fmtTime } from "../lib/format.js";
+import { confirmSheet, failed, saved, toast } from "../lib/store.js";
import { t } from "../lib/i18n.js";
const NOTION_PORTAL = "https://www.notion.so/developers";
@@ -14,18 +19,74 @@ const OAUTH_WAIT_MS = 10 * 60_000;
const serviceName = (service) => (service === "feishu" ? t("settings.connections.feishu") : "Notion");
-/** 账号列表和正在打开的弹窗 */
+/** 聊天渠道,按这个顺序列 */
+const CHANNELS = ["weixin", "feishu", "telegram", "slack", "discord"];
+/** Telegram、Slack、Discord:填 token 连上。key 和后端 MESSENGER_FIELDS 对应 */
+const MESSENGER_FIELDS = {
+ telegram: [{ key: "token", placeholder: "123456789:AA…" }],
+ slack: [{ key: "botToken", placeholder: "xoxb-…" }, { key: "appToken", placeholder: "xapp-…" }],
+ discord: [{ key: "token", placeholder: "" }],
+};
+/** 接入说明里 <code> 包着的权限名、事件名 */
+const code = (s) => html`<code>${s}</code>`;
+const MESSENGER_HINT = {
+ telegram: () => ({ bot: code("@BotFather"), cmd: code("/newbot") }),
+ slack: () => ({ conn: code("connections:write"), s1: code("chat:write"), s2: code("im:history"), s3: code("files:read"), s4: code("files:write"), event: code("message.im") }),
+ discord: () => ({}),
+};
+const FEISHU_HINT = () => ({ event: code("im.message.receive_v1"), p1: code("im:message.p2p_msg:readonly"), p2: code("im:message:send_as_bot"), p3: code("cardkit:card:write"), p4: code("im:message.history:readonly") });
+const ACTIVE_LOGIN = ["fetching", "wait", "scaned", "need_verifycode"];
+
+/** 账号列表和正在打开的弹窗。渠道账号的状态会变(连上、过期、有人申请使用),所以一直刷新 */
export function useConnections() {
const [accounts, setAccounts] = useState([]);
+ const [channelAccounts, setChannelAccounts] = useState([]);
const [sheet, setSheet] = useState(null);
+ const reloadChannels = () => api("/channel-accounts").then((r) => setChannelAccounts(r.accounts)).catch(() => {});
useEffect(() => {
api("/connections").then((r) => setAccounts(r.accounts)).catch(failed);
+ reloadChannels();
+ const timer = setInterval(reloadChannels, 5000);
+ return () => clearInterval(timer);
}, []);
- return { accounts, setAccounts, sheet, setSheet };
+ return { accounts, setAccounts, channelAccounts, setChannelAccounts, reloadChannels, sheet, setSheet };
+}
+
+/** 设置页的行:先是聊天渠道,再是数据账号 */
+export function connectionRows(conn, bots) {
+ return [...channelRows(conn, bots), ...dataRows(conn)];
+}
+
+function channelRows({ channelAccounts, setSheet }, bots) {
+ const botName = (id) => (bots || []).find((b) => b.id === id)?.name ?? id;
+ const rows = [];
+ for (const channel of CHANNELS) {
+ rows.push({
+ tab: "connections",
+ id: `add-channel-${channel}`,
+ name: channelName(channel),
+ sub: t("settings.connections.channelSub"),
+ keys: t("settings.connections.channelKeys", { channel: channelName(channel) }),
+ ctl: html`<button type="button" class="btn" onClick=${() => setSheet({ kind: "channel", channel })}>${t("settings.connections.addAccount")}</button>`,
+ });
+ for (const a of channelAccounts.filter((x) => x.channel === channel)) {
+ const parts = [a.status?.detail, t("settings.connections.defaultIs", { bot: botName(a.defaultBot) }), a.requests ? t("settings.connections.requests", { count: a.requests }) : ""];
+ rows.push({
+ tab: "connections",
+ id: `channel-${channel}-${a.key}`,
+ name: `${channelName(channel)} ${a.number} · ${a.label}`,
+ sub: parts.filter(Boolean).join(" · "),
+ keys: `${channelName(channel)} ${a.label}`,
+ ctl: html`${a.status && html`<${Badge} s=${a.status.state} />`}
+ <button type="button" class="text" onClick=${() => setSheet({ kind: "channel", channel, accountKey: a.key })}>${t("settings.connections.manage")}</button>`,
+ });
+ }
+ }
+ return rows;
}
-/** 设置页的行:每个服务一行添加入口,下面是这个服务已加的账号 */
-export function connectionRows({ accounts, setAccounts, setSheet }) {
+/** 数据账号:每个服务一行添加入口,下面是这个服务已加的账号 */
+function dataRows({ accounts, setAccounts, setSheet }) {
const remove = async (a) => {
if (!(await confirmSheet({ title: t("settings.connections.removeTitle", { name: a.label }), body: t("settings.connections.removeBody"), confirmLabel: t("settings.connections.remove"), danger: true }))) return;
try {
@@ -235,10 +296,191 @@ function RenameSheet({ conn, account, onClose }) {
<//>`;
}
-export function ConnectionSheets({ conn }) {
+/** 谁能用这个账号:使用请求、主人、允许名单、拒绝过的人。名单跟着账号走,能用这个账号的人可以和任何机器人聊 */
+function AccessPanel({ accountKey, channel, onChanged }) {
+ const [d, setD] = useState(null);
+ const [busy, setBusy] = useState("");
+ const base = `/channel-accounts/${encodeURIComponent(accountKey)}/access`;
+ const load = () => api(base).then(setD).catch(() => {});
+ useEffect(() => {
+ load();
+ const timer = setInterval(load, 4000);
+ return () => clearInterval(timer);
+ }, [accountKey]);
+ const call = async (path, method) => {
+ try {
+ await api(`${base}/${path}`, method === "DELETE" ? { method } : { method, body: {} });
+ saved();
+ load();
+ onChanged();
+ } catch (e) {
+ failed(e);
+ }
+ };
+ if (!d) return html`<div class="list-head">${t("botSettings.access.head")}</div><div class="list"><div class="row"><${Skeleton} w="45%" /></div></div>`;
+ const own = (x) => x.channel === channel;
+ const requests = d.requests.filter(own);
+ const allowed = d.entries.filter((e) => own(e) && e.status === "allowed");
+ const denied = d.entries.filter((e) => own(e) && e.status === "denied");
+ const owner = d.owners[channel];
+ const decide = async (r, what) => {
+ setBusy(r.id + what);
+ await call(`${encodeURIComponent(r.id)}/${what}`, "POST");
+ toast(t(what === "approve" ? "info.access.allowed" : "info.access.denied", { who: r.who }));
+ setBusy("");
+ };
+ const remove = async (e) => {
+ const isDenied = e.status === "denied";
+ if (!(await confirmSheet({
+ title: t(isDenied ? "botSettings.access.removeDeniedTitle" : "botSettings.access.revokeTitle", { who: e.who }),
+ body: t(isDenied ? "botSettings.access.removeDeniedBody" : "botSettings.access.revokeBody"),
+ confirmLabel: t("botSettings.access.remove"),
+ danger: !isDenied,
+ }))) return;
+ call(encodeURIComponent(e.id), "DELETE");
+ };
+ const resetOwner = async () => {
+ const name = channelName(channel);
+ if (!(await confirmSheet({ title: t("botSettings.access.resetOwnerTitle", { channel: name }), body: t("botSettings.access.resetOwnerBody", { channel: name, who: owner.name }), confirmLabel: t("botSettings.access.reset") }))) return;
+ call(`owner/${channel}`, "DELETE");
+ };
+ const line = (id, name, sub, children) => html`<div class="row" key=${id}><div class="who"><div class="name">${name}</div>${sub && html`<div class="sub">${sub}</div>`}</div><div class="ctl">${children}</div></div>`;
+ return html`<div class="list-head">${t("botSettings.access.head")}${requests.length > 0 && html`<span class="badge count warn">${requests.length}</span>`}</div>
+ ${requests.map((r) => html`<div key=${r.id} class="card">
+ <div class="meta"><span>${t("info.access.wants", { code: html`<span class="num">${r.code}</span>` })}</span> <span class="hint">${fmtAgo(r.createdAt)}</span></div>
+ <div class="q">${r.who}</div>
+ ${r.text && html`<div class="q-detail selectable">${t("info.access.quote", { text: r.text })}</div>`}
+ <div class="actions">
+ <${Button} variant="primary" loading=${busy === r.id + "approve"} disabled=${!!busy} onClick=${() => decide(r, "approve")}>${t("info.access.allow")}</${Button}>
+ <${Button} loading=${busy === r.id + "deny"} disabled=${!!busy} onClick=${() => decide(r, "deny")}>${t("info.access.deny")}</${Button}>
+ </div>
+ </div>`)}
+ <div class="list">
+ ${line("policy", t("botSettings.access.policy"))}
+ ${owner && line("owner", t("botSettings.access.owner", { channel: channelName(channel) }), owner.name, owner.via !== "login" && html`<button type="button" class="text" onClick=${resetOwner}>${t("botSettings.access.reset")}</button>`)}
+ ${allowed.map((e) => line(e.id, e.who, [sourceLabel(e.source), e.decidedAt ? fmtAgo(e.decidedAt) : ""].filter(Boolean).join(" · "), html`<button type="button" class="text danger" onClick=${() => remove(e)}>${t("botSettings.access.remove")}</button>`))}
+ ${denied.map((e) => line(e.id, e.who, t("botSettings.access.deniedSub", { when: fmtAgo(e.decidedAt) }), html`<button type="button" class="text accent" onClick=${() => call(`${encodeURIComponent(e.id)}/approve`, "POST")}>${t("botSettings.access.allow")}</button>
+ <button type="button" class="text" onClick=${() => remove(e)}>${t("botSettings.access.remove")}</button>`))}
+ </div>`;
+}
+
+/** 微信:扫码登录。账号在扫码成功后才出现 */
+function WeixinConnect({ accountKey, st, reload }) {
+ const [code2, setCode] = useState("");
+ const login = st?.login;
+ const active = login && ACTIVE_LOGIN.includes(login.state);
+ const base = `/channel-accounts/${encodeURIComponent(accountKey)}/weixin`;
+ useEffect(() => {
+ if (!active) return;
+ const timer = setInterval(reload, 1500);
+ return () => clearInterval(timer);
+ }, [active]);
+ const call = (path, body = {}) => api(base + path, { method: "POST", body }).then(reload).catch(failed);
+ return html`${login && login.state !== "idle" && html`<div class="actions"><${Badge} s=${login.state} /><span class="hint">${login.message}</span></div>`}
+ ${active && login.qrDataUrl && html`<img class="panel-qr" src=${login.qrDataUrl} alt=${t("info.weixin.qrAlt")} /><p class="hint">${t("info.weixin.scanHint")}</p>`}
+ ${login && login.state === "need_verifycode" && html`<div class="actions"><input class="field" style="width:140px" placeholder=${t("info.weixin.verifyCode")} value=${code2} onInput=${(e) => setCode(e.target.value)} />
+ <button type="button" class="btn" onClick=${() => call("/verify", { code: code2 }).then(() => setCode(""))}>${t("info.weixin.submit")}</button></div>`}
+ ${st?.account && st.account.pausedUntil > Date.now() && html`<p class="hint">${t("info.weixin.pausedUntil", { time: fmtTime(st.account.pausedUntil) })}</p>`}
+ <div class="actions">
+ ${active
+ ? html`<button type="button" class="btn" onClick=${() => call("/cancel")}>${t("common.cancel")}</button>`
+ : html`<button type="button" class="btn primary" onClick=${() => call("/login")}>${st?.account ? t("info.weixin.relogin") : t("info.weixin.login")}</button>`}
+ </div>
+ ${st?.quota && st.quota.length > 0 && html`<p class="hint">${t("info.weixin.quota", { list: st.quota.map((q) => t("info.weixin.quotaItem", { user: q.userId.slice(0, 8), count: q.remaining })).join(t("info.weixin.quotaSep")) })}</p>`}`;
+}
+
+/** 飞书、Telegram、Slack、Discord:填凭据连上。已保存的留空表示不改 */
+function CredentialConnect({ accountKey, channel, st, reload }) {
+ const [values, setValues] = useState({});
+ const [busy, setBusy] = useState(false);
+ const feishu = channel === "feishu";
+ const fields = feishu ? [{ key: "appId", label: "App ID", placeholder: "cli_xxxxxxxx", plain: true }, { key: "appSecret", label: "App Secret", placeholder: "" }] : MESSENGER_FIELDS[channel].map((f) => ({ ...f, label: t(`info.messenger.${channel}.${f.key}`) }));
+ const account = st?.account;
+ const saved0 = (key) => account?.saved?.[key];
+ const value = (f) => values[f.key] ?? (f.plain ? account?.appId ?? "" : "");
+ const filled = (f) => !!value(f).trim();
+ const ready = account ? fields.some((f) => (values[f.key] || "").trim()) : fields.every(filled);
+ const save = async (e) => {
+ e.preventDefault();
+ setBusy(true);
+ try {
+ await api(`/channel-accounts/${encodeURIComponent(accountKey)}/${channel}`, { method: "PUT", body: feishu ? { appId: value(fields[0]).trim(), appSecret: (values.appSecret || "").trim() } : values });
+ setValues({});
+ saved();
+ reload();
+ } catch (err) {
+ failed(err);
+ }
+ setBusy(false);
+ };
+ return html`<form onSubmit=${save}>
+ ${fields.map((f) => html`<label class="set-field" key=${f.key}><span class="k">${f.label}${saved0(f.key) && html`<span class="hint">${t("info.messenger.secretSaved", { masked: saved0(f.key) })}</span>`}</span>
+ <input class="field mono" type=${f.plain ? "text" : "password"} autocomplete="off" spellcheck="false" placeholder=${f.placeholder} value=${value(f)} onInput=${(ev) => setValues((v) => ({ ...v, [f.key]: ev.target.value }))} />
+ </label>`)}
+ <div class="actions"><button type="submit" class="btn primary" disabled=${!ready || busy}>${busy ? html`<${Spinner} />` : t("info.messenger.saveConnect")}</button></div>
+ <p class="hint">${feishu ? t("info.feishu.setupHint", FEISHU_HINT()) : t(`info.messenger.${channel}.setupHint`, MESSENGER_HINT[channel]())}</p>
+ </form>`;
+}
+
+/** 管理一个渠道账号(别名、默认机器人、凭据、谁能用),或添加新账号(key 先要一个,连上才真的存) */
+function ChannelSheet({ conn, bots, channel, accountKey, onClose }) {
+ const [key, setKey] = useState(accountKey || "");
+ const [st, setSt] = useState(null);
+ const account = conn.channelAccounts.find((a) => a.key === key && a.channel === channel);
+ const [label, setLabel] = useState(account?.label ?? "");
+ const reload = () => {
+ conn.reloadChannels();
+ if (key) api(`/channel-accounts/${encodeURIComponent(key)}/channels`).then((r) => setSt(r[channel])).catch(() => {});
+ };
+ useEffect(() => {
+ if (!key) api("/channel-accounts/new-key", { method: "POST", body: {} }).then((r) => setKey(r.key)).catch(failed);
+ else reload();
+ }, [key]);
+ useEffect(() => {
+ if (account) setLabel(account.label);
+ }, [account?.label]);
+ const put = async (body) => {
+ try {
+ conn.setChannelAccounts((await api(`/channel-accounts/${encodeURIComponent(key)}/${channel}/settings`, { method: "PUT", body })).accounts);
+ saved();
+ } catch (e) {
+ failed(e);
+ if (account) setLabel(account.label);
+ }
+ };
+ const remove = async () => {
+ if (!(await confirmSheet({ title: t("settings.connections.removeTitle", { name: account.label }), body: t("settings.connections.removeChannelBody"), confirmLabel: t("settings.connections.remove"), danger: true }))) return;
+ try {
+ await api(`/channel-accounts/${encodeURIComponent(key)}/${channel}`, { method: "DELETE" });
+ conn.reloadChannels();
+ saved();
+ onClose();
+ } catch (e) {
+ failed(e);
+ }
+ };
+ const title = account ? `${channelName(channel)} ${account.number} · ${account.label}` : t("settings.connections.addChannelTitle", { channel: channelName(channel) });
+ return html`<${Sheet} title=${title} wide onClose=${onClose}>
+ ${account && html`<label class="set-field"><span class="k">${t("settings.connections.nameLabel")}</span>
+ <input class="field" maxlength="80" value=${label} onInput=${(e) => setLabel(e.target.value)} onBlur=${() => label.trim() !== account.label && put({ label: label.trim() })} />
+ </label>
+ <div class="set-field"><span class="k">${t("settings.connections.defaultBot")}</span>
+ <${MenuButton} label=${t("settings.connections.defaultBot")} value=${account.defaultBot} width=${260} options=${(bots || []).map((b) => [b.id, b.name])} onChange=${(v) => put({ defaultBot: v })} />
+ <p class="hint">${t("settings.connections.defaultBotHint")}</p>
+ </div>`}
+ ${key && (channel === "weixin"
+ ? html`<${WeixinConnect} accountKey=${key} st=${st} reload=${reload} />`
+ : html`<${CredentialConnect} key=${key} accountKey=${key} channel=${channel} st=${st} reload=${reload} />`)}
+ ${account && html`<${AccessPanel} accountKey=${key} channel=${channel} onChanged=${conn.reloadChannels} />
+ <div class="actions"><button type="button" class="text danger" onClick=${remove}>${t("settings.connections.removeAccount")}</button></div>`}
+ <//>`;
+}
+
+export function ConnectionSheets({ conn, bots }) {
const { sheet, setSheet } = conn;
const close = () => setSheet(null);
if (!sheet) return null;
+ if (sheet.kind === "channel") return html`<${ChannelSheet} key=${`${sheet.channel}-${sheet.accountKey ?? "new"}`} conn=${conn} bots=${bots} channel=${sheet.channel} accountKey=${sheet.accountKey} onClose=${close} />`;
if (sheet.kind === "notion-oauth") return html`<${NotionOAuthSheet} conn=${conn} onClose=${close} />`;
if (sheet.kind === "notion-token") return html`<${NotionTokenSheet} conn=${conn} onClose=${close} />`;
if (sheet.kind === "feishu") return html`<${FeishuSheet} conn=${conn} mode=${sheet.mode} onClose=${close} />`;
diff --git a/ui/screens/info-panel.js b/ui/screens/info-panel.js
index c5a3348..6eee135 100644
--- a/ui/screens/info-panel.js
+++ b/ui/screens/info-panel.js
@@ -1,13 +1,12 @@
// 信息面板:点悬浮胶囊或 ⌘⇧I 打开,面板自己的 ✕ 关闭,⚙ 进机器人设置。
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
-import { html, Icon, Badge, Button, Sheet, Spinner, Skeleton } from "../components/ui.js";
+import { html, Icon, Badge, Button, Sheet, Skeleton } from "../components/ui.js";
import { ActivityLine, currentStep, useNow } from "../components/activity.js";
import { PromptCard } from "./chat.js";
import { api } from "../lib/api.js";
-import { confirmSheet, failed, saved, toast } from "../lib/store.js";
+import { confirmSheet, failed, toast } from "../lib/store.js";
import { markDone } from "../lib/guide.js";
import { fmtAgo, fmtClock, fmtDur, fmtTime } from "../lib/format.js";
-import { channelName as accessChannel } from "../lib/access.js";
import { PausedLine, TaskGroup } from "../components/tasks.js";
import { DeliveredFiles } from "../components/files.js";
import { t } from "../lib/i18n.js";
@@ -28,181 +27,6 @@ export function usePoll(fn, ms, deps = []) {
/** 渠道名(渲染时取,跟着界面语言);不认识的渠道原样显示 id */
const channelName = (c) => ({ web: t("info.channel.web"), feishu: t("info.channel.feishu"), weixin: t("info.channel.weixin"), telegram: t("info.channel.telegram"), slack: t("info.channel.slack"), discord: t("info.channel.discord") })[c];
-/** Telegram、Slack、Discord:填 token 连上。key 和后端 MESSENGER_FIELDS 对应 */
-const MESSENGER_FIELDS = {
- telegram: [{ key: "token", placeholder: "123456789:AA…" }],
- slack: [{ key: "botToken", placeholder: "xoxb-…" }, { key: "appToken", placeholder: "xapp-…" }],
- discord: [{ key: "token", placeholder: "" }],
-};
-/** 接入说明里 <code> 包着的权限名、事件名 */
-const code = (s) => html`<code>${s}</code>`;
-const MESSENGER_HINT = {
- telegram: () => ({ bot: code("@BotFather"), cmd: code("/newbot") }),
- slack: () => ({ conn: code("connections:write"), s1: code("chat:write"), s2: code("im:history"), s3: code("files:read"), s4: code("files:write"), event: code("message.im") }),
- discord: () => ({}),
-};
-
-function MessengerRow({ bot, id, st, owner, reload }) {
- const [open, setOpen] = useState(false);
- const [values, setValues] = useState({});
- const [busy, setBusy] = useState(false);
- const fields = MESSENGER_FIELDS[id];
- const account = st.account;
- const name = channelName(id);
- // 第一次连接要填全;已保存的留空表示不改
- const ready = account ? fields.some((f) => (values[f.key] || "").trim()) : fields.every((f) => (values[f.key] || "").trim());
- const save = async () => {
- setBusy(true);
- try {
- await api(`/bots/${bot.id}/${id}`, { method: "PUT", body: values });
- setValues({});
- saved();
- reload();
- } catch (e) {
- failed(e);
- }
- setBusy(false);
- };
- const clear = async () => {
- if (!(await confirmSheet({ title: t("info.messenger.disconnectTitle", { channel: name }), body: t("info.messenger.disconnectBody", { channel: name }), confirmLabel: t("info.messenger.disconnect"), danger: true }))) return;
- try {
- await api(`/bots/${bot.id}/${id}`, { method: "DELETE" });
- setValues({});
- reload();
- } catch (e) {
- failed(e);
- }
- };
- return html`<div class="row clickable" onClick=${() => setOpen((v) => !v)} role="button" tabindex="0" aria-expanded=${open}
- onKeyDown=${(e) => (e.key === "Enter" || e.key === " ") && (e.preventDefault(), setOpen((v) => !v))}>
- <div class="who"><div class="name">${name}</div><div class="sub">${st.detail || (account && account.name) || t(`info.messenger.${id}.sub`)}</div></div>
- <${Badge} s=${st.state} />
- </div>
- ${open && html`<div class="row-edit">
- ${fields.map((f) => html`<label key=${f.key}>${t(`info.messenger.${id}.${f.key}`)}${account && account.saved[f.key] && html`<span class="hint">${t("info.messenger.secretSaved", { masked: account.saved[f.key] })}</span>`}
- <input class="field mono" type="password" autocomplete="off" placeholder=${f.placeholder} value=${values[f.key] || ""} onInput=${(e) => setValues((v) => ({ ...v, [f.key]: e.target.value }))} /></label>`)}
- <div class="actions">
- <button type="button" class="btn primary" disabled=${!ready || busy} onClick=${save}>${busy ? html`<${Spinner} />` : t("info.messenger.saveConnect")}</button>
- ${account && html`<button type="button" class="text danger" onClick=${clear}>${t("info.messenger.disconnect")}</button>`}
- </div>
- ${account && owner === null && html`<p class="hint">${t("info.messenger.bindHint")}</p>`}
- <p class="hint">${t(`info.messenger.${id}.setupHint`, MESSENGER_HINT[id]())}</p>
- </div>`}`;
-}
-
-function FeishuRow({ bot, st, owner, reload }) {
- const [open, setOpen] = useState(false);
- const [appId, setAppId] = useState(bot.feishuAppId);
- const [secret, setSecret] = useState("");
- const [busy, setBusy] = useState(false);
- useEffect(() => setAppId(bot.feishuAppId), [bot.id, bot.feishuAppId]);
- const save = async () => {
- setBusy(true);
- try {
- await api(`/bots/${bot.id}/feishu`, { method: "PUT", body: { appId, appSecret: secret } });
- setSecret("");
- saved();
- reload();
- } catch (e) {
- failed(e);
- }
- setBusy(false);
- };
- const clear = async () => {
- if (!(await confirmSheet({ title: t("info.feishu.disconnectTitle"), body: t("info.feishu.disconnectBody"), confirmLabel: t("info.feishu.disconnect"), danger: true }))) return;
- try {
- await api(`/bots/${bot.id}/feishu`, { method: "DELETE" });
- setAppId("");
- reload();
- } catch (e) {
- failed(e);
- }
- };
- return html`<div class="row clickable" onClick=${() => setOpen((v) => !v)} role="button" tabindex="0" aria-expanded=${open}
- onKeyDown=${(e) => (e.key === "Enter" || e.key === " ") && (e.preventDefault(), setOpen((v) => !v))}>
- <div class="who"><div class="name">${t("info.channel.feishu")}</div><div class="sub">${st.detail || (bot.feishuAppId ? bot.feishuAppId : t("info.feishu.sub"))}</div></div>
- <${Badge} s=${st.state} />
- </div>
- ${open && html`<div class="row-edit">
- <label>App ID<input class="field mono" value=${appId} placeholder="cli_xxxxxxxx" onInput=${(e) => setAppId(e.target.value)} /></label>
- <label>App Secret${bot.feishuAppSecretMasked && html`<span class="hint">${t("info.feishu.secretSaved", { masked: bot.feishuAppSecretMasked })}</span>`}
- <input class="field mono" type="password" autocomplete="off" value=${secret} onInput=${(e) => setSecret(e.target.value)} /></label>
- <div class="actions">
- <button type="button" class="btn primary" disabled=${!appId.trim() || busy} onClick=${save}>${busy ? html`<${Spinner} />` : t("info.feishu.saveConnect")}</button>
- ${bot.feishuAppId && html`<button type="button" class="text danger" onClick=${clear}>${t("info.feishu.disconnect")}</button>`}
- </div>
- ${bot.feishuAppId && owner === null && html`<p class="hint">${t("info.feishu.bindHint")}</p>`}
- <p class="hint">${t("info.feishu.setupHint", { event: html`<code>im.message.receive_v1</code>`, p1: html`<code>im:message.p2p_msg:readonly</code>`, p2: html`<code>im:message:send_as_bot</code>`, p3: html`<code>cardkit:card:write</code>`, p4: html`<code>im:message.history:readonly</code>` })}</p>
- </div>`}`;
-}
-
-function WeixinRow({ bot, st, reload }) {
- const [open, setOpen] = useState(false);
- const [code, setCode] = useState("");
- const login = st.login;
- const active = login && ["fetching", "wait", "scaned", "need_verifycode"].includes(login.state);
- useEffect(() => {
- if (!active) return;
- setOpen(true);
- const timer = setInterval(reload, 1500);
- return () => clearInterval(timer);
- }, [active]);
- const call = (path, body = {}) => api(`/bots/${bot.id}/weixin${path}`, { method: path ? "POST" : "PUT", body }).then(reload).catch(failed);
- const logout = async () => {
- if (await confirmSheet({ title: t("info.weixin.unlinkTitle"), body: t("info.weixin.unlinkBody"), confirmLabel: t("info.weixin.unlink"), danger: true })) call("/logout");
- };
- return html`<div class="row clickable" data-guide="weixin" onClick=${() => setOpen((v) => !v)} role="button" tabindex="0" aria-expanded=${open}
- onKeyDown=${(e) => (e.key === "Enter" || e.key === " ") && (e.preventDefault(), setOpen((v) => !v))}>
- <div class="who"><div class="name">${t("info.channel.weixin")}</div><div class="sub">${st.account ? t("info.weixin.linked", { id: st.account.ilinkBotId }) : st.detail || t("info.weixin.sub")}</div></div>
- <${Badge} s=${st.state} />
- </div>
- ${open && html`<div class="row-edit">
- ${login && login.state !== "idle" && html`<div class="actions"><${Badge} s=${login.state} /><span class="hint">${login.message}</span></div>`}
- ${active && login.qrDataUrl && html`<img class="panel-qr" src=${login.qrDataUrl} alt=${t("info.weixin.qrAlt")} />
- <p class="hint">${t("info.weixin.scanHint")}</p>`}
- ${login && login.state === "need_verifycode" && html`<div class="actions"><input class="field" style="width:140px" placeholder=${t("info.weixin.verifyCode")} value=${code} onInput=${(e) => setCode(e.target.value)} />
- <button type="button" class="btn" onClick=${() => call("/verify", { code }).then(() => setCode(""))}>${t("info.weixin.submit")}</button></div>`}
- ${st.account && st.account.pausedUntil > Date.now() && html`<p class="hint">${t("info.weixin.pausedUntil", { time: fmtTime(st.account.pausedUntil) })}</p>`}
- <div class="actions">
- ${active ? html`<button type="button" class="btn" onClick=${() => call("/cancel")}>${t("common.cancel")}</button>` : html`<button type="button" class="btn primary" onClick=${() => call("/login")}>${st.account ? t("info.weixin.relogin") : t("info.weixin.login")}</button>`}
- <button type="button" class="text" onClick=${() => call("", { enabled: !bot.weixinEnabled })}>${bot.weixinEnabled ? t("info.weixin.disable") : t("info.weixin.enable")}</button>
- ${st.account && html`<button type="button" class="text danger" onClick=${logout}>${t("info.weixin.unlink")}</button>`}
- </div>
- ${st.quota && st.quota.length > 0 && html`<p class="hint">${t("info.weixin.quota", { list: st.quota.map((q) => t("info.weixin.quotaItem", { user: q.userId.slice(0, 8), count: q.remaining })).join(t("info.weixin.quotaSep")) })}</p>`}
- </div>`}`;
-}
-
-/** 使用请求:不在允许名单里的人给机器人发了消息(他只收到一句"还没被允许",没有调用模型)。允许 / 拒绝。 */
-function AccessRequests({ botId, data, reload }) {
- const [busy, setBusy] = useState("");
- if (!data || !data.requests.length) return null;
- const act = async (r, what) => {
- setBusy(r.id + what);
- try {
- await api(`/bots/${botId}/access/${encodeURIComponent(r.id)}/${what}`, { method: "POST", body: {} });
- toast(t(what === "approve" ? "info.access.allowed" : "info.access.denied", { who: r.who }));
- } catch (e) {
- failed(e);
- }
- setBusy("");
- reload();
- };
- return html`<div class="list-head">${t("info.access.head")}<span class="badge count warn">${data.requests.length}</span></div>
- <div class="stack">${data.requests.map((r) => html`<div key=${r.id} class="stack approval" style="--gap: var(--space-1)">
- <span class="hint">${accessChannel(r.channel)} · ${fmtAgo(r.createdAt)}${r.requests > 1 ? ` · ${t("info.access.messages", { count: r.requests })}` : ""}</span>
- <div class="card">
- <div class="meta"><span>${t("info.access.wants", { code: html`<span class="num">${r.code}</span>` })}</span></div>
- <div class="q">${r.who}</div>
- ${r.text && html`<div class="q-detail selectable">${t("info.access.quote", { text: r.text })}</div>`}
- <div class="actions">
- <${Button} variant="primary" loading=${busy === r.id + "approve"} disabled=${!!busy} onClick=${() => act(r, "approve")}>${t("info.access.allow")}</${Button}>
- <${Button} loading=${busy === r.id + "deny"} disabled=${!!busy} onClick=${() => act(r, "deny")}>${t("info.access.deny")}</${Button}>
- </div>
- <span class="hint">${t("info.access.replyHint", { code: r.code })}</span>
- </div>
- </div>`)}</div>`;
-}
-
function MemorySection({ botId }) {
const [d, err, reload] = usePoll(() => api(`/bots/${botId}/memory`), 0, [botId]);
const forget = async (sc, text, topic) => {
@@ -284,20 +108,20 @@ function ConversationSheet({ conv, onClose }) {
<//>`;
}
-export function InfoPanel({ bot, leaving, onClose, onOpenBotSettings, onOpenChat }) {
+export function InfoPanel({ bot, leaving, onClose, onOpenBotSettings, onOpenChat, onOpenConnections }) {
const [detail, , reloadDetail] = usePoll(() => api(`/bots/${bot.id}`), 5000, [bot.id]);
+ const [channels] = usePoll(() => api("/channel-accounts"), 5000, []);
const [appr, , reloadAppr] = usePoll(() => api(`/approvals?status=pending&bot=${encodeURIComponent(bot.id)}`), 4000, [bot.id]);
const [convs] = usePoll(() => api(`/conversations?bot=${encodeURIComponent(bot.id)}`), 8000, [bot.id]);
- const [access, , reloadAccess] = usePoll(() => api(`/bots/${encodeURIComponent(bot.id)}/access`), 4000, [bot.id]);
const [viewing, setViewing] = useState(null);
// 任务来自的会话:网页的就是这里的对话,微信、飞书的在会话记录里看
const openConv = (task) => (task.channel === "web" ? onOpenChat() : setViewing((convs?.conversations || []).find((c) => c.id === task.conversationId) || null));
const pending = (appr && appr.approvals) || [];
- // 上手清单:微信扫码绑定了,或飞书、Telegram、Slack、Discord 连上了,就算接好了渠道
+ // 上手清单:加了任何一个聊天渠道账号,就算接好了渠道
+ const mine = (channels?.accounts || []).filter((a) => a.defaultBot === bot.id);
useEffect(() => {
- const ch = detail && detail.channels;
- if (ch && (ch.weixin.account || ["feishu", "telegram", "slack", "discord"].some((c) => ch[c] && ch[c].state === "connected"))) markDone("weixin");
- }, [detail]);
+ if (channels?.accounts?.length) markDone("weixin");
+ }, [channels]);
// leaving:关上后还在播滑出的那一小会儿(main.js 的 usePresence),不再接收操作
return html`<aside class=${`panel${leaving ? " leaving" : ""}`} aria-label=${t("info.aria")} inert=${leaving || undefined}>
<div class="panel-head">
@@ -309,13 +133,15 @@ export function InfoPanel({ bot, leaving, onClose, onOpenBotSettings, onOpenChat
${detail?.bot?.settings?.paused && html`<${PausedLine} onResume=${async () => (await api(`/bots/${bot.id}/settings`, { method: "PUT", body: { paused: false } }), reloadDetail())} />`}
<div class="list-head">${t("info.channels")}</div>
<div class="list">
- ${detail && detail.bot
- ? 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} reload=${reloadDetail} />${["telegram", "slack", "discord"].map((id) => html`<${MessengerRow} key=${id} bot=${detail.bot} id=${id} st=${detail.channels[id]} owner=${access ? access.owners[id] : undefined} reload=${reloadDetail} />`)}`
- : html`<div class="row"><${Skeleton} w="50%" /></div><div class="row"><${Skeleton} w="40%" /></div>`}
+ ${mine.map((a) => html`<div key=${`${a.channel}-${a.key}`} class="row clickable" role="button" tabindex="0" onClick=${onOpenConnections} onKeyDown=${(e) => e.key === "Enter" && onOpenConnections()}>
+ <div class="who"><div class="name">${channelName(a.channel)} · ${a.label}</div><div class="sub">${a.status?.detail || t("info.channelsDefault")}</div></div>
+ <${Badge} s=${a.status?.state} />
+ </div>`)}
+ <div class="row clickable" data-guide="weixin" role="button" tabindex="0" onClick=${onOpenConnections} onKeyDown=${(e) => e.key === "Enter" && onOpenConnections()}>
+ <div class="who"><div class="name">${t("info.channelsManage")}</div><div class="sub">${t("info.channelsSub")}</div></div>
+ </div>
</div>
- <${AccessRequests} botId=${bot.id} data=${access} reload=${reloadAccess} />
-
<div class="list-head">${t("info.approvals")}${pending.length > 0 && html`<span class="badge count warn">${pending.length}</span>`}</div>
${pending.length
? html`<div class="stack">${pending.map((a) => html`<div key=${a.id} class="stack approval" style="--gap: var(--space-1)">
diff --git a/ui/screens/settings.js b/ui/screens/settings.js
index 3febab5..6a6a194 100644
--- a/ui/screens/settings.js
+++ b/ui/screens/settings.js
@@ -405,7 +405,7 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, onTab, focusRow,
{ tab: "privacy", id: "sandbox", name: t("settings.rows.sandbox.name"), sub: t("settings.rows.sandbox.sub"), ctl: null, keys: t("settings.rows.sandbox.keys") },
{ tab: "privacy", id: "screens", name: t("settings.rows.screens.name"), sub: t("settings.rows.screens.sub"), ctl: null, keys: t("settings.rows.screens.keys") },
- ...connectionRows(conn),
+ ...connectionRows(conn, bots),
{ tab: "network", id: "web-search", name: t("settings.rows.webSearch.name"), sub: t("settings.rows.webSearch.sub"), keys: t("settings.rows.webSearch.keys"),
ctl: html`<${MenuButton} label=${t("settings.rows.webSearch.name")} value=${s.webSearch.provider} width=${200} options=${SEARCH_OPTIONS()} onChange=${(v) => putSearch({ provider: v })} />` },
s.webSearch.provider === "searxng" && { tab: "network", id: "web-search-url", name: t("settings.rows.webSearchUrl.name"), keys: t("settings.rows.webSearchUrl.keys"),
@@ -437,7 +437,7 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, onTab, focusRow,
{ tab: "about", id: "links", name: "Modelflare", sub: t("settings.rows.links.sub"),
ctl: html`<a class="text" href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">modelflare.dev ↗</a><a class="text" href=${MF_DOCS_LINK} target="_blank" rel="noopener noreferrer">${t("settings.rows.links.docs")}</a>` },
].filter(Boolean);
- }, [s, mf, mode, p, models, modelsError, cu, status, bots, acct, invite, unread, g, media, lang, langPref, conn.accounts]);
+ }, [s, mf, mode, p, models, modelsError, cu, status, bots, acct, invite, unread, g, media, lang, langPref, conn.accounts, conn.channelAccounts]);
const needle = q.trim().toLowerCase();
const shown = needle ? rows.filter((r) => `${r.name} ${r.sub || ""} ${r.keys || ""}`.toLowerCase().includes(needle)) : rows.filter((r) => r.tab === tab);
@@ -458,7 +458,7 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, onTab, focusRow,
<${KeyForm} line=${mf.line} showLine=${false} submitLabel=${t("settings.rekey.submit")} onConnected=${() => { setRekey(false); saved(); onMfChanged(); reloadModels(); }} />
<//>`}
${notices && html`<${NoticesSheet} onClose=${() => setNotices(false)} />`}
- <${ConnectionSheets} conn=${conn} />
+ <${ConnectionSheets} conn=${conn} bots=${bots} />
${sheet === "login" && html`<${LoginSheet} onClose=${() => setSheet("")} onSignedIn=${(r) => { onAccount(r); onMfChanged(); reloadModels(); }} />`}
${sheet === "usage" && html`<${UsageSheet} onClose=${() => setSheet("")} />`}
${sheet === "notifications" && html`<${NotificationsSheet} onClose=${() => { setSheet(""); setUnread(null); }} />`}