Skip to content

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

feat(server,web): enabling a messaging connection is the binding (#490)

Yaowei Zhengca5f85db6ab2
diff --git a/changelog/unreleased/2026-08-26-backward-compatibility.md b/changelog/unreleased/2026-08-26-backward-compatibility.md
new file mode 100644
index 00000000..7f2ef74f
--- /dev/null
+++ b/changelog/unreleased/2026-08-26-backward-compatibility.md
@@ -0,0 +1,62 @@
+# Backward compatibility
+
+- **Date:** 2026-08-26
+- **Type:** process
+- **Scope:** `server`
+- **PR:** [#490](https://github.com/Prism-Shadow/penguin-harness/pull/490)
+- **Breaking:** yes — one-way for the database: after two Sessions have saved the same bot account, a build from before this change can no longer open that `web.db`
+
+[中文版](2026-08-26-backward-compatibility.zh.md)
+
+This batch touches one piece of existing state: the `idx_messaging_account` unique index on
+`messaging_bindings`, carried by every `web.db` that has opened a build with messaging bindings in
+it (0.2.5 and later).
+
+## The retired unique account index
+
+The index made `(channel, account_id)` unique across the whole table, which is how a bot account
+belonged to one Session forever. With [enabling as the binding](2026-08-26-messaging-bind-by-enable.md),
+several Sessions may keep the same account saved and the index would reject the second save. Left
+in place it would turn the new behaviour into a SQLite constraint error on an ordinary save.
+
+Chosen: **drop it on open**, one `DROP INDEX IF EXISTS idx_messaging_account` next to the existing
+`idx_usage_session` drop in `openDatabase`. `SCHEMA_SQL` creates `idx_messaging_by_account` over
+the same two columns in the same open, so the by-account lookup the enable guard performs stays
+indexed and no query plan changes. Dropping is safe because an index is derived and never data:
+every row survives untouched, and a database that never had the index is unaffected (the statement
+is a no-op).
+
+Nothing is asked of the user: the drop is automatic, runs on the first open of an updated build,
+and no binding, credential or remembered chat is altered.
+
+## The one-way half
+
+The drop cannot be undone by an older build. A build from before this change recreates the unique
+index as part of its own `SCHEMA_SQL`, and that `CREATE UNIQUE INDEX` fails once duplicate
+`(channel, account_id)` rows exist — which they will as soon as a second Session saves the same
+bot. `openDatabase` runs the schema before anything else, so the failure is at open: the older
+build does not start against that database at all. Downgrading after using the new behaviour
+therefore means deleting the duplicate binding rows first, keeping one Session's row per account.
+A database on which no account was ever saved twice downgrades with no work.
+
+## How long the tolerance stays
+
+The `DROP INDEX` line is load-bearing for as long as a `web.db` formed by 0.2.5 through 0.2.7 can
+still be opened by a current build — in practice indefinitely, at the cost of one no-op statement
+per open. It is removed only in a release that is allowed to break existing `web.db` files, and it
+should be removed together with the `idx_usage_session` drop that sits beside it, since both are
+the same kind of debt.
+
+## Compatibility
+
+No action is required. The first open of an updated build drops the index; bindings, credentials
+and remembered chats are untouched, and a user who never saves one bot on two Sessions cannot tell
+the difference.
+
+Before downgrading to a build from before this change, remove the extra rows if any account is now
+saved on more than one Session — otherwise the older server fails to open the database. Check with:
+
+```sql
+SELECT channel, account_id, COUNT(*) FROM messaging_bindings
+GROUP BY channel, account_id HAVING COUNT(*) > 1;
+```
diff --git a/changelog/unreleased/2026-08-26-backward-compatibility.zh.md b/changelog/unreleased/2026-08-26-backward-compatibility.zh.md
new file mode 100644
index 00000000..97bf53b5
--- /dev/null
+++ b/changelog/unreleased/2026-08-26-backward-compatibility.zh.md
@@ -0,0 +1,54 @@
+# 向后兼容
+
+- **Date:** 2026-08-26
+- **Type:** process
+- **Scope:** `server`
+- **PR:** [#490](https://github.com/Prism-Shadow/penguin-harness/pull/490)
+- **Breaking:** yes — 对数据库是单向的:一旦两个 Session 保存了同一个机器人账号,本次改动之前的构建就再也打不开那个 `web.db`
+
+[English](2026-08-26-backward-compatibility.md)
+
+本批改动触及一处存量状态:`messaging_bindings` 上的 `idx_messaging_account` 唯一索引——凡是打开
+过带消息绑定的构建(0.2.5 及以后)的 `web.db` 都带有它。
+
+## 退役的账号唯一索引
+
+该索引让 `(channel, account_id)` 在全表唯一,这正是「一个机器人账号永久归属于一个 Session」的实
+现方式。改为[启用即绑定](2026-08-26-messaging-bind-by-enable.zh.md)之后,多个 Session 可以同时保
+存同一个账号,而该索引会拒绝第二次保存。若保留不动,新行为会在一次普通保存上变成 SQLite 的约束
+错误。
+
+选定方案:**打开时删除**,在 `openDatabase` 中既有的 `idx_usage_session` 删除语句旁加一条
+`DROP INDEX IF EXISTS idx_messaging_account`。同一次打开中 `SCHEMA_SQL` 会在同样的两列上创建
+`idx_messaging_by_account`,因此启用守卫所做的按账号查询仍然走索引,查询计划没有变化。删除是安
+全的,因为索引是派生物而非数据:每一行都原样保留;从未有过该索引的数据库不受影响(该语句是空
+操作)。
+
+用户无需做任何事:删除是自动的,在升级后第一次打开时执行,任何绑定、凭证与记住的会话都不改动。
+
+## 单向的那一半
+
+删除无法被旧构建撤销。本次改动之前的构建会在自己的 `SCHEMA_SQL` 中重新创建该唯一索引,而一旦出
+现重复的 `(channel, account_id)` 行——第二个 Session 保存同一个机器人时就会出现——该
+`CREATE UNIQUE INDEX` 会失败。`openDatabase` 在一切之前先执行 schema,因此失败发生在打开阶段:旧
+构建根本无法对该数据库启动。因此,在使用过新行为之后再降级,需要先删除重复的绑定行,每个账号只
+保留一个 Session 的那一行。从未把同一账号保存两次的数据库降级无需任何操作。
+
+## 这份兼容要留多久
+
+只要当前构建仍需打开 0.2.5 至 0.2.7 形成的 `web.db`,这条 `DROP INDEX` 就是必需的——实际上等于无
+限期保留,代价是每次打开多执行一条空操作语句。它只在允许破坏存量 `web.db` 的版本中移除,并且应
+当与紧挨着它的 `idx_usage_session` 删除语句一并清理,两者属于同一类债务。
+
+## 兼容性
+
+无需任何操作。升级后第一次打开即删除该索引;绑定、凭证与记住的会话都不受影响,从不把同一个机器
+人保存到两个 Session 的用户完全感觉不到差别。
+
+降级到本次改动之前的构建之前,若已有账号被保存在多个 Session 上,请先删除多余的行,否则旧服务端
+无法打开该数据库。可用以下语句检查:
+
+```sql
+SELECT channel, account_id, COUNT(*) FROM messaging_bindings
+GROUP BY channel, account_id HAVING COUNT(*) > 1;
+```
diff --git a/changelog/unreleased/2026-08-26-messaging-bind-by-enable.md b/changelog/unreleased/2026-08-26-messaging-bind-by-enable.md
new file mode 100644
index 00000000..b043214d
--- /dev/null
+++ b/changelog/unreleased/2026-08-26-messaging-bind-by-enable.md
@@ -0,0 +1,45 @@
+# Enabling a messaging connection is the binding
+
+- **Date:** 2026-08-26
+- **Type:** feature
+- **Scope:** `server`, `web`, `docs`
+- **PR:** [#490](https://github.com/Prism-Shadow/penguin-harness/pull/490)
+
+[中文版](2026-08-26-messaging-bind-by-enable.zh.md)
+
+A Feishu app or a Telegram bot used to belong to one Session forever: whichever Session saved its
+credentials first owned it, a second Session's save was refused with 409 `feishu_app_in_use` /
+`telegram_bot_in_use`, and the Web App offered no unbind, so moving a bot to another conversation
+had no path through the product at all. Saving stopped being exclusive: enabling the connection is
+what binds the account to a conversation, and turning that switch off releases it.
+
+## Details
+
+- Saving credentials no longer conflicts across Sessions. Any number of Sessions may keep the same
+ Feishu app or Telegram bot saved side by side, each with its own stored config and its own
+ remembered chat. Both PUTs lost their `_in_use` 409 and `MessagingBindingsRepo.upsert` lost its
+ failure mode.
+- One save is still refused, because it is an enable in disguise: an **enabled** binding
+ re-pointed at an account another Session has enabled answers the same 409
+ `account_enabled_elsewhere`. Such a save restarts the connector on the new credentials, so
+ without the check two Sessions would end up connected to one account having never passed the
+ enable gate. A disabled binding is exempt, which is the whole point of the model.
+- An enabled binding whose Session no longer exists — deleted with its Project or its Agent,
+ neither of which sweeps bindings — is now reconciled when the next enable asks for its account,
+ rather than holding it until the next server start. The refusal names no Session, so an orphan
+ would otherwise point at a connection nobody could reach.
+- Enabling a channel is refused while **another Session has a binding on the same
+ `(channel, account_id)` enabled**: 409 `account_enabled_elsewhere` — turn that one off first.
+ One account has one event stream, so that is the only exclusivity that remains.
+- That refusal says nothing about the Session holding the connection. Authorization is per
+ Project and the route proved access to the caller's Session only, so the holder may sit in a
+ Project the caller cannot see; the remedy does not depend on hearing it named.
+- The per-Session rule is unchanged: at most one of a Session's own channels is enabled at a time
+ (409 `another_channel_enabled`).
+- In the binding editor, the connection switch carries the new meaning as its own tooltip, and the
+ "what binding does" fold states how one bot moves between conversations without a credential
+ being deleted. The two retired error codes left both string dictionaries and
+ `account_enabled_elsewhere` joined them.
+- The unique index `idx_messaging_account` was replaced by a plain `idx_messaging_by_account` over
+ the same columns, and is dropped from databases that already carry it — see
+ [backward compatibility](2026-08-26-backward-compatibility.md).
diff --git a/changelog/unreleased/2026-08-26-messaging-bind-by-enable.zh.md b/changelog/unreleased/2026-08-26-messaging-bind-by-enable.zh.md
new file mode 100644
index 00000000..1d1c5511
--- /dev/null
+++ b/changelog/unreleased/2026-08-26-messaging-bind-by-enable.zh.md
@@ -0,0 +1,37 @@
+# 启用消息连接即是绑定
+
+- **Date:** 2026-08-26
+- **Type:** feature
+- **Scope:** `server`, `web`, `docs`
+- **PR:** [#490](https://github.com/Prism-Shadow/penguin-harness/pull/490)
+
+[English](2026-08-26-messaging-bind-by-enable.md)
+
+一个飞书应用或 Telegram 机器人此前会永久归属于某一个 Session:谁先保存凭据谁就拥有它,第二个
+Session 保存时被 409 `feishu_app_in_use` / `telegram_bot_in_use` 拒绝,而 Web 界面又没有解绑入
+口,因此把机器人换到另一个对话在产品内根本没有路径。现在保存不再互斥:启用连接才是把账号绑定
+到该对话,关掉这个开关即解除绑定。
+
+## 细节
+
+- 保存凭据不再跨 Session 冲突。任意多个 Session 都可以同时保存同一个飞书应用或 Telegram 机器
+ 人,各自持有自己的配置与自己记住的会话。两个 PUT 都去掉了各自的 `_in_use` 409,
+ `MessagingBindingsRepo.upsert` 也不再有失败分支。
+- 仍有一种保存会被拒绝,因为它实质上就是一次启用:把**已启用**的绑定改指到另一个 Session 已启
+ 用的账号上,返回同样的 409 `account_enabled_elsewhere`。这类保存会用新凭据重启连接器,若不做
+ 这道检查,两个 Session 就会在从未经过启用闸门的情况下连到同一个账号上。已停用的绑定不受此限
+ ——那正是这套模型的用意所在。
+- 已启用绑定的 Session 若已不存在(随 Project 或 Agent 一起删除,二者都不会顺带清理绑定),现在
+ 会在下一次有人申请该账号时就地清理,而不必等到下次服务端启动。拒绝信息不点名任何 Session,否
+ 则这样一条残留记录指向的将是一条谁也够不着的连接。
+- 只有当**另一个 Session 已启用同一 `(channel, account_id)` 的绑定**时,启用才被拒绝:409
+ `account_enabled_elsewhere`——先把那一个停用。一个账号只有一条事件流,这也是仅存的互斥。
+- 该拒绝不透露持有连接的 Session 的任何信息。授权按 Project 计,而该路由只验证了调用方自己那个
+ Session 的访问权,持有方可能位于调用方看不到的 Project;而且解决办法并不依赖于知道它是谁。
+- 每个 Session 内部的规则不变:同一时刻至多启用自己的一个渠道(409
+ `another_channel_enabled`)。
+- 绑定编辑器中,连接开关以自身的 tooltip 承载新语义,「绑定后会发生什么」折叠区说明一个机器人
+ 如何在对话之间迁移而无需删除凭证。两个退役错误码从两份字典中移除,`account_enabled_elsewhere`
+ 加入其中。
+- 唯一索引 `idx_messaging_account` 被同列的普通索引 `idx_messaging_by_account` 取代,已带有它的
+ 数据库会在打开时将其删除——参见[向后兼容](2026-08-26-backward-compatibility.zh.md)。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 5a540465..35ff0b46 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -285,25 +285,25 @@ The filename always rides along as `filename*=UTF-8''` with percent-encoding. `p
### Messaging Bindings (Feishu, Telegram)
-A Session can be connected to a messaging bot — Feishu and Telegram are the channels today, each under `/messaging/<channel>`. A Session keeps **at most one saved config per channel** (both may sit saved side by side), and **at most one of them is enabled** — the enabled channel holds the live connection. Inbound messages to the bot start Tasks on the Session as ordinary user input, exactly as if typed into the web composer (no marker, queued as follow-ups while the Session is busy), and completed replies are relayed back to the chat, chunked under the channel's text-size limit (Telegram's hard cap is 4096 characters). Feishu listens over the SDK's WebSocket long connection; Telegram long-polls `getUpdates` — neither needs a public callback URL. Saving and connecting are separate: PUT persists credentials only, and the explicit state endpoint owns the connection. Paths omit the `/api/sessions/:sessionId` prefix like the table above.
+A Session can be connected to a messaging bot — Feishu and Telegram are the channels today, each under `/messaging/<channel>`. A Session keeps **at most one saved config per channel** (both may sit saved side by side), and **at most one of them is enabled** — the enabled channel holds the live connection. Enabling is what binds the bot account to the Session and disabling releases it, so the same app or bot may sit saved on any number of Sessions and only the enable is exclusive. Inbound messages to the bot start Tasks on the Session as ordinary user input, exactly as if typed into the web composer (no marker, queued as follow-ups while the Session is busy), and completed replies are relayed back to the chat, chunked under the channel's text-size limit (Telegram's hard cap is 4096 characters). Feishu listens over the SDK's WebSocket long connection; Telegram long-polls `getUpdates` — neither needs a public callback URL. Saving and connecting are separate: PUT persists credentials only, and the explicit state endpoint owns the connection. Paths omit the `/api/sessions/:sessionId` prefix like the table above.
| Method | Path | Description |
| --- | --- | --- |
| GET | /messaging | Channel-agnostic read: EVERY saved channel config (`channel` discriminant, secrets masked, per-row `enabled` intent + runtime status + `lastChatKnown`). The channel-aware binding editor loads this one |
| GET | /messaging/feishu | The Feishu config in a `{binding, status}` envelope (null when not saved) |
-| PUT | /messaging/feishu | Save credentials: `{appId, appSecret?, baseDomain?, clearAppSecret?}`. An omitted/blank `appSecret` keeps the stored one; `clearAppSecret: true` drops it (a typed secret wins; 409 `messaging_disable_before_clear` while enabled — the cleared config keeps its row and non-secret fields); `baseDomain` defaults to `https://open.feishu.cn`. No connection side effect — except that an **enabled** binding's connector restarts with the new credentials, so stored config and live connection never diverge. 409 `feishu_app_in_use` when the app is bound to another Session |
-| POST | /messaging/feishu/state | The connection toggle: `{enabled}` — enabling connects with the STORED credentials, disabling terminates. 409 `another_channel_enabled` while the Session's other channel is enabled (turn it off first); 400 `feishu_secret_required` when the stored config has no secret. New configs start disabled; server startup connects only enabled ones |
+| PUT | /messaging/feishu | Save credentials: `{appId, appSecret?, baseDomain?, clearAppSecret?}`. An omitted/blank `appSecret` keeps the stored one; `clearAppSecret: true` drops it (a typed secret wins; 409 `messaging_disable_before_clear` while enabled — the cleared config keeps its row and non-secret fields); `baseDomain` defaults to `https://open.feishu.cn`. No connection side effect — except that an **enabled** binding's connector restarts with the new credentials, so stored config and live connection never diverge. A save never conflicts across Sessions, with one exception that follows from that restart: re-pointing an **enabled** binding at an account ANOTHER Session has enabled answers 409 `account_enabled_elsewhere`, because the restart would otherwise carry a second live connection onto it without passing the enable gate |
+| POST | /messaging/feishu/state | The connection toggle: `{enabled}` — enabling connects with the STORED credentials, disabling terminates. 409 `another_channel_enabled` while the Session's other channel is enabled, 409 `account_enabled_elsewhere` while ANOTHER Session has the same account enabled (both mean: turn that one off first — the second names nothing about the holder, which may sit in a Project the caller cannot see); 400 `feishu_secret_required` when the stored config has no secret. New configs start disabled; server startup connects only enabled ones |
| DELETE | /messaging/feishu | Remove this channel's config entirely (App Secret included; the other channel is untouched). API completeness only — the web UI's removal affordance is the clear flag |
| POST | /messaging/feishu/test | Credential probe with the request's draft values, each falling back to the stored config → `{ok, latencyMs?, error?}` (a rejected credential is `ok: false`, not an HTTP error) |
| POST | /messaging/feishu/test-message | Send a short fixed text to the last known chat; 409 `feishu_no_chat` until the bot has been messaged once in Feishu |
| GET | /messaging/telegram | The Telegram config in the same envelope (`botId`, `botTokenMasked`) |
-| PUT | /messaging/telegram | Save the credential: `{botToken?, clearBotToken?}` — the whole credential is the one `<bot id>:<secret>` token from @BotFather (omitted/blank keeps the stored one; 400 `telegram_token_invalid` when the numeric id cannot be read; the clear flag works like Feishu's and the cleared config keeps its bot identity). Same save/enable split. 409 `telegram_bot_in_use` when the bot id is bound to another Session |
+| PUT | /messaging/telegram | Save the credential: `{botToken?, clearBotToken?}` — the whole credential is the one `<bot id>:<secret>` token from @BotFather (omitted/blank keeps the stored one; 400 `telegram_token_invalid` when the numeric id cannot be read; the clear flag works like Feishu's and the cleared config keeps its bot identity). Same save/enable split, the same 409 `account_enabled_elsewhere` when an enabled binding's token is swapped for one another Session has enabled, and otherwise the same absence of a cross-Session conflict on save |
| POST | /messaging/telegram/state | Same contract as the Feishu toggle (400 `telegram_token_required` without a stored token) |
| DELETE | /messaging/telegram | Remove this channel's config entirely (Bot Token included). API completeness only |
| POST | /messaging/telegram/test | Credential probe (`getMe`) with the draft token falling back to the stored one → `{ok, latencyMs?, botUsername?, error?}` — success names the bot the token signs in as |
| POST | /messaging/telegram/test-message | Send a short fixed text to the last known chat; 409 `telegram_no_chat` until the bot has been messaged once in Telegram |
-Masked secrets are omitted from responses when none is stored (a cleared config), and a config without a secret cannot be enabled. Cross-session uniqueness is per bot account per channel — Feishu's account identity is the `app_id`, Telegram's is the numeric bot id in front of the token's colon (robust against token rotation). Reads and the two tests are open to any Project member; PUT, the state toggle and DELETE are owner-only (vault semantics — the binding writes carry or act on the secret). Secrets never round-trip. Deleting the Session removes all its configs, and inbound processing accepts text messages only (other types get a bilingual "text only" reply). Telegram connects by draining the backlog first: messages sent while no connection existed are skipped, matching Feishu, where missed events are simply gone.
+Masked secrets are omitted from responses when none is stored (a cleared config), and a config without a secret cannot be enabled. The one cross-Session rule is per bot account per channel and applies to the connection only: one account has one event stream, so at most one Session may have it enabled. Feishu's account identity is the `app_id`, Telegram's is the numeric bot id in front of the token's colon (robust against token rotation). Reads and the two tests are open to any Project member; PUT, the state toggle and DELETE are owner-only (vault semantics — the binding writes carry or act on the secret). Secrets never round-trip. Deleting the Session removes all its configs, and inbound processing accepts text messages only (other types get a bilingual "text only" reply). Telegram connects by draining the backlog first: messages sent while no connection existed are skipped, matching Feishu, where missed events are simply gone.
### Preview on a separate origin
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 0a137544..807b431f 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -284,25 +284,25 @@ Workspace 文件可能由 Agent 生成,`GET /files/content` 一律按不可信
### 消息绑定(飞书、Telegram)
-Session 可以接入消息软件机器人——目前的渠道是飞书与 Telegram,各自挂在 `/messaging/<channel>` 之下。一个 Session **每个渠道至多保存一份配置**(两份可同时保存),其中**至多一个渠道处于启用状态**——启用的渠道持有在线连接。发给机器人的消息以普通用户输入在该 Session 上发起 Task——与在网页输入框里输入完全一致(无标记块;忙碌时排入 follow-up 队列)——完成的回复再转发回对应会话,并按渠道文本上限分段(Telegram 硬上限 4096 字符)。飞书经 SDK 的 WebSocket 长连接接收事件;Telegram 用 `getUpdates` 长轮询——两者都无需公网回调地址。保存与连接是两件事:PUT 只保存凭据,连接由独立的 state 接口开关。路径同上表,省略 `/api/sessions/:sessionId` 前缀。
+Session 可以接入消息软件机器人——目前的渠道是飞书与 Telegram,各自挂在 `/messaging/<channel>` 之下。一个 Session **每个渠道至多保存一份配置**(两份可同时保存),其中**至多一个渠道处于启用状态**——启用的渠道持有在线连接。启用即把机器人账号绑定到该 Session,停用即解除绑定,因此同一个应用或机器人可以同时保存在任意多个 Session 上,只有启用是互斥的。发给机器人的消息以普通用户输入在该 Session 上发起 Task——与在网页输入框里输入完全一致(无标记块;忙碌时排入 follow-up 队列)——完成的回复再转发回对应会话,并按渠道文本上限分段(Telegram 硬上限 4096 字符)。飞书经 SDK 的 WebSocket 长连接接收事件;Telegram 用 `getUpdates` 长轮询——两者都无需公网回调地址。保存与连接是两件事:PUT 只保存凭据,连接由独立的 state 接口开关。路径同上表,省略 `/api/sessions/:sessionId` 前缀。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| GET | /messaging | 渠道无关读取:该 Session **每一份**已保存的渠道配置(`channel` 判别字段、密钥掩码、逐行 `enabled` 意图 + 连接运行状态 + `lastChatKnown`)。渠道感知的绑定编辑器只加载这一个 |
| GET | /messaging/feishu | `{binding, status}` 形态下的飞书配置(未保存时为 null) |
-| PUT | /messaging/feishu | 保存凭据:`{appId, appSecret?, baseDomain?, clearAppSecret?}`。`appSecret` 省略或留空则保持已存值;`clearAppSecret: true` 清除已存密钥(新输入的密钥优先于清除标记;启用中返回 409 `messaging_disable_before_clear`——清除后配置行与非密钥字段保留);`baseDomain` 默认 `https://open.feishu.cn`。不带连接副作用——唯一例外:**已启用**绑定的连接器会用新凭据重启,保证存储配置与在线连接永不背离。应用已绑定到其他 Session 时返回 409 `feishu_app_in_use` |
-| POST | /messaging/feishu/state | 连接开关:`{enabled}`——启用即用**已存凭据**建立连接,停用即断开。该 Session 另一渠道已启用时返回 409 `another_channel_enabled`(先停用它);已存配置没有密钥时返回 400 `feishu_secret_required`。新配置默认停用;服务端启动只连接已启用的配置 |
+| PUT | /messaging/feishu | 保存凭据:`{appId, appSecret?, baseDomain?, clearAppSecret?}`。`appSecret` 省略或留空则保持已存值;`clearAppSecret: true` 清除已存密钥(新输入的密钥优先于清除标记;启用中返回 409 `messaging_disable_before_clear`——清除后配置行与非密钥字段保留);`baseDomain` 默认 `https://open.feishu.cn`。不带连接副作用——唯一例外:**已启用**绑定的连接器会用新凭据重启,保证存储配置与在线连接永不背离。保存不会与其他 Session 冲突,唯一例外正源于这次重启:把**已启用**的绑定改指到另一个 Session 已启用的账号上,返回 409 `account_enabled_elsewhere`,否则那次重启就会绕过启用闸门、把第二条在线连接接到同一账号上 |
+| POST | /messaging/feishu/state | 连接开关:`{enabled}`——启用即用**已存凭据**建立连接,停用即断开。该 Session 另一渠道已启用时返回 409 `another_channel_enabled`,同一账号已在**其他 Session** 上启用时返回 409 `account_enabled_elsewhere`(两者都是「先停用那一个」——后者不透露持有方的任何信息,它可能位于调用方看不到的 Project);已存配置没有密钥时返回 400 `feishu_secret_required`。新配置默认停用;服务端启动只连接已启用的配置 |
| DELETE | /messaging/feishu | 整体删除该渠道的配置(含 App Secret;另一渠道不受影响)。仅为 API 完整性保留——Web 界面的移除入口是清除标记 |
| POST | /messaging/feishu/test | 用请求携带的草稿值做凭据探测,缺省字段回落到已存配置 → `{ok, latencyMs?, error?}`(凭据被拒是 `ok: false`,不是 HTTP 错误) |
| POST | /messaging/feishu/test-message | 向最近一次收到消息的会话发送一条固定测试文本;在飞书里给机器人发过消息之前返回 409 `feishu_no_chat` |
| GET | /messaging/telegram | 同一形态下的 Telegram 配置(`botId`、`botTokenMasked`) |
-| PUT | /messaging/telegram | 保存凭据:`{botToken?, clearBotToken?}`——整份凭据就是 @BotFather 签发的一条 `<机器人 id>:<密钥>` Token(省略或留空则保持已存值;读不出数字 id 时返回 400 `telegram_token_invalid`;清除标记与飞书同口径,清除后配置保留其机器人身份)。保存与启用的分离一致。机器人 id 已绑定到其他 Session 时返回 409 `telegram_bot_in_use` |
+| PUT | /messaging/telegram | 保存凭据:`{botToken?, clearBotToken?}`——整份凭据就是 @BotFather 签发的一条 `<机器人 id>:<密钥>` Token(省略或留空则保持已存值;读不出数字 id 时返回 400 `telegram_token_invalid`;清除标记与飞书同口径,清除后配置保留其机器人身份)。保存与启用的分离一致;把已启用绑定的 Token 换成另一个 Session 已启用的机器人时,同样返回 409 `account_enabled_elsewhere`,其余情况不存在跨 Session 的保存冲突 |
| POST | /messaging/telegram/state | 与飞书开关同一契约(无已存 Token 时返回 400 `telegram_token_required`) |
| DELETE | /messaging/telegram | 整体删除该渠道的配置(含 Bot Token)。仅为 API 完整性保留 |
| POST | /messaging/telegram/test | 凭据探测(`getMe`),草稿 Token 缺省回落到已存值 → `{ok, latencyMs?, botUsername?, error?}`——成功时报出 Token 登录到的机器人 |
| POST | /messaging/telegram/test-message | 向最近一次收到消息的会话发送一条固定测试文本;在 Telegram 里给机器人发过消息之前返回 409 `telegram_no_chat` |
-没有已存密钥的配置(被清除过的)不返回掩码字段,也无法启用。跨 Session 的唯一性按渠道内机器人账号计——飞书的账号身份是 `app_id`,Telegram 是 Token 冒号前的数字机器人 id(换发 Token 也不会改变)。读取与两个测试接口对任意 Project 成员开放;PUT、state 开关与 DELETE 仅限所有者(与 Vault 同口径——绑定写操作携带或作用于密钥)。密钥永不回传。删除 Session 会连带删除其全部渠道配置;入站仅处理文本消息(其他类型收到双语的“仅支持文本”回复)。Telegram 建立连接时先清空积压:无连接期间发来的消息会被跳过,与飞书“错过的事件即消失”同口径。
+没有已存密钥的配置(被清除过的)不返回掩码字段,也无法启用。唯一的跨 Session 规则按渠道内机器人账号计,且只作用于连接:一个账号只有一条事件流,因此至多一个 Session 能将其启用。飞书的账号身份是 `app_id`,Telegram 是 Token 冒号前的数字机器人 id(换发 Token 也不会改变)。读取与两个测试接口对任意 Project 成员开放;PUT、state 开关与 DELETE 仅限所有者(与 Vault 同口径——绑定写操作携带或作用于密钥)。密钥永不回传。删除 Session 会连带删除其全部渠道配置;入站仅处理文本消息(其他类型收到双语的“仅支持文本”回复)。Telegram 建立连接时先清空积压:无连接期间发来的消息会被跳过,与飞书“错过的事件即消失”同口径。
### 独立源预览
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index e77f52f2..852c2d89 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -1715,7 +1715,8 @@ export interface FeishuBindingPutRequest {
/**
* PUT …/messaging/telegram — saves the credential ONLY, same contract as the Feishu PUT
* (an enabled binding's connector restarts with the new token; the connection toggle is
- * POST …/state). 409 `telegram_bot_in_use` when the token's bot id is bound elsewhere.
+ * POST …/state). Saving never conflicts across Sessions: the same bot may sit saved on
+ * several, and only enabling it is exclusive.
*/
export interface TelegramBindingPutRequest {
/** Omitted or blank keeps the stored token (the masked value never round-trips). */
@@ -1730,9 +1731,11 @@ export interface TelegramBindingPutRequest {
/**
* POST …/messaging/<channel>/state — enable connects with the STORED credentials,
- * disable terminates. Enabling is mutually exclusive per Session: while another channel
- * is enabled it answers 409 `another_channel_enabled` (turn that one off first), and a
- * config whose secret is missing answers its channel's 400 `*_required`.
+ * disable terminates. Enabling is what binds the bot account to this Session, and it is
+ * mutually exclusive twice over: while another channel of the same Session is enabled it
+ * answers 409 `another_channel_enabled`, and while another SESSION has the same account
+ * enabled it answers 409 `account_enabled_elsewhere` (both say: turn that one off first).
+ * A config whose secret is missing answers its channel's 400 `*_required`.
*/
export interface MessagingBindingStateRequest {
enabled: boolean;
diff --git a/packages/server/src/db/database.ts b/packages/server/src/db/database.ts
index a9ef2b4b..dbb7b72f 100644
--- a/packages/server/src/db/database.ts
+++ b/packages/server/src/db/database.ts
@@ -37,6 +37,16 @@ export function openDatabase(dbPath: string): DatabaseSync {
// this database: the old index is a strict prefix of it, so every query it served is
// served identically. Dropping is safe — an index is derived, never data.
db.exec("DROP INDEX IF EXISTS idx_usage_session");
+ // The uniqueness index of the old binding model, where a bot account belonged to one
+ // Session forever and a second Session could not even SAVE its credentials. Enabling a
+ // connection is the binding now, so exclusivity is checked per enable (the state route's
+ // 409 account_enabled_elsewhere) and the same account may sit saved on many Sessions —
+ // which this index would reject. SCHEMA_SQL has just created idx_messaging_by_account
+ // over the same columns, so the by-account lookup stays indexed. Dropping is safe: an
+ // index is derived, never data. It is however ONE-WAY — an older build recreates the
+ // unique index on open, which fails outright once duplicate (channel, account_id) rows
+ // exist, so a downgrade after two Sessions saved the same bot needs those rows removed.
+ db.exec("DROP INDEX IF EXISTS idx_messaging_account");
upgradeLastActiveAt(db);
return db;
}
diff --git a/packages/server/src/db/repos/messaging-bindings.ts b/packages/server/src/db/repos/messaging-bindings.ts
index ae8bb11a..8696f1cc 100644
--- a/packages/server/src/db/repos/messaging-bindings.ts
+++ b/packages/server/src/db/repos/messaging-bindings.ts
@@ -7,11 +7,13 @@
* one-enabled-per-session invariant is enforced by the state route (409
* `another_channel_enabled`), not here — the repo stays a dumb store.
*
- * Cross-session uniqueness is per bot account: the unique index on
- * `(channel, account_id)` — one account has one event stream, and two Sessions racing it
- * is meaningless. `upsert` reports that conflict as a result value rather than throwing,
- * so a route can answer its channel's 409 (`feishu_app_in_use` / `telegram_bot_in_use`)
- * without parsing SQLite errors.
+ * Saving is NOT exclusive across Sessions: any number of Sessions may keep the same bot
+ * account saved side by side, each with its own config document and its own last-chat
+ * memory, so `upsert` has no failure mode at all. The one cross-session rule sits on the
+ * connection instead — enabling a binding whose account is already enabled on another
+ * Session is refused by the state route (409 `account_enabled_elsewhere`), which reads
+ * `findEnabledByAccount` to see it. One account has one event stream, so two live
+ * connections on it are meaningless; two saved configs are not.
*
* `config` is the channel-specific credential/config document, stored as JSON. Secrets
* inside it are plaintext at rest (same trade-off as the proxy address in
@@ -33,8 +35,10 @@ export interface MessagingBindingRow {
/**
* INTENT state: whether the binding should hold a live connection (the connection's
* runtime status stays in memory). Saving credentials never flips it — only the
- * explicit state toggle does — and new bindings start disabled. At most one of a
- * Session's rows is enabled (route-enforced).
+ * explicit state toggle does — and new bindings start disabled. Flipping it on is what
+ * binds the account to this Session: at most one of a Session's rows is enabled, and at
+ * most one row per `(channel, accountId)` is enabled across all Sessions (both
+ * route-enforced).
*/
enabled: boolean;
/** Most recent inbound chat (null until the bot is messaged once). */
@@ -95,9 +99,18 @@ export class MessagingBindingsRepo {
return rows.map((r) => mapRow(r as Record<string, unknown>));
}
- findByAccount(channel: string, accountId: string): MessagingBindingRow | null {
+ /**
+ * Whichever binding currently holds this account's connection — null while every Session
+ * that saved the account keeps it dark. At most one row can match, for the same reason
+ * `findEnabled` is at-most-one: the state route refuses the second enable, and its
+ * guard-then-flip runs in one synchronous block, so two requests cannot interleave
+ * between the check and the write.
+ */
+ findEnabledByAccount(channel: string, accountId: string): MessagingBindingRow | null {
const r = this.db
- .prepare("SELECT * FROM messaging_bindings WHERE channel = ? AND account_id = ?")
+ .prepare(
+ "SELECT * FROM messaging_bindings WHERE channel = ? AND account_id = ? AND enabled = 1",
+ )
.get(channel, accountId);
return r ? mapRow(r as Record<string, unknown>) : null;
}
@@ -112,22 +125,18 @@ export class MessagingBindingsRepo {
/**
* Create or replace the Session's config for one channel — credentials/config only:
* `enabled` is intent state the state toggle owns, so an insert starts disabled and an
- * update keeps the stored value. Returns `account_in_use` (writing nothing) when the
- * `(channel, accountId)` pair is already bound to a DIFFERENT Session; re-saving a
- * Session's own binding keeps its last-chat memory, so a settings edit never loses the
- * reply target — unless the account changed, whose chats are unrelated: the remembered
- * chat is dropped so replies can never land in the old bot's conversation.
+ * update keeps the stored value. It cannot fail on another Session: the same account
+ * saved elsewhere is none of this write's business, since only enabling is exclusive.
+ * Re-saving a Session's own binding keeps its last-chat memory, so a settings edit never
+ * loses the reply target — unless the account changed, whose chats are unrelated: the
+ * remembered chat is dropped so replies can never land in the old bot's conversation.
*/
upsert(args: {
sessionId: string;
channel: string;
accountId: string;
config: Record<string, unknown>;
- }): { ok: true; row: MessagingBindingRow } | { ok: false; reason: "account_in_use" } {
- const holder = this.findByAccount(args.channel, args.accountId);
- if (holder !== null && holder.sessionId !== args.sessionId) {
- return { ok: false, reason: "account_in_use" };
- }
+ }): MessagingBindingRow {
const now = new Date().toISOString();
const configJson = JSON.stringify(args.config);
const existing = this.find(args.sessionId, args.channel);
@@ -162,7 +171,7 @@ export class MessagingBindingsRepo {
}
const row = this.find(args.sessionId, args.channel);
if (!row) throw new Error("Failed to read back messaging_bindings after upsert");
- return { ok: true, row };
+ return row;
}
/** The state toggle's write: flip one channel's connection intent (the bridge then aligns the live connection). */
diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.ts
index fa01125c..b615f8dc 100644
--- a/packages/server/src/db/schema.ts
+++ b/packages/server/src/db/schema.ts
@@ -123,9 +123,9 @@ CREATE TABLE IF NOT EXISTS goal_state ( -- goal-mode runtime state (GOAL.
);
CREATE INDEX IF NOT EXISTS idx_goal_session ON goal_state(session_id);
CREATE TABLE IF NOT EXISTS messaging_bindings ( -- Session ↔ messaging-channel bot bindings (runtime/messaging/ holds the long connections)
- session_id TEXT NOT NULL, -- a Session keeps at most one saved config PER channel (composite PK below); at most ONE of them is enabled at a time (route-enforced, 409 another_channel_enabled)
+ session_id TEXT NOT NULL, -- a Session keeps at most one saved config PER channel (composite PK below); at most ONE of them is enabled at a time (route-enforced, 409 another_channel_enabled), and enabling is what binds the account to this Session
channel TEXT NOT NULL, -- messaging channel discriminator ('feishu' | 'telegram')
- account_id TEXT NOT NULL, -- channel-scoped bot/app identity (feishu: app_id; telegram: the bot token's numeric id); one binding per account per channel (idx_messaging_account: one account has one event stream, two Sessions would race it)
+ account_id TEXT NOT NULL, -- channel-scoped bot/app identity (feishu: app_id; telegram: the bot token's numeric id); NOT unique — any number of Sessions may keep the same account saved side by side, each with its own config and last-chat memory; only ENABLING is exclusive (route-enforced, 409 account_enabled_elsewhere: one account has one event stream, two live connections on it would race)
config_json TEXT NOT NULL, -- channel-specific credentials/config JSON (feishu: appId/appSecret/baseDomain; telegram: botToken); secrets plaintext at rest (same trade-off as the proxy address in server_settings), masked at every API surface; a cleared secret is stored as "" (the row and its account identity stay)
enabled INTEGER NOT NULL DEFAULT 0, -- INTENT state (the connection's runtime status stays in memory): new bindings start disabled — saving credentials never opens a connection, the explicit state toggle does
last_chat_id TEXT, -- most recent inbound chat (NULL until the bot is messaged once; replies and test messages target it)
@@ -134,7 +134,7 @@ CREATE TABLE IF NOT EXISTS messaging_bindings ( -- Session ↔ messaging-channel
updated_at TEXT NOT NULL,
PRIMARY KEY (session_id, channel)
);
-CREATE UNIQUE INDEX IF NOT EXISTS idx_messaging_account ON messaging_bindings(channel, account_id);
+CREATE INDEX IF NOT EXISTS idx_messaging_by_account ON messaging_bindings(channel, account_id); -- serves the enable guard's by-account lookup; deliberately NOT unique, unlike its predecessor idx_messaging_account (dropped on open) which made an account exclusive to one Session forever
CREATE TABLE IF NOT EXISTS ui_prefs (
user_id TEXT PRIMARY KEY REFERENCES users(user_id) ON DELETE CASCADE,
prefs_json TEXT NOT NULL -- {theme?, lastProjectId?, ...} free-form JSON
diff --git a/packages/server/src/http/routes/messaging.ts b/packages/server/src/http/routes/messaging.ts
index 1d6c1a47..043accdb 100644
--- a/packages/server/src/http/routes/messaging.ts
+++ b/packages/server/src/http/routes/messaging.ts
@@ -5,9 +5,15 @@
* returns them all, and each channel owns a subtree with its own config shape — /feishu
* and /telegram carry the same verb set, and a further channel adds its own.
*
- * At most ONE of a Session's channels is enabled at a time: the state toggle refuses to
- * enable a channel while another is enabled (409 `another_channel_enabled` — turn that
- * one off first) and to enable a config whose secret is missing (its channel's 400).
+ * ENABLING the connection IS the binding, and disabling it is the unbind. Saving
+ * credentials therefore never conflicts across Sessions — any number of Sessions may keep
+ * the same Feishu app or Telegram bot saved, each with its own config and last-chat
+ * memory — and both exclusivity rules sit on the state toggle instead: it refuses to
+ * enable a channel while another channel of the SAME Session is enabled (409
+ * `another_channel_enabled`), and to enable an account ANOTHER Session already has
+ * enabled (409 `account_enabled_elsewhere` — one account has one event stream, so two
+ * live connections on it would race). A config whose secret is missing is refused with
+ * its channel's 400.
*
* Authorization mirrors the vault's split, through the sessions routes' resolveSession
* pattern (404 never leaks a Session's existence): any Project member can read bindings
@@ -166,8 +172,37 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
};
/**
- * The one-enabled-per-session rule plus the secret prerequisite, checked before an
- * enable flips intent. Disabling is always allowed.
+ * The one-connection-per-account rule, on its own because two paths need it: the enable,
+ * and a save that would carry an already-live connection onto a different account.
+ *
+ * The refusal says nothing about who holds the connection, on purpose. Authorization
+ * here proved access to the CALLER's Session only; the holder may sit in a Project this
+ * user cannot see, so its title or id would be a leak — and the remedy, turning that
+ * connection off where it is on, does not depend on hearing it named.
+ */
+ const guardAccountFree = (sessionId: string, channel: string, accountId: string): void => {
+ const holder = deps.messagingRepo.findEnabledByAccount(channel, accountId);
+ if (holder === null || holder.sessionId === sessionId) return;
+ // A holder whose Session is gone — deleted with its Project or its Agent, neither of
+ // which sweeps bindings — would make this refusal a dead end: it names no Session by
+ // design, and the remedy it offers is to turn off a connection that no longer exists.
+ // Reconcile it here the way start() does on boot, so the account is released now
+ // rather than at the next restart.
+ if (deps.sessionsRepo.findById(holder.sessionId) === null) {
+ deps.messagingRepo.delete(holder.sessionId, channel);
+ return;
+ }
+ throw new HttpError(
+ 409,
+ "account_enabled_elsewhere",
+ "Another Session has this bot's connection enabled: turn it off there first.",
+ );
+ };
+
+ /**
+ * Everything checked before an enable flips intent: the one-enabled-per-session rule,
+ * the one-connection-per-account rule across Sessions, and the secret prerequisite.
+ * Disabling is never gated — it is the unbind, the only way to release an account.
*/
const guardEnable = (sessionId: string, channel: string, row: MessagingBindingRow): void => {
const enabledRow = deps.messagingRepo.findEnabled(sessionId);
@@ -178,6 +213,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
"Another channel's connection is enabled on this Session: disable it first.",
);
}
+ guardAccountFree(sessionId, channel, row.accountId);
const secret =
channel === "feishu" ? feishuFieldsOf(row).appSecret : telegramFieldsOf(row).botToken;
if (secret === "") {
@@ -239,23 +275,23 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
}
appSecret = stored;
}
- const result = deps.messagingRepo.upsert({
+ // A save never enables — but an ENABLED binding re-pointed at another app keeps its
+ // connection and restarts it below, which would stand two Sessions on one app without
+ // ever passing the enable gate. Exclusivity is therefore asked here too, of the app
+ // this write would land on. A disabled binding stays exempt: that is the whole point
+ // of enabling being the binding, and its own enable is still gated.
+ if (existing !== null && existing.enabled) guardAccountFree(row.sessionId, "feishu", appId);
+ const saved = deps.messagingRepo.upsert({
sessionId: row.sessionId,
channel: "feishu",
accountId: appId,
config: { appId, appSecret, baseDomain },
});
- if (!result.ok) {
- throw new HttpError(
- 409,
- "feishu_app_in_use",
- "This Feishu app is already bound to another Session.",
- );
- }
// Save persists credentials only and never flips the connection — with one deliberate
// exception: an ENABLED binding's connector restarts with the new credentials, so the
- // stored config and the live connection never diverge. A disabled binding stays dark.
- if (result.row.enabled) await deps.messaging.sync(row.sessionId);
+ // stored config and the live connection never diverge. A disabled binding stays dark,
+ // whoever else has the same app saved or even connected: only the enable is exclusive.
+ if (saved.enabled) await deps.messaging.sync(row.sessionId);
return c.json(feishuResponse(row.sessionId));
});
@@ -390,21 +426,17 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
botToken = stored;
botId = existing.accountId;
}
- const result = deps.messagingRepo.upsert({
+ // Same reason as the Feishu PUT: a token swap on an enabled binding would carry the
+ // live connection onto another bot without passing the enable gate.
+ if (existing !== null && existing.enabled) guardAccountFree(row.sessionId, "telegram", botId);
+ const saved = deps.messagingRepo.upsert({
sessionId: row.sessionId,
channel: "telegram",
accountId: botId,
config: { botToken },
});
- if (!result.ok) {
- throw new HttpError(
- 409,
- "telegram_bot_in_use",
- "This Telegram bot is already bound to another Session.",
- );
- }
// Same save/enable split as Feishu: only an enabled binding restarts its connector.
- if (result.row.enabled) await deps.messaging.sync(row.sessionId);
+ if (saved.enabled) await deps.messaging.sync(row.sessionId);
return c.json(telegramResponse(row.sessionId));
});
diff --git a/packages/server/test/db-upgrade.test.ts b/packages/server/test/db-upgrade.test.ts
index e15b3747..663f14a9 100644
--- a/packages/server/test/db-upgrade.test.ts
+++ b/packages/server/test/db-upgrade.test.ts
@@ -5,11 +5,12 @@
* pre-existing database.
*
* The last two suites cover the other two directions a released build meets on disk: a table
- * that did not exist when the database was formed, and a database written by a *newer* build
- * than the one opening it (a user who updates, dislikes it, and reinstalls the previous
- * release). Nothing records a schema version, so both properties rest on every schema change
- * staying additive — and the downgrade one on more than that, which the last suite pins next to
- * the tolerance rather than leaving it implied.
+ * that did not exist when the database was formed (and, in the same suite, an index that has
+ * since been retired — the one shape openDatabase removes rather than adds), and a database
+ * written by a *newer* build than the one opening it (a user who updates, dislikes it, and
+ * reinstalls the previous release). Nothing records a schema version, so both properties rest
+ * on every schema change staying additive — and the downgrade one on more than that, which the
+ * last suite pins next to the tolerance rather than leaving it implied.
*/
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { mkdtemp, rm } from "node:fs/promises";
@@ -297,7 +298,7 @@ describe("SessionsRepo last_active_at writes", () => {
* that were already on disk are untouched. `messaging_bindings` is the real instance: it
* shipped in 0.2.5, so every database formed by 0.2.4 or earlier meets this path.
*/
-describe("openDatabase table upgrade", () => {
+describe("openDatabase table and index upgrades", () => {
/**
* Seeds a database in the shape it had **before** messaging_bindings existed, derived from
* the real SCHEMA_SQL rather than a hand-copied DDL replica: create today's schema, then
@@ -341,12 +342,12 @@ describe("openDatabase table upgrade", () => {
const db = openDatabase(dbPath);
try {
- // The table and the account uniqueness index both arrive; the pre-existing Session is
+ // The table and its by-account lookup index both arrive; the pre-existing Session is
// still there, which is what makes this an upgrade rather than a reset.
expect(
db
.prepare(
- "SELECT name FROM sqlite_master WHERE type = 'index' AND name = 'idx_messaging_account'",
+ "SELECT name FROM sqlite_master WHERE type = 'index' AND name = 'idx_messaging_by_account'",
)
.all(),
).toHaveLength(1);
@@ -354,41 +355,143 @@ describe("openDatabase table upgrade", () => {
// And it is immediately writable — a newly created table with no rows would look
// identical to one the upgrade forgot to create until something tries to use it.
const repo = new MessagingBindingsRepo(db);
- const saved = repo.upsert({
- sessionId: "session-pre-messaging",
- channel: "telegram",
- accountId: "12345",
- config: { botToken: "t" },
- });
- expect(saved.ok).toBe(true);
- expect(repo.find("session-pre-messaging", "telegram")?.accountId).toBe("12345");
- // A second Session claiming the same account is refused...
expect(
repo.upsert({
- sessionId: "other-session",
+ sessionId: "session-pre-messaging",
channel: "telegram",
accountId: "12345",
config: { botToken: "t" },
- }),
- ).toEqual({ ok: false, reason: "account_in_use" });
- // ...but that refusal comes from the repo's own findByAccount pre-check, which answers
- // identically over a non-unique index — so it says nothing about what the upgrade
- // created. Only a write that goes around the pre-check reaches the index, so the
- // uniqueness is asserted on the raw INSERT. (The row differs in session_id, so the
- // (session_id, channel) primary key cannot be what rejects it.)
- expect(() =>
+ }).accountId,
+ ).toBe("12345");
+ expect(repo.find("session-pre-messaging", "telegram")?.accountId).toBe("12345");
+ } finally {
+ db.close();
+ }
+ });
+
+ /**
+ * Seeds a database in the shape it had while a bot account belonged to ONE Session forever:
+ * today's schema with the by-account index swapped back to the UNIQUE one it used to be.
+ * Same derivation rule as the helper above — a hand-copied DDL replica forks silently from
+ * the schema it is imitating.
+ */
+ function seedUniqueAccountIndexDb(dbPath: string, seed: (db: DatabaseSync) => void): void {
+ const db = new sqlite.DatabaseSync(dbPath);
+ try {
+ db.exec(SCHEMA_SQL);
+ db.exec("DROP INDEX idx_messaging_by_account");
+ db.exec(
+ "CREATE UNIQUE INDEX idx_messaging_account ON messaging_bindings(channel, account_id)",
+ );
+ seed(db);
+ } finally {
+ db.close();
+ }
+ }
+
+ it("drops the retired unique account index, so one bot account fits on two Sessions", () => {
+ const dbPath = path.join(dir, "web.db");
+ const ts = "2026-01-01T00:00:00.000Z";
+ seedUniqueAccountIndexDb(dbPath, (old) => {
+ old
+ .prepare(
+ `INSERT INTO messaging_bindings
+ (session_id, channel, account_id, config_json, created_at, updated_at)
+ VALUES ('session-a', 'telegram', '12345', '{"botToken":"t"}', ?, ?)`,
+ )
+ .run(ts, ts);
+ });
+ // Read the pre-state and close before asserting on it, for the same reason the sibling
+ // test does: a failed expect between open and close leaks the handle.
+ const before = new sqlite.DatabaseSync(dbPath);
+ let indexBefore: unknown[];
+ try {
+ indexBefore = before
+ .prepare(
+ "SELECT name FROM sqlite_master WHERE type = 'index' AND name = 'idx_messaging_account'",
+ )
+ .all();
+ } finally {
+ before.close();
+ }
+ expect(indexBefore).toHaveLength(1);
+
+ const db = openDatabase(dbPath);
+ try {
+ // The unique index is gone and the plain lookup index over the same columns is there.
+ expect(
+ db
+ .prepare(
+ "SELECT name FROM sqlite_master WHERE type = 'index' AND name = 'idx_messaging_account'",
+ )
+ .all(),
+ ).toEqual([]);
+ expect(
+ db
+ .prepare(
+ "SELECT name FROM sqlite_master WHERE type = 'index' AND name = 'idx_messaging_by_account'",
+ )
+ .all(),
+ ).toHaveLength(1);
+ // The row written under the old rule survived, and a second Session may now keep the
+ // same account saved beside it — the write the unique index used to reject.
+ const repo = new MessagingBindingsRepo(db);
+ expect(repo.find("session-a", "telegram")?.accountId).toBe("12345");
+ expect(
+ repo.upsert({
+ sessionId: "session-b",
+ channel: "telegram",
+ accountId: "12345",
+ config: { botToken: "t2" },
+ }).sessionId,
+ ).toBe("session-b");
+ expect(
db
.prepare(
- `INSERT INTO messaging_bindings
- (session_id, channel, account_id, config_json, created_at, updated_at)
- VALUES ('other-session', 'telegram', '12345', '{}', ?, ?)`,
+ "SELECT COUNT(*) AS n FROM messaging_bindings WHERE channel = 'telegram' AND account_id = '12345'",
)
- .run("2026-01-01T00:00:00.000Z", "2026-01-01T00:00:00.000Z"),
+ .get(),
+ ).toEqual({ n: 2 });
+ // Neither row is enabled, so the lookup the enable guard reads still finds nobody:
+ // saving is not binding, and only an enabled row can hold the account.
+ expect(repo.findEnabledByAccount("telegram", "12345")).toBeNull();
+ // The drop is ONE-WAY, which is the cost of it: an older build recreates the unique
+ // index on open, and over these two rows that statement — its own SCHEMA_SQL, verbatim
+ // — fails, so the older build cannot open this database at all.
+ expect(() =>
+ db.exec(
+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_messaging_account ON messaging_bindings(channel, account_id)",
+ ),
).toThrow(/UNIQUE constraint failed/);
} finally {
db.close();
}
});
+
+ it("an already-enabled binding survives the upgrade and still holds its account", () => {
+ const dbPath = path.join(dir, "web.db");
+ const ts = "2026-01-01T00:00:00.000Z";
+ // The upgrade that actually happens to a user: not a dormant row, but a live connection
+ // they left switched on. It must come back enabled, and it must still be the holder the
+ // enable guard refuses a second Session against.
+ seedUniqueAccountIndexDb(dbPath, (old) => {
+ old
+ .prepare(
+ `INSERT INTO messaging_bindings
+ (session_id, channel, account_id, config_json, enabled, created_at, updated_at)
+ VALUES ('session-a', 'telegram', '99999', '{"botToken":"t"}', 1, ?, ?)`,
+ )
+ .run(ts, ts);
+ });
+ const db = openDatabase(dbPath);
+ try {
+ const repo = new MessagingBindingsRepo(db);
+ expect(repo.find("session-a", "telegram")?.enabled).toBe(true);
+ expect(repo.findEnabledByAccount("telegram", "99999")?.sessionId).toBe("session-a");
+ } finally {
+ db.close();
+ }
+ });
});
/**
diff --git a/packages/server/test/messaging-telegram.test.ts b/packages/server/test/messaging-telegram.test.ts
index 785f2676..8ea56d7a 100644
--- a/packages/server/test/messaging-telegram.test.ts
+++ b/packages/server/test/messaging-telegram.test.ts
@@ -1,7 +1,8 @@
/**
* Telegram messaging tests — the mirror of messaging.test.ts for the second channel, and
* the proof the connector seam holds: the /api/sessions/:id/messaging/telegram routes
- * (token masking + keep-on-blank, bot-id identity 409, the save/enable split, the getMe
+ * (token masking + keep-on-blank, the bot id as the account identity and the enable-time
+ * 409 it collides on, the save/enable split, the getMe
* probe surfacing the bot username), the channel-agnostic GET the channel-aware editor
* reads, and the connector's long-poll loop through a fake Bot API transport — offset
* advancement, the connect-time backlog drain, inbound routing as plain user input,
@@ -400,16 +401,60 @@ describe("telegram binding routes and connector loop", () => {
expect(fake.lastClient().creds.botToken).toBe(rotated);
});
- it("one binding per bot: the same numeric id under a rotated secret still 409s", async () => {
- await api.put(BASE(SID), { botToken: TOKEN });
+ it("a token swap cannot re-point an ENABLED binding at a bot another Session has enabled", async () => {
t.deps.sessionsRepo.insert(sessionRowOf(SID2, projectId));
- // Different secret half, same id half: the identity is the id, not the whole token.
- const res = await api.put(BASE(SID2), { botToken: "7000000001:other-secret-CCCC" });
- expect(res.status).toBe(409);
- expect(((await res.json()) as { error: { code: string } }).error.code).toBe(
- "telegram_bot_in_use",
+ // Two Sessions, each polling its own bot.
+ await bindEnabled(SID);
+ await bindEnabled(SID2, "7000000002:test-secret-BBBB-2222");
+ await waitFor(() => t.deps.messaging.statusOf(SID2, "telegram").state === "connected");
+
+ // Saving the first Session's token here would carry this live poll onto its bot, which
+ // is the enable gate bypassed by a different door: two getUpdates loops on one token.
+ const stolen = await api.put(BASE(SID2), { botToken: TOKEN });
+ expect(stolen.status).toBe(409);
+ const refusal = (await stolen.json()) as { error: { code: string; message: string } };
+ expect(refusal.error.code).toBe("account_enabled_elsewhere");
+ expect(refusal.error.message).not.toContain(SID);
+
+ // Refused means nothing moved: the row keeps its own bot id and its own connection.
+ expect(t.deps.messagingRepo.find(SID2, "telegram")?.accountId).toBe("7000000002");
+ expect(t.deps.messagingRepo.findEnabledByAccount("telegram", "7000000001")?.sessionId).toBe(
+ SID,
);
- expect(t.deps.messagingRepo.find(SID2, "telegram")).toBeNull();
+ expect(t.deps.messaging.statusOf(SID2, "telegram").state).toBe("connected");
+
+ // Disabled first, the same save is allowed again — only the enable is exclusive.
+ expect((await api.post(`${BASE(SID2)}/state`, { enabled: false })).status).toBe(200);
+ expect((await api.put(BASE(SID2), { botToken: TOKEN })).status).toBe(200);
+ expect((await api.post(`${BASE(SID2)}/state`, { enabled: true })).status).toBe(409);
+ });
+
+ it("the account is the bot id: a rotated secret saves freely and collides only on enable", async () => {
+ t.deps.sessionsRepo.insert(sessionRowOf(SID2, projectId));
+ await bindEnabled(SID);
+ // Different secret half, same id half: the identity is the id, not the whole token. It
+ // saves without a murmur — saving is never exclusive across Sessions...
+ const rotated = "7000000001:other-secret-CCCC";
+ expect((await api.put(BASE(SID2), { botToken: rotated })).status).toBe(200);
+ expect(t.deps.messagingRepo.find(SID2, "telegram")?.accountId).toBe("7000000001");
+
+ // ...and is refused only when it asks for the connection the first Session is holding.
+ const blocked = await api.post(`${BASE(SID2)}/state`, { enabled: true });
+ expect(blocked.status).toBe(409);
+ const refusal = (await blocked.json()) as { error: { code: string; message: string } };
+ expect(refusal.error.code).toBe("account_enabled_elsewhere");
+ // Nothing about the holder travels in the refusal (it may sit in an invisible Project).
+ expect(refusal.error.message).not.toContain(SID);
+ expect(t.deps.messaging.statusOf(SID, "telegram").state).toBe("connected");
+
+ // Disabling the first is the unbind: the second then polls on its own token.
+ expect((await api.post(`${BASE(SID)}/state`, { enabled: false })).status).toBe(200);
+ expect((await api.post(`${BASE(SID2)}/state`, { enabled: true })).status).toBe(200);
+ await waitFor(() => t.deps.messaging.statusOf(SID2, "telegram").state === "connected");
+ expect(fake.lastClient().creds.botToken).toBe(rotated);
+ expect(t.deps.messaging.statusOf(SID, "telegram").state).toBe("disconnected");
+ // The released Session kept its token: the switch unbinds, it does not delete.
+ expect(t.deps.messagingRepo.find(SID, "telegram")?.config.botToken).toBe(TOKEN);
});
it("GET /messaging lists every saved channel config; both channels sit saved side by side", async () => {
diff --git a/packages/server/test/messaging.test.ts b/packages/server/test/messaging.test.ts
index 6ce999ba..9bac6d01 100644
--- a/packages/server/test/messaging.test.ts
+++ b/packages/server/test/messaging.test.ts
@@ -1,6 +1,7 @@
/**
* Messaging-binding tests, Feishu side (the Telegram connector's mirror suite is
- * messaging-telegram.test.ts): the repo's two uniqueness rules, the
+ * messaging-telegram.test.ts): the bind-by-enable model (saving is never exclusive,
+ * enabling is), the
* /api/sessions/:id/messaging/feishu routes (masking, secret keep-on-blank, the
* save/enable split — PUT persists credentials only, POST /state owns the connection —
* 409s, authz split, cascade on session delete), and the bridge's routing through a fake
@@ -376,16 +377,97 @@ describe("messaging binding routes and bridge", () => {
expect(((await res.json()) as FeishuBindingResponse).binding?.enabled).toBe(true);
});
- it("one binding per app: a second Session on the same app_id gets 409 feishu_app_in_use", async () => {
- await api.put(BASE(SID), PUT_BODY);
- const row2 = sessionRowOf(SID2, projectId);
- t.deps.sessionsRepo.insert(row2);
- const res = await api.put(BASE(SID2), PUT_BODY);
- expect(res.status).toBe(409);
- expect(((await res.json()) as { error: { code: string } }).error.code).toBe(
- "feishu_app_in_use",
+ it("enabling is the binding: two Sessions may save one app, only one may have it enabled", async () => {
+ t.deps.sessionsRepo.insert(sessionRowOf(SID2, projectId));
+ // Saving the same app on a second Session is not a conflict at all — each keeps its own
+ // stored config, and neither of them is connected by a save.
+ expect((await api.put(BASE(SID), PUT_BODY)).status).toBe(200);
+ expect((await api.put(BASE(SID2), PUT_BODY)).status).toBe(200);
+ expect(t.deps.messagingRepo.find(SID2, "feishu")?.accountId).toBe(PUT_BODY.appId);
+ expect(fake.connections).toHaveLength(0);
+
+ // The first enable takes the app; the second is refused while it holds it.
+ expect((await api.post(`${BASE(SID)}/state`, { enabled: true })).status).toBe(200);
+ const blocked = await api.post(`${BASE(SID2)}/state`, { enabled: true });
+ expect(blocked.status).toBe(409);
+ const refusal = (await blocked.json()) as { error: { code: string; message: string } };
+ expect(refusal.error.code).toBe("account_enabled_elsewhere");
+ // The refusal identifies nothing about the holder: it may sit in a Project this caller
+ // cannot see, so its id must not travel in the message.
+ expect(refusal.error.message).not.toContain(SID);
+ // Refused means nothing moved: the second stays dark, the first keeps its connection.
+ expect(t.deps.messagingRepo.find(SID2, "feishu")?.enabled).toBe(false);
+ expect(fake.connections).toHaveLength(1);
+
+ // And a save on the dark Session is still just a save, connection or no connection
+ // elsewhere: only the enabled binding's own connector ever restarts.
+ const resave = await api.put(BASE(SID2), { ...PUT_BODY, appSecret: "second-secret-7777" });
+ expect(resave.status).toBe(200);
+ expect(fake.connections).toHaveLength(1);
+ expect(t.deps.messaging.statusOf(SID, "feishu").state).toBe("connected");
+
+ // Turning the first one off releases the app, and the second takes it.
+ expect((await api.post(`${BASE(SID)}/state`, { enabled: false })).status).toBe(200);
+ const moved = await api.post(`${BASE(SID2)}/state`, { enabled: true });
+ expect(moved.status).toBe(200);
+ expect(((await moved.json()) as FeishuBindingResponse).binding?.enabled).toBe(true);
+ expect(fake.connections).toHaveLength(2);
+ expect(fake.connections[0]!.closed).toBe(true);
+ // Disabling released the account without touching the credentials: the first Session
+ // keeps its saved config, ready to take the app back.
+ expect(t.deps.messagingRepo.find(SID, "feishu")?.config.appSecret).toBe(PUT_BODY.appSecret);
+ });
+
+ it("a save cannot re-point an ENABLED binding at an app another Session has enabled", async () => {
+ t.deps.sessionsRepo.insert(sessionRowOf(SID2, projectId));
+ // Two Sessions, each connected to its own app. Exclusivity holds so far.
+ await bindEnabled(SID);
+ await bindEnabled(SID2, { appId: "cli_app_second", appSecret: PUT_BODY.appSecret });
+ expect(fake.connections).toHaveLength(2);
+
+ // The save path is the way around the enable gate: this binding is already enabled, so
+ // the write would carry its live connection onto the first Session's app and leave two
+ // rows enabled on one account — the state the whole model rests on being unreachable.
+ const stolen = await api.put(BASE(SID2), {
+ appId: PUT_BODY.appId,
+ appSecret: PUT_BODY.appSecret,
+ });
+ expect(stolen.status).toBe(409);
+ const refusal = (await stolen.json()) as { error: { code: string; message: string } };
+ expect(refusal.error.code).toBe("account_enabled_elsewhere");
+ expect(refusal.error.message).not.toContain(SID);
+
+ // Refused means nothing moved: no third connection, and the row keeps its own app.
+ expect(fake.connections).toHaveLength(2);
+ expect(t.deps.messagingRepo.find(SID2, "feishu")?.accountId).toBe("cli_app_second");
+ expect(t.deps.messagingRepo.findEnabledByAccount("feishu", PUT_BODY.appId)?.sessionId).toBe(
+ SID,
+ );
+
+ // A DISABLED binding is still free to save the same app — that is what "enabling is the
+ // binding" means, and its own enable is still gated.
+ expect((await api.post(`${BASE(SID2)}/state`, { enabled: false })).status).toBe(200);
+ expect((await api.put(BASE(SID2), PUT_BODY)).status).toBe(200);
+ expect((await api.post(`${BASE(SID2)}/state`, { enabled: true })).status).toBe(409);
+ });
+
+ it("an enabled binding whose Session is gone releases its app to the next enable", async () => {
+ t.deps.sessionsRepo.insert(sessionRowOf(SID2, projectId));
+ await bindEnabled(SID);
+ // Deleting a Project or an Agent removes its Sessions without sweeping their bindings,
+ // so the row stays behind holding the app. Until boot reconciles it, the refusal it
+ // produces names no Session — by design — and points at a connection nobody can reach.
+ t.deps.sessionsRepo.deleteById(SID);
+
+ expect((await api.put(BASE(SID2), PUT_BODY)).status).toBe(200);
+ const taken = await api.post(`${BASE(SID2)}/state`, { enabled: true });
+ expect(taken.status).toBe(200);
+ expect(((await taken.json()) as FeishuBindingResponse).binding?.enabled).toBe(true);
+ // The orphan is gone rather than merely stepped over.
+ expect(t.deps.messagingRepo.find(SID, "feishu")).toBeNull();
+ expect(t.deps.messagingRepo.findEnabledByAccount("feishu", PUT_BODY.appId)?.sessionId).toBe(
+ SID2,
);
- expect(t.deps.messagingRepo.find(SID2, "feishu")).toBeNull();
});
it("authz: non-members get 404; a member reads but cannot write or toggle (owner-only)", async () => {
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 3e42dfc1..6e76768a 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -527,7 +527,7 @@ export const putTelegramBinding = (sessionId: string, body: TelegramBindingPutRe
{ method: "PUT", body },
);
-/** The connection toggle: enable connects with the STORED credentials (409 `another_channel_enabled` while the other channel is enabled), disable terminates. */
+/** The connection toggle, which is also the bind/unbind: enable connects with the STORED credentials (409 `another_channel_enabled` while the other channel is enabled, 409 `account_enabled_elsewhere` while another conversation has this bot enabled), disable releases the account. */
export const setMessagingBindingState = (
sessionId: string,
channel: MessagingChannel,
diff --git a/packages/web/src/features/messaging/messaging-binding-editor.tsx b/packages/web/src/features/messaging/messaging-binding-editor.tsx
index 4f6f6957..baaa7ff3 100644
--- a/packages/web/src/features/messaging/messaging-binding-editor.tsx
+++ b/packages/web/src/features/messaging/messaging-binding-editor.tsx
@@ -20,8 +20,13 @@
* page's interaction: the field always starts empty, a stored secret shows as a masked
* line under it with a "clear stored …" checkbox (typing unchecks it; applied on Save),
* blank keeps the stored value — and clearing requires the channel's connection to be
- * disabled first. There is no unbind affordance: removing a credential IS the per-field
- * clear.
+ * disabled first. The connection switch IS the bind/unbind control — enabling binds the
+ * bot to this conversation, turning it off releases it, and the credentials stay saved
+ * through both, so several conversations may keep one bot saved and take turns holding it
+ * (the server refuses a second live one with 409 `account_enabled_elsewhere`, naming
+ * nothing about who holds it). That is semantics, so it is disclosed rather than parked on
+ * screen: the switch carries it as its tooltip and the "what binding does" fold states it
+ * in full. Deleting a stored credential remains a separate act — the per-field clear.
*
* The GET is re-polled while the host shows the editor (the hook's `poll` flag) so
* connect/error flips show up live.
@@ -498,9 +503,14 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })
/>
</div>
{/* The connection toggle + live status on one line: the Switch is the intent, the
- tone-colored text is what the connection actually is right now. At most one
- channel is enabled per Session — the hint under the probes names what gates the
- switch. The error state's `lastError` gets its own line below rather than a track
+ tone-colored text is what the connection actually is right now. The switch's
+ title says the thing its label cannot — flipping it on is the bind, flipping it
+ off the unbind — as a tooltip rather than a line, because a permanent sentence
+ here would push everything below it down for a fact read once. At most one
+ channel is enabled per Session, and at most one conversation may hold a given
+ bot; the hint under the probes names what gates the switch, and only the
+ per-Session rule is knowable client-side — the cross-conversation one arrives as
+ the server's 409. The error state's `lastError` gets its own line below rather than a track
on this one: the connection failures worth reporting name what to do about them
("another program is already polling this bot …"), and a share of a row that
already carries a switch, a label and a status word truncates that to a couple of
@@ -508,7 +518,10 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })
the whole message on hover. */}
<div className="space-y-1">
<div className="flex flex-wrap items-center gap-2 text-xs">
- <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
+ <label
+ className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300"
+ title={S.messaging.bindByEnableHint}
+ >
<Switch
checked={facts.enabled}
disabled={b.toggleBlocked}
@@ -682,6 +695,9 @@ export function MessagingBindingHelp({ channel }: { channel: MessagingChannel })
</HelpFold>
<HelpFold title={S.messaging.faqWhatTitle}>
<p>{per.intro}</p>
+ {/* The channel's own flavor first, then the channel-neutral rule that owns the
+ question a reader actually arrives with: how the bot moves conversations. */}
+ <p className="mt-1.5">{S.messaging.faqWhatBinding}</p>
</HelpFold>
<HelpFold title={S.messaging.faqTroubleTitle}>
<ul className="list-disc space-y-1 pl-4">
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 8130a91d..b89ecc9d 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -1829,6 +1829,9 @@ Scenarios:
console: "Open developer console",
/** The connection toggle (flips immediately, using the stored credentials). */
enabled: "Enable connection",
+ /** The toggle's own tooltip: the switch IS the bind/unbind control, which a label reading "enable" does not say. */
+ bindByEnableHint:
+ "Enabling binds this bot to this conversation; turning it off releases it. The credentials stay saved either way.",
/** Why the toggle is gated while the form has unsaved edits. */
saveBeforeEnable: "Save the credentials first, then enable the connection",
test: "Test connection",
@@ -1862,6 +1865,9 @@ Scenarios:
/** The collapsed FAQ folds below the save area. */
faqSetupTitle: "Set up the bot",
faqWhatTitle: "What binding does",
+ /** The channel-neutral half of that fold: how the same bot moves between conversations. */
+ faqWhatBinding:
+ "The same bot can stay saved in several conversations, but only one of them may have its connection enabled at a time. To move it, turn the connection off where it is on and enable it here — no credential has to be deleted.",
faqTroubleTitle: "Troubleshooting",
/** Troubleshooting entries (bot must be messaged once; connection errors point at credentials; one poller per Telegram token). */
troubleNoChat:
@@ -2093,14 +2099,10 @@ Scenarios:
trace_not_found: "This Trace file no longer exists.",
trace_session_exists:
"This agent already has a Session with that id; a duplicate Trace cannot be imported.",
- feishu_app_in_use:
- "This Feishu app is already bound to another Session — unbind it there or use a different app.",
feishu_secret_required: "App Secret is required.",
feishu_not_bound: "This Session has no Feishu binding yet.",
feishu_no_chat: "No Feishu message received yet — message the bot once in Feishu first.",
feishu_send_failed: "Sending the Feishu message failed.",
- telegram_bot_in_use:
- "This Telegram bot is already bound to another Session — unbind it there or use a different bot.",
telegram_token_required: "Bot Token is required.",
telegram_token_invalid: "The Bot Token is malformed: it looks like <digits>:<secret>.",
telegram_not_bound: "This Session has no Telegram binding yet.",
@@ -2109,6 +2111,10 @@ Scenarios:
telegram_send_failed: "Sending the Telegram message failed.",
another_channel_enabled:
"Another channel's connection is enabled on this conversation: disable it first.",
+ // Deliberately names nothing about the other conversation: it may live in a Project
+ // this user cannot see, and the remedy does not depend on knowing which one it is.
+ account_enabled_elsewhere:
+ "This bot's connection is enabled on another conversation: turn it off there first.",
messaging_disable_before_clear:
"Disable this channel's connection before clearing its credential.",
},
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index da5cfb7d..8611e8f0 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -1791,6 +1791,8 @@ Benchmark:
console: "前往开发者后台",
/** The connection toggle (flips immediately, using the stored credentials). */
enabled: "启用连接",
+ /** The toggle's own tooltip: the switch IS the bind/unbind control, which a label reading "enable" does not say. */
+ bindByEnableHint: "启用即把该机器人绑定到本对话,停用即解除绑定;凭证在两种状态下都保留。",
/** Why the toggle is gated while the form has unsaved edits. */
saveBeforeEnable: "先保存凭证,再启用连接",
test: "测试连接",
@@ -1823,6 +1825,9 @@ Benchmark:
/** The collapsed FAQ folds below the save area. */
faqSetupTitle: "如何创建机器人",
faqWhatTitle: "绑定后会发生什么",
+ /** The channel-neutral half of that fold: how the same bot moves between conversations. */
+ faqWhatBinding:
+ "同一个机器人可以同时保存在多个对话里,但同一时刻只能有一个对话启用它的连接。要换一个对话使用,先在原对话停用连接,再在这里启用——凭证不必删除。",
faqTroubleTitle: "常见问题",
/** Troubleshooting entries (bot must be messaged once; connection errors point at credentials; one poller per Telegram token). */
troubleNoChat: "「发送测试消息」不可用?机器人要先收到过一条消息,才知道要发到哪个会话。",
@@ -2053,18 +2058,19 @@ Benchmark:
invalid_trace: "该文件不是有效的 Trace 文件。",
trace_not_found: "该 Trace 文件已不存在。",
trace_session_exists: "该 Agent 已存在同名 Session,无法导入重复的 Trace。",
- feishu_app_in_use: "该飞书应用已绑定到其他 Session,请先解除或换一个应用。",
feishu_secret_required: "需要填写 App Secret。",
feishu_not_bound: "该 Session 尚未绑定飞书。",
feishu_no_chat: "尚未收到飞书消息:先在飞书中给机器人发一条消息。",
feishu_send_failed: "飞书消息发送失败。",
- telegram_bot_in_use: "该 Telegram 机器人已绑定到其他 Session,请先解除或换一个机器人。",
telegram_token_required: "需要填写 Bot Token。",
telegram_token_invalid: "Bot Token 格式不正确:应形如「数字:密钥」。",
telegram_not_bound: "该 Session 尚未绑定 Telegram。",
telegram_no_chat: "尚未收到 Telegram 消息:先在 Telegram 中给机器人发一条消息。",
telegram_send_failed: "Telegram 消息发送失败。",
another_channel_enabled: "该会话已启用另一渠道的连接:先停用它,再启用当前渠道。",
+ // Deliberately names nothing about the other conversation: it may live in a Project
+ // this user cannot see, and the remedy does not depend on knowing which one it is.
+ account_enabled_elsewhere: "该机器人的连接已在另一个会话中启用:先在那边停用,再在此启用。",
messaging_disable_before_clear: "先停用该渠道的连接,才能清除其凭证。",
},
},
diff --git a/packages/web/test/messaging-binding-editor.test.ts b/packages/web/test/messaging-binding-editor.test.ts
index 55c407a9..08ab83bf 100644
--- a/packages/web/test/messaging-binding-editor.test.ts
+++ b/packages/web/test/messaging-binding-editor.test.ts
@@ -1,12 +1,14 @@
/**
* The messaging binding editor's rendered shape (src/features/messaging/messaging-binding-editor.tsx).
*
- * Five rules this pins, all of which are invisible to a type checker: the form opens on its
+ * Six rules this pins, all of which are invisible to a type checker: the form opens on its
* FIELDS (the explanation lives in the collapsed FAQ under the save area, not above the first
- * input), each channel's developer-console link rides the credential field's corner, a stored
- * secret is removed by the models-page clear checkbox rather than an unbind button — that
- * checkbox is gated, on screen, while the channel holds the connection — and a connection
- * error's detail reaches the reader whole rather than as a few words of a shared row.
+ * input), each channel's developer-console link rides the credential field's corner, the
+ * connection switch — which IS the bind/unbind — carries that sentence as its own tooltip
+ * rather than as a line the form would have to make room for, a stored secret is removed by
+ * the models-page clear checkbox and that checkbox is gated, on screen, while the channel
+ * holds the connection, and a connection error's detail reaches the reader whole rather than
+ * as a few words of a shared row.
*/
import { describe, expect, it } from "vitest";
import { createElement } from "react";
@@ -101,6 +103,15 @@ describe("MessagingBindingBody", () => {
expect(live).toContain(S.messaging.disableBeforeClearHint);
});
+ it("carries the bind/unbind sentence on the switch itself, as a tooltip rather than a line", () => {
+ // Enabling the connection is what binds the bot to this conversation, which a label
+ // reading "enable connection" does not say. It is semantics, so it is disclosed: on the
+ // control, where nothing below has to move to make room for it.
+ const html = render(stateOf("feishu"));
+ expect(html).toContain(`title="${S.messaging.bindByEnableHint}"`);
+ expect(html).not.toContain(`>${S.messaging.bindByEnableHint}<`);
+ });
+
it("gives a connection error its own line, whole, instead of a share of the status row", () => {
// The connection failures worth reporting name the action in the sentence — a share of
// a row that already carries a switch, a label and a status word cut this one to
@@ -158,6 +169,9 @@ describe("MessagingBindingHelp", () => {
// The panels stay in the DOM while folded (aria-controls has to resolve), so the text is
// present — hidden, not absent.
expect(html).toContain(S.feishu.intro);
+ // The channel-neutral half of that fold: how one bot moves between conversations, which
+ // is the question the enable-time 409 sends a reader here with.
+ expect(html).toContain(S.messaging.faqWhatBinding);
expect(html).toContain(S.messaging.troubleNoChat);
expect(html).toContain(S.feishu.setupSteps[0]);
});