A local-first multi-agent app development platform, built on PenguinHarness
feat(server,web): messaging integration — Feishu + Telegram behind one channel seam; a saved config per channel, at most one connected (#464)
Yaowei Zheng7783268bc8a4
diff --git a/changelog/unreleased/2026-08-25-feishu-session-bridge.md b/changelog/unreleased/2026-08-25-feishu-session-bridge.mdnew file mode 100644index 00000000..5afbe8e7--- /dev/null+++ b/changelog/unreleased/2026-08-25-feishu-session-bridge.md@@ -0,0 +1,81 @@+# Connect a Session to a messaging bot (Feishu, Telegram)++- **Date:** 2026-08-25+- **Type:** feature+- **Scope:** `server`, `web`, `docs`+- **PR:** [#464](https://github.com/Prism-Shadow/penguin-harness/pull/464)++[中文版](2026-08-25-feishu-session-bridge.zh.md)++Added messaging-channel bindings with Feishu (Lark) and Telegram as the first two+channels: a Session can be connected to a self-built Feishu app or a Telegram bot, after+which messages sent to the bot flow into that Session as ordinary user input and the AI's+completed replies are relayed back to the chat. 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+one holding the live connection.++## Details++- Two management surfaces shared one channel-aware binding editor: the session-row menu's+ "Messaging binding…" dialog, and a new "Messaging" dock panel in the conversation's+ panel rail (after the Trace panel) managing the current conversation's bindings. The+ channel selector switches freely between the two channels' forms, each independently+ savable and each showing its own configured / enabled state — Feishu takes App ID / App+ Secret / API domain, Telegram a single Bot Token. The form opens on the connection+ controls — the enable switch with its live status, the two probes, then the hint naming+ what gates the switch — and the credential fields follow them, so the controls hold one+ vertical offset in both channels even though their field lists differ in length. The+ channel's developer-console link rides the credential field's top-right corner (the+ models page's "get API key" idiom), and collapsed folds below the Save area hold the+ setup steps (ending in the channel's tutorial link), what binding does, and+ troubleshooting.+- A stored secret is managed the way the models page manages an API key: the field always+ starts empty, the saved value shows only as its site-wide mask on the line beneath, and+ a "clear stored …" checkbox next to that mask drops it on save (typing a replacement+ wins over a checked box). Clearing is refused while the channel's connection is enabled+ — the checkbox is disabled with the reason on screen, and the server answers 409+ `messaging_disable_before_clear` — so a live connection can never outrun the credential+ its store still has. There is no unbind button: removing a credential is the clear.+- Saving and enabling were made separate concerns: Save persisted credentials only and+ never touched the connection (with one exception — an enabled binding's connector+ restarted with the just-saved credentials, so stored config and live connection never+ diverge), while a dedicated enable switch connected or terminated using the stored+ credentials. Enabling is mutually exclusive per Session: the switch is grayed with a+ "turn the other channel's connection off first" hint, and the server refuses it with+ 409 `another_channel_enabled`. New configs started disabled; server startup connected+ only the enabled ones, and the session row carries a small paper plane — one mark for+ every channel, the channel itself named in the mark's tooltip and screen-reader text —+ for an enabled connection rather than a merely saved one.+- The sidebar row's hover affordance changed shape: archive stayed a direct button, and+ the delete button was replaced by a solid three-dot "more" button that opens the row's+ full context menu anchored at itself — the menu gained configuration actions that+ right-click alone left undiscoverable, and delete moved inside it (still+ danger-styled).+- The server stored configs in a channel-discriminated `messaging_bindings` table keyed+ by `(session_id, channel)`, with cross-session uniqueness per bot account per channel+ (409 `feishu_app_in_use` / `telegram_bot_in_use`) and `enabled` as stored intent, and+ ran a messaging bridge holding the enabled binding's inbound event connection behind a+ channel-connector seam: Feishu over the SDK's WebSocket long connection, Telegram over+ an offset-based `getUpdates` long poll (connect drains the dark-period backlog;+ transient poll failures back off, report once per outage, and recover) — neither needs+ a public URL. Inbound text started Tasks with `queueIfBusy` as plain composer-style+ input (no marker, no special sender — the model does not learn the message came from a+ messaging channel); other message types got a bilingual "text only" reply; each+ completed assistant message mirrored back to the last known chat on its own, the moment+ it completed, so a run that writes working notes between tool calls before its answer+ reaches the chat as that same sequence of messages rather than one block at the end —+ sends serialised per Session so they arrive in the order they completed, chunked under+ the channels' text-size limits (inside Telegram's 4096-character cap), and in a group+ chat the run's first message threaded onto the inbound one while the rest were plain+ sends. A pending tool-call approval sent a one-line notice pointing at the web UI.+- New endpoints under `/api/sessions/:sessionId/messaging`: a channel-agnostic GET+ listing every saved channel config (`channel`-discriminated, per-row `enabled` and+ runtime status) plus the same verb set per channel — `/feishu` and `/telegram` each+ with get / put / state / delete / test / test-message. PUT carries the channel's clear+ flag; the state toggle answers 400 `feishu_secret_required` /+ `telegram_token_required` for a config whose secret was cleared. DELETE removes a whole+ channel config and is kept for API completeness — the web UI's removal affordance is+ the clear flag. Telegram's bot identity is the numeric id in front of the token's+ colon, so a rotated token keeps its binding, and a cleared config keeps that identity.+ Secrets masked in every response and kept on a blank re-save, reads and tests for any+ Project member, writes owner-only. Deleting the Session removed all its configs.diff --git a/changelog/unreleased/2026-08-25-feishu-session-bridge.zh.md b/changelog/unreleased/2026-08-25-feishu-session-bridge.zh.mdnew file mode 100644index 00000000..e8c89a90--- /dev/null+++ b/changelog/unreleased/2026-08-25-feishu-session-bridge.zh.md@@ -0,0 +1,19 @@+# Session 接入消息软件机器人(飞书、Telegram)++- **Date:** 2026-08-25+- **Type:** feature+- **Scope:** `server`, `web`, `docs`+- **PR:** [#464](https://github.com/Prism-Shadow/penguin-harness/pull/464)++[English](2026-08-25-feishu-session-bridge.md)++新增消息渠道接入,飞书(Lark)与 Telegram 为首批两个渠道:Session 接入自建飞书应用或 Telegram 机器人后,发给机器人的消息以普通用户输入进入该 Session,AI 完成的回复再转发回对应会话。一个 Session 每个渠道至多保存一份配置(两份可并存),其中至多一个处于启用状态——启用的那个持有在线连接。++## 细节++- 两处管理入口共用同一个渠道感知的绑定编辑器:会话行菜单的「消息软件绑定…」对话框,与对话页右侧面板栏新增的「消息软件」停靠面板(排在轨迹面板之后,管理当前会话的接入配置)。渠道选择器在两个渠道的表单之间自由切换,两份配置各自独立保存、各自显示自己的已存 / 启用状态——飞书填 App ID / App Secret / API 域名,Telegram 只有一条 Bot Token。表单以连接控件开头——「启用连接」开关与实时连接状态、两个探测按钮,其后是说明开关为何置灰的提示——凭据字段排在它们下方,两个渠道的字段数量不同也不改变控件的纵向位置;该渠道的「前往开发者后台」链接挂在凭据字段右上角(与模型库「获取 API key」同口径),保存区下方是默认收起的折叠说明:建机器人步骤(末尾附该渠道的「前往教程」)、绑定后会发生什么、常见问题。+- 已存密钥按模型库管理 API key 的口径管理:字段始终留空,已保存的值只以全站统一掩码显示在下方一行,掩码旁的「清除已存」勾选在保存时生效(新输入的密钥优先于已勾选的清除)。渠道连接启用期间拒绝清除——勾选框置灰并在界面上写出原因,服务端返回 409 `messaging_disable_before_clear`——在线连接因此永远不会跑在存储已经没有的凭据上。没有解绑按钮:移除凭据就是清除。+- 保存与启用拆分为两件事:「保存」只保存凭据、从不建立或断开连接(唯一例外——已启用配置在保存新凭据时用新凭据重启连接器,存储配置与在线连接永不背离);独立的「启用连接」开关用已存凭据即时建立或断开连接。启用在同一 Session 内互斥:另一渠道已启用时开关置灰并提示先停用它,服务端以 409 `another_channel_enabled` 拒绝。新配置默认停用;服务端启动只连接已启用的配置;会话行以一枚纸飞机标记启用中的连接(所有渠道共用同一图形,渠道名写在该标记的悬浮提示与读屏文本里),仅保存不标。+- 侧栏会话行的悬停按钮改形:归档保留为直接按钮,删除按钮换成实心三圆点「更多」按钮——点击即在按钮处打开该行的完整右键菜单(菜单新增了仅靠右键难以发现的配置类操作),删除移入菜单(仍为危险样式)。+- 服务端以带渠道判别列的 `messaging_bindings` 表存储配置,主键为 `(session_id, channel)`,跨 Session 唯一性按渠道内机器人账号计(409 `feishu_app_in_use` / `telegram_bot_in_use`),`enabled` 为存储的连接意图;并经渠道连接器接缝运行消息桥,持有已启用配置的那条入站事件连接:飞书走 SDK 的 WebSocket 长连接,Telegram 走基于 offset 的 `getUpdates` 长轮询(建立连接时先清空停用期间的积压;轮询瞬时失败按指数退避、每次故障只上报一次、恢复后自动回连)——两者都无需公网地址。入站文本以 `queueIfBusy` 按普通输入框口径发起 Task(无标记块、无特殊 sender,模型不知道消息来自消息软件);其他消息类型收到双语「仅支持文本」回复;每条完成的助手消息在完成的当下各自镜像回最近的会话——一次运行中先写工具调用之间的进展、再给出答案,聊天里就按同样的顺序逐条收到,而不是结束时收到一整块;同一 Session 的发送串行排队,到达顺序与完成顺序一致,并按渠道文本上限分段(不超过 Telegram 的 4096 字符硬上限);群聊中只有该次运行的第一条消息回复到原消息,其余为普通发送。有工具调用等待审批时发送一行指向 Web 界面的提醒。+- `/api/sessions/:sessionId/messaging` 下新增接口:渠道无关的 GET 列出该 Session 每一份已保存的渠道配置(以 `channel` 判别,逐行给出 `enabled` 与连接状态),加上每个渠道相同的动词集——`/feishu` 与 `/telegram` 各有 get / put / state / delete / test / test-message。PUT 携带该渠道的清除标记;密钥被清除过的配置在 state 开关处得到 400 `feishu_secret_required` / `telegram_token_required`。DELETE 整体删除某渠道的配置,仅为 API 完整性保留——Web 界面的移除入口是清除标记。Telegram 的机器人身份取 Token 冒号前的数字 id,换发 Token 不丢配置,清除密钥也保留这份身份。密钥在所有响应中掩码、留空重存时保持原值,读取与测试对任意 Project 成员开放、写入仅限所有者。删除 Session 连带删除其全部渠道配置。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 18897641..16825578 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -283,6 +283,28 @@ Workspace files may be Agent-generated, so `GET /files/content` treats them as uThe filename always rides along as `filename*=UTF-8''` with percent-encoding. `preview=1` is where the preview redirect falls back when no separate preview origin is available: the document keeps its real type and does render and run, but the sandbox deliberately omits `allow-same-origin`, so it lands in an opaque origin and can reach neither this origin's cookies nor the API. That isolation is also why `localStorage`, `document.cookie` and third-party embeds do not work there.+### Messaging Bindings (Feishu, Telegram)++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.++| 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 |+| 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 |+| 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.+### Preview on a separate originBoth the Files panel's rendered HTML view (an iframe) and "open in a new tab" go through `GET /files/preview-redirect?path=`, which authenticates the caller, then mints a short-lived HMAC token and 302s to a **different origin**:diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 3d4223e7..5c0a5693 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -282,6 +282,28 @@ Workspace 文件可能由 Agent 生成,`GET /files/content` 一律按不可信文件名始终以 `filename*=UTF-8''` 形式携带(百分号编码)。`preview=1` 是预览跳转在没有独立预览源时的回退目标:文档保留真实类型,可以正常渲染并执行脚本,但沙箱刻意不含 `allow-same-origin`,因此它落在一个不透明源里,既拿不到本源的 Cookie,也调不动 API。这份隔离也正是那里 `localStorage`、`document.cookie` 与第三方 embed 全都不可用的原因。+### 消息绑定(飞书、Telegram)++Session 可以接入消息软件机器人——目前的渠道是飞书与 Telegram,各自挂在 `/messaging/<channel>` 之下。一个 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`。新配置默认停用;服务端启动只连接已启用的配置 |+| 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` |+| 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 建立连接时先清空积压:无连接期间发来的消息会被跳过,与飞书“错过的事件即消失”同口径。+### 独立源预览Files 面板内的 HTML 渲染视图(iframe)与“新页面打开”都走 `GET /files/preview-redirect?path=`:先鉴权,再签发一枚短时效 HMAC 令牌,然后 302 跳转到**另一个源**:diff --git a/packages/server/package.json b/packages/server/package.jsonindex e3658c05..470aa91a 100644--- a/packages/server/package.json+++ b/packages/server/package.json@@ -53,6 +53,7 @@},"dependencies": {"@hono/node-server": "^2.0.5",+ "@larksuiteoapi/node-sdk": "^1.73.0","@prismshadow/penguin-core": "workspace:*","@prismshadow/penguin-skills": "workspace:*","@xterm/headless": "^5.5.0",diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 1fafafa1..03315764 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -1180,6 +1180,8 @@ export interface SessionInfo {* history itself when it needs it.*/tracePath?: string;+ /** Present when the Session has an ENABLED messaging binding: its channel (the sidebar row's per-channel indicator). */+ messagingChannel?: MessagingChannel;}/**@@ -1596,6 +1598,181 @@ export interface SessionProcessesResponse {processes: SessionProcessInfo[];}+// ---------------------------------------------------------------------------+// Messaging bindings (/api/sessions/:sessionId/messaging/*)+// ---------------------------------------------------------------------------++/** Messaging channels a Session can bind to. */+export type MessagingChannel = "feishu" | "telegram";++/** Event-connection runtime state of one binding (kept in memory, not persisted). */+export type MessagingRuntimeState = "disconnected" | "connecting" | "connected" | "error";++export interface MessagingRuntimeStatus {+ state: MessagingRuntimeState;+ /** Failure detail; present only in the `error` state. */+ lastError?: string;+ /** When the state last changed (ISO 8601); absent for a binding that never connected. */+ changedAt?: string;+}++/** The stored Feishu config, secret masked (plaintext never leaves the server). */+export interface FeishuBindingInfo {+ channel: "feishu";+ sessionId: string;+ appId: string;+ /**+ * Masked app secret (site-wide mask rule: `***`, or `first4…last4` for long values);+ * absent when no secret is stored (never entered, or cleared) — the binding cannot be+ * enabled until one is saved.+ */+ appSecretMasked?: string;+ baseDomain: string;+ /** Connection INTENT (the state toggle's value); new bindings start disabled, and at most one of a Session's channels is enabled. */+ enabled: boolean;+ /**+ * Whether an inbound Feishu chat is known (the bot has been messaged at least once).+ * Replies and test messages target that chat; until it exists nothing can be sent.+ */+ lastChatKnown: boolean;+ createdAt: string;+ updatedAt: string;+}++/** The stored Telegram config, token masked (plaintext never leaves the server). */+export interface TelegramBindingInfo {+ channel: "telegram";+ sessionId: string;+ /** The numeric bot id (the token's half before the colon) — the channel-scoped account identity, never secret. */+ botId: string;+ /**+ * Masked bot token (site-wide mask rule: `***`, or `first4…last4` for long values);+ * absent when no token is stored (cleared) — the binding cannot be enabled until one+ * is saved.+ */+ botTokenMasked?: string;+ /** Connection INTENT (the state toggle's value); new bindings start disabled, and at most one of a Session's channels is enabled. */+ enabled: boolean;+ /**+ * Whether an inbound Telegram chat is known (the bot has been messaged at least once).+ * Replies and test messages target that chat; until it exists nothing can be sent.+ */+ lastChatKnown: boolean;+ createdAt: string;+ updatedAt: string;+}++/** A Session's saved config for one messaging channel (`channel` is the discriminant). */+export type MessagingBindingInfo = FeishuBindingInfo | TelegramBindingInfo;++/** One saved channel config with its event-connection runtime status. */+export interface MessagingChannelState {+ binding: MessagingBindingInfo;+ /** Only the enabled channel's connection is ever anything but disconnected. */+ status: MessagingRuntimeStatus;+}++/**+ * GET …/messaging response — the channel-agnostic read the channel-aware binding editor+ * loads: EVERY saved channel config (masked) with its runtime status. A Session may keep+ * both channels saved; at most one of them is enabled.+ */+export interface MessagingBindingsResponse {+ bindings: MessagingChannelState[];+}++/** GET / PUT …/messaging/feishu response: the Feishu config (null = not saved) plus its runtime status. */+export interface FeishuBindingResponse {+ binding: FeishuBindingInfo | null;+ status: MessagingRuntimeStatus;+}++/** GET / PUT …/messaging/telegram response (the Telegram narrowing of the same envelope). */+export interface TelegramBindingResponse {+ binding: TelegramBindingInfo | null;+ status: MessagingRuntimeStatus;+}++/**+ * PUT …/messaging/feishu — saves credentials/config ONLY, never flipping the connection+ * (exception: an enabled binding's connector restarts with the new credentials so stored+ * config and live connection never diverge). The connection toggle is POST …/state.+ */+export interface FeishuBindingPutRequest {+ appId: string;+ /** Omitted or blank keeps the stored secret (the masked value never round-trips). */+ appSecret?: string;+ /** Defaults to https://open.feishu.cn when omitted or blank. */+ baseDomain?: string;+ /**+ * Drops the STORED secret (the models-page clear idiom; a typed `appSecret` wins over+ * it). Refused with 409 `messaging_disable_before_clear` while the binding is enabled.+ */+ clearAppSecret?: boolean;+}++/**+ * 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.+ */+export interface TelegramBindingPutRequest {+ /** Omitted or blank keeps the stored token (the masked value never round-trips). */+ botToken?: string;+ /**+ * Drops the STORED token (the models-page clear idiom; a typed `botToken` wins over+ * it — and the row keeps its bot identity). Refused with 409+ * `messaging_disable_before_clear` while the binding is enabled.+ */+ clearBotToken?: boolean;+}++/**+ * 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`.+ */+export interface MessagingBindingStateRequest {+ enabled: boolean;+}++/** POST …/messaging/feishu/test — draft values; each omitted field falls back to the stored binding. */+export interface FeishuTestRequest {+ appId?: string;+ appSecret?: string;+ baseDomain?: string;+}++/** Credential-test outcome (an unreachable/rejected credential is `ok:false`, not an HTTP error). */+export interface FeishuTestResponse {+ ok: boolean;+ latencyMs?: number;+ error?: string;+}++/** POST …/messaging/telegram/test — a draft token, falling back to the stored binding when omitted. */+export interface TelegramTestRequest {+ botToken?: string;+}++/** Telegram credential-test outcome: success additionally names the bot the token signs in as. */+export interface TelegramTestResponse {+ ok: boolean;+ latencyMs?: number;+ /** The bot's `@username`, when the API reports one. */+ botUsername?: string;+ error?: string;+}++/**+ * POST …/messaging/<channel>/test-message — sent to the last known chat (409+ * `feishu_no_chat` / `telegram_no_chat` before one exists).+ */+export interface MessagingTestMessageResponse {+ ok: true;+}+// ---------------------------------------------------------------------------// SSE server events (OmniMessage uses the default event, only server_event here)// ---------------------------------------------------------------------------diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex e87052e4..b3861348 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -43,6 +43,7 @@ import type { ProxyControl } from "./hmr/capabilities.js";import { openDatabase } from "./db/database.js";import { AuthSessionsRepo } from "./db/repos/auth-sessions.js";import { ErrorsRepo } from "./db/repos/errors.js";+import { MessagingBindingsRepo } from "./db/repos/messaging-bindings.js";import { GoalsRepo } from "./db/repos/goals.js";import { SchedulesRepo } from "./db/repos/schedules.js";import { ServerSettingsRepo } from "./db/repos/server-settings.js";@@ -70,6 +71,13 @@ import {} from "./runtime/session-manager.js";import { SessionSources } from "./runtime/session-sources.js";import { Scheduler } from "./runtime/scheduler.js";+import { MessagingBridge } from "./runtime/messaging/bridge.js";+import { FeishuConnector } from "./runtime/messaging/feishu-connector.js";+import { createLarkSdk } from "./runtime/messaging/feishu-sdk.js";+import type { FeishuSdk } from "./runtime/messaging/feishu-sdk.js";+import { TelegramConnector } from "./runtime/messaging/telegram-connector.js";+import { createTelegramTransport } from "./runtime/messaging/telegram-api.js";+import type { TelegramTransport } from "./runtime/messaging/telegram-api.js";import { TitleGenerator, TitleNotifier } from "./runtime/title-generator.js";import { AdminService } from "./services/admin-service.js";import { DesktopService } from "./services/desktop-service.js";@@ -130,6 +138,7 @@ import { agentConfigRoutes } from "./http/routes/agent-config.js";import { agentTracesRoutes } from "./http/routes/agent-traces.js";import { usageRoutes } from "./http/routes/usage.js";import { agentSessionsRoutes, sessionsRoutes } from "./http/routes/sessions.js";+import { sessionMessagingRoutes } from "./http/routes/messaging.js";import { versionRoutes } from "./http/routes/version.js";import { UsageRecorder } from "./runtime/usage-recorder.js";import { previewRoutes } from "./http/routes/preview.js";@@ -165,6 +174,10 @@ export interface AppDeps {schedulesRepo: SchedulesRepo;goalsRepo: GoalsRepo;errorsRepo: ErrorsRepo;+ /** Session ↔ messaging-channel bot bindings (stored; runtime connections live on `messaging`). */+ messagingRepo: MessagingBindingsRepo;+ /** Messaging bridge — channel connectors + event connections (started by the platform next to the scheduler). */+ messaging: MessagingBridge;scheduler: Scheduler;channels: ChannelHub;manager: SessionManager;@@ -194,6 +207,12 @@ export interface BuildDepsOverrides {titles?: TitleNotifier;/** Test double: update-check service with a stubbed fetch/clock (avoids real network calls). */updateCheck?: UpdateCheckService;+ /** Test double: the Feishu connector's SDK factory (avoids real Lark network / long connections). */+ feishuSdk?: FeishuSdk;+ /** Test double: the Telegram connector's Bot API transport (avoids real Telegram network / long polls). */+ telegramTransport?: TelegramTransport;+ /** Test hook: the Telegram connector's poll backoff (tests collapse it to zero). */+ telegramRetryDelayMs?: (failures: number) => number;/*** Test double: scrypt work factor for password hashes written through this app.* Omitted in production, where the KDF runs at full strength.@@ -709,6 +728,26 @@ export function buildAppDeps(: {}),...(overrides.now ? { now: overrides.now } : {}),});+ const messagingRepo = new MessagingBindingsRepo(db);+ // Messaging bridge: assembled here, started by platform.ts's create() (tests drive it+ // via sync()/fake transports, no real network), stopped by the same create()'s dispose+ // effect. One connector per channel; further channels register here.+ const messaging = new MessagingBridge({+ repo: messagingRepo,+ sessions: sessionsRepo,+ channels,+ runner: manager,+ connectors: [+ new FeishuConnector(overrides.feishuSdk ?? createLarkSdk()),+ new TelegramConnector(+ overrides.telegramTransport ?? createTelegramTransport(),+ overrides.telegramRetryDelayMs ? { retryDelayMs: overrides.telegramRetryDelayMs } : {},+ ),+ ],+ errors,+ log,+ ...(overrides.now ? { now: () => overrides.now!().getTime() } : {}),+ });const sessionService = new SessionService({root: config.root,sessions: sessionsRepo,@@ -718,6 +757,15 @@ export function buildAppDeps(traceIndex,proxyEnv,controlEnv,+ // List rows carry the ENABLED channel's indicator (saved-but-dark configs stay off+ // the row); a point query per row keeps the repo out of the service. An unknown+ // stored channel reads as none (same defensive skip as the bridge and the routes).+ messagingChannel: (sessionId) => {+ const enabled = messagingRepo.findEnabled(sessionId);+ return enabled !== null && (enabled.channel === "feishu" || enabled.channel === "telegram")+ ? enabled.channel+ : null;+ },});// Schedule scheduler: assembled here, started by platform.ts's create() (tests drive it// via tickOnce, no real timer), stopped by the same create()'s dispose effect.@@ -762,6 +810,8 @@ export function buildAppDeps(schedulesRepo,goalsRepo,errorsRepo,+ messagingRepo,+ messaging,scheduler,channels,manager,@@ -859,6 +909,7 @@ export function createApp(app.route("/api/projects/:projectId/agents/:agentId/sessions", agentSessionsRoutes(deps));app.route("/api/projects/:projectId/usage", usageRoutes(deps));app.route("/api/sessions", sessionsRoutes(deps));+ app.route("/api/sessions", sessionMessagingRoutes(deps));// Workspace HTML preview on the separate preview origin: deliberately outside /api and// outside the auth middleware — that origin never receives the session cookie, so thediff --git a/packages/server/src/db/repos/messaging-bindings.ts b/packages/server/src/db/repos/messaging-bindings.tsnew file mode 100644index 00000000..ae8bb11a--- /dev/null+++ b/packages/server/src/db/repos/messaging-bindings.ts@@ -0,0 +1,200 @@+/**+ * Repo for Session ↔ messaging-channel bot bindings (Feishu and Telegram today).+ *+ * A Session keeps at most one saved config PER channel — the `(session_id, channel)`+ * primary key — and both channels' credentials may sit saved side by side. Which of them+ * (at most one) holds a live connection is the per-row `enabled` intent; the+ * 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.+ *+ * `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+ * server_settings) and must be masked at every API surface — nothing here ever masks,+ * callers do. A cleared secret is stored as the empty string: the row, its non-secret+ * fields and its account identity stay. The repo does not interpret the document; each+ * channel's connector and route own its shape.+ */+import type { DatabaseSync } from "node:sqlite";++export interface MessagingBindingRow {+ sessionId: string;+ /** Messaging channel discriminator (`feishu` | `telegram`). */+ channel: string;+ /** Channel-scoped bot/app identity (feishu: the app_id; telegram: the bot token's numeric id); never secret. */+ accountId: string;+ /** Channel-specific config document (feishu: appId/appSecret/baseDomain; telegram: botToken). */+ config: Record<string, unknown>;+ /**+ * 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).+ */+ enabled: boolean;+ /** Most recent inbound chat (null until the bot is messaged once). */+ lastChatId: string | null;+ /** Whether that chat is a direct chat; group chats prefer reply-to-message. */+ lastChatIsDirect: boolean;+ createdAt: string;+ updatedAt: string;+}++function mapRow(r: Record<string, unknown>): MessagingBindingRow {+ let config: Record<string, unknown> = {};+ try {+ const parsed: unknown = JSON.parse(r.config_json as string);+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {+ config = parsed as Record<string, unknown>;+ }+ } catch {+ // A malformed document reads as empty config; the connector then reports it malformed.+ }+ return {+ sessionId: r.session_id as string,+ channel: r.channel as string,+ accountId: r.account_id as string,+ config,+ enabled: Number(r.enabled) === 1,+ lastChatId: (r.last_chat_id as string | null) ?? null,+ lastChatIsDirect: Number(r.last_chat_is_direct) === 1,+ createdAt: r.created_at as string,+ updatedAt: r.updated_at as string,+ };+}++export class MessagingBindingsRepo {+ constructor(private readonly db: DatabaseSync) {}++ /** The Session's saved config of ONE channel (null when that channel is not configured). */+ find(sessionId: string, channel: string): MessagingBindingRow | null {+ const r = this.db+ .prepare("SELECT * FROM messaging_bindings WHERE session_id = ? AND channel = ?")+ .get(sessionId, channel);+ return r ? mapRow(r as Record<string, unknown>) : null;+ }++ /** The Session's enabled binding — at most one exists (route-enforced); null when all are dark. */+ findEnabled(sessionId: string): MessagingBindingRow | null {+ const r = this.db+ .prepare("SELECT * FROM messaging_bindings WHERE session_id = ? AND enabled = 1")+ .get(sessionId);+ return r ? mapRow(r as Record<string, unknown>) : null;+ }++ /** Every channel config the Session has saved, in stable channel order. */+ listForSession(sessionId: string): MessagingBindingRow[] {+ const rows = this.db+ .prepare("SELECT * FROM messaging_bindings WHERE session_id = ? ORDER BY channel")+ .all(sessionId);+ return rows.map((r) => mapRow(r as Record<string, unknown>));+ }++ findByAccount(channel: string, accountId: string): MessagingBindingRow | null {+ const r = this.db+ .prepare("SELECT * FROM messaging_bindings WHERE channel = ? AND account_id = ?")+ .get(channel, accountId);+ return r ? mapRow(r as Record<string, unknown>) : null;+ }++ listAll(): MessagingBindingRow[] {+ const rows = this.db+ .prepare("SELECT * FROM messaging_bindings ORDER BY session_id, channel")+ .all();+ return rows.map((r) => mapRow(r as Record<string, unknown>));+ }++ /**+ * 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.+ */+ 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" };+ }+ const now = new Date().toISOString();+ const configJson = JSON.stringify(args.config);+ const existing = this.find(args.sessionId, args.channel);+ if (existing === null) {+ this.db+ .prepare(+ `INSERT INTO messaging_bindings+ (session_id, channel, account_id, config_json, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?)`,+ )+ .run(args.sessionId, args.channel, args.accountId, configJson, now, now);+ } else {+ const keepChat = existing.accountId === args.accountId;+ this.db+ .prepare(+ `UPDATE messaging_bindings+ SET account_id = ?, config_json = ?,+ last_chat_id = CASE WHEN ? THEN last_chat_id ELSE NULL END,+ last_chat_is_direct = CASE WHEN ? THEN last_chat_is_direct ELSE 1 END,+ updated_at = ?+ WHERE session_id = ? AND channel = ?`,+ )+ .run(+ args.accountId,+ configJson,+ keepChat ? 1 : 0,+ keepChat ? 1 : 0,+ now,+ args.sessionId,+ args.channel,+ );+ }+ 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 };+ }++ /** The state toggle's write: flip one channel's connection intent (the bridge then aligns the live connection). */+ setEnabled(sessionId: string, channel: string, enabled: boolean): void {+ this.db+ .prepare(+ `UPDATE messaging_bindings SET enabled = ?, updated_at = ?+ WHERE session_id = ? AND channel = ?`,+ )+ .run(enabled ? 1 : 0, new Date().toISOString(), sessionId, channel);+ }++ /** Remember the most recent inbound chat (the reply and test-message target; chats are channel-scoped). */+ recordChat(sessionId: string, channel: string, chatId: string, isDirect: boolean): void {+ this.db+ .prepare(+ `UPDATE messaging_bindings+ SET last_chat_id = ?, last_chat_is_direct = ?, updated_at = ?+ WHERE session_id = ? AND channel = ?`,+ )+ .run(chatId, isDirect ? 1 : 0, new Date().toISOString(), sessionId, channel);+ }++ /** Drop one channel's config. */+ delete(sessionId: string, channel: string): void {+ this.db+ .prepare("DELETE FROM messaging_bindings WHERE session_id = ? AND channel = ?")+ .run(sessionId, channel);+ }++ /** Drop every channel config of a Session (the session-delete cascade). */+ deleteSession(sessionId: string): void {+ this.db.prepare("DELETE FROM messaging_bindings WHERE session_id = ?").run(sessionId);+ }+}diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.tsindex ddeeeed0..fa01125c 100644--- a/packages/server/src/db/schema.ts+++ b/packages/server/src/db/schema.ts@@ -87,7 +87,7 @@ CREATE TABLE IF NOT EXISTS error_records ( -- server-side error capture (theproject_id TEXT, -- nullable: sign-in/registration and process-level errors have no Project contextagent_id TEXT,session_id TEXT,- source TEXT NOT NULL, -- http | session | usage | title | subagent | process | llm | environment | compaction | schedule+ source TEXT NOT NULL, -- http | session | usage | title | subagent | process | llm | environment | compaction | schedule | messagingkind TEXT NOT NULL, -- expected (HttpError, business 4xx) | unexpected (500/runtime)code TEXT NOT NULL, -- HttpError.code / internal / session_run_failed / ...status INTEGER, -- HTTP status code; NULL for non-HTTP sources@@ -122,6 +122,19 @@ CREATE TABLE IF NOT EXISTS goal_state ( -- goal-mode runtime state (GOAL.updated_at TEXT NOT NULL);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)+ 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)+ 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)+ last_chat_is_direct INTEGER NOT NULL DEFAULT 1, -- 1 = direct chat (reply by chat id), 0 = group chat (prefer reply-to-message)+ created_at TEXT NOT NULL,+ 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 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 JSONdiff --git a/packages/server/src/hmr/platform.ts b/packages/server/src/hmr/platform.tsindex e691baa9..e3c2abd9 100644--- a/packages/server/src/hmr/platform.ts+++ b/packages/server/src/hmr/platform.ts@@ -202,6 +202,9 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {// Schedule scheduler: startup reconciliation (missed, don't backfill) + periodic// scan; only active while this App is.await deps.scheduler.start();+ // Messaging bridge: connect every enabled Session binding (channel event+ // streams); only active while this App is, like the scheduler.+ await deps.messaging.start();// Goal mode runs only in SessionManager memory: a hard crash (SIGKILL, power loss)// can leave goal_state rows stuck `active` with no runner behind them — and so can// the previous App, whose manager a swap hard-aborts. Reconcile them to `aborted`@@ -245,6 +248,8 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {// runtime-owned, re-claimed by every App; not this App's to park// SUSPENDED (stopped here; the successor rebuilds it fresh at load):// - scheduler stop() now; successor start() reconciles missed fires+ // - messaging bridge stop() closes the channel connections; successor start()+ // reconnects every enabled binding from the DB// - agent runs approvals → deny, drives → abort; goal rows reconciled by// the successor's abortOrphanedActive// - session environments dispose() after the drive settles — kills background@@ -272,6 +277,7 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {const drains: Promise<unknown>[] = [];if (business !== null) {business.scheduler.stop();+ business.messaging.stop();drains.push(business.manager.shutdown(DRAIN_GRACE_MS));}drained = Promise.allSettled(drains).then(() => undefined);diff --git a/packages/server/src/http/routes/messaging.ts b/packages/server/src/http/routes/messaging.tsnew file mode 100644index 00000000..1d6c1a47--- /dev/null+++ b/packages/server/src/http/routes/messaging.ts@@ -0,0 +1,488 @@+/**+ * Messaging-binding routes: /api/sessions/:sessionId/messaging[...] — the binding+ * editor's and the Messaging dock panel's shared surface. A Session keeps at most one+ * saved config PER channel (both may sit saved side by side); the channel-agnostic GET+ * returns them all, and each channel owns a subtree with its own config shape — /feishu+ * and /telegram carry the same verb set, and a further channel adds its own.+ *+ * 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).+ *+ * 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+ * and run the two tests; the secret-mutating writes — PUT, the state toggle and DELETE —+ * are Project-owner-only.+ *+ * Round-trip rule for secrets: GET only ever returns the masked value, and a PUT whose+ * secret (feishu `appSecret`, telegram `botToken`) is omitted or blank keeps the stored+ * one (the same never-round-trip-masked-keys convention as the models test endpoint), so+ * the plaintext exists only at first entry. Dropping a stored secret is the explicit+ * clear flag (the models-page idiom), refused while the binding is enabled — the cleared+ * config's row and account identity stay; full removal is the DELETE, which the web UI+ * no longer offers (API completeness only).+ */+import { Hono } from "hono";+import type { Context } from "hono";+import type {+ FeishuBindingInfo,+ FeishuBindingResponse,+ FeishuTestResponse,+ MessagingBindingInfo,+ MessagingBindingsResponse,+ MessagingBindingStateRequest,+ MessagingChannelState,+ MessagingTestMessageResponse,+ TelegramBindingInfo,+ TelegramBindingResponse,+ TelegramTestResponse,+} from "../../api/types.js";+import type { AppEnv } from "../../auth/middleware.js";+import type { MessagingBindingRow } from "../../db/repos/messaging-bindings.js";+import type { SessionRow } from "../../db/repos/sessions.js";+import { FEISHU_DEFAULT_DOMAIN, feishuConfigOf } from "../../runtime/messaging/feishu-connector.js";+import { telegramBotIdOf } from "../../runtime/messaging/telegram-connector.js";+import { maskApiKey } from "../../services/project-config-service.js";+import { HttpError } from "../errors.js";+import { badRequest, optionalString, readJson, requireString } from "../validate.js";+import type { AppDeps } from "../../app.js";++/** The stored feishu config, tolerated loosely (a malformed document reads as blanks). */+function feishuFieldsOf(row: MessagingBindingRow): {+ appId: string;+ appSecret: string;+ baseDomain: string;+} {+ const { appId, appSecret, baseDomain } = row.config;+ return {+ appId: typeof appId === "string" ? appId : row.accountId,+ appSecret: typeof appSecret === "string" ? appSecret : "",+ baseDomain: typeof baseDomain === "string" ? baseDomain : FEISHU_DEFAULT_DOMAIN,+ };+}++/** The stored telegram config, tolerated loosely (a malformed document reads as blank). */+function telegramFieldsOf(row: MessagingBindingRow): { botToken: string } {+ const { botToken } = row.config;+ return { botToken: typeof botToken === "string" ? botToken : "" };+}++function toFeishuInfo(row: MessagingBindingRow): FeishuBindingInfo {+ const fields = feishuFieldsOf(row);+ return {+ channel: "feishu",+ sessionId: row.sessionId,+ appId: fields.appId,+ // A cleared/never-entered secret has no mask: the field's absence is what tells the+ // editor to render "not configured" instead of a masked placeholder.+ ...(fields.appSecret !== "" ? { appSecretMasked: maskApiKey(fields.appSecret) } : {}),+ baseDomain: fields.baseDomain,+ enabled: row.enabled,+ lastChatKnown: row.lastChatId !== null,+ createdAt: row.createdAt,+ updatedAt: row.updatedAt,+ };+}++function toTelegramInfo(row: MessagingBindingRow): TelegramBindingInfo {+ const { botToken } = telegramFieldsOf(row);+ return {+ channel: "telegram",+ sessionId: row.sessionId,+ botId: row.accountId,+ ...(botToken !== "" ? { botTokenMasked: maskApiKey(botToken) } : {}),+ enabled: row.enabled,+ lastChatKnown: row.lastChatId !== null,+ createdAt: row.createdAt,+ updatedAt: row.updatedAt,+ };+}++/** Whatever channel the row is: its masked view, or null on an unknown discriminator (skipped defensively, like the bridge does). */+function toBindingInfo(row: MessagingBindingRow): MessagingBindingInfo | null {+ if (row.channel === "feishu") return toFeishuInfo(row);+ if (row.channel === "telegram") return toTelegramInfo(row);+ return null;+}++/** Normalizes a domain input: blank → the default; anything else must be an http(s) origin. */+function parseBaseDomain(raw: string | undefined): string {+ const trimmed = raw?.trim() ?? "";+ if (trimmed === "") return FEISHU_DEFAULT_DOMAIN;+ let url: URL;+ try {+ url = new URL(trimmed);+ } catch {+ throw badRequest("baseDomain must be an http(s) URL, e.g. https://open.feishu.cn.");+ }+ if (url.protocol !== "http:" && url.protocol !== "https:") {+ throw badRequest("baseDomain must be an http(s) URL, e.g. https://open.feishu.cn.");+ }+ // The SDK joins paths onto the domain itself: keep only the origin.+ return url.origin;+}++/** Session-level entry: /api/sessions/:sessionId/messaging[...]. */+export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {+ const app = new Hono<AppEnv>();++ /** Same lookup-and-authz shape as the sessions routes: 404 without leaking existence. */+ const resolveSession = (c: Context<AppEnv>): SessionRow => {+ const sessionId = c.req.param("sessionId");+ const row = sessionId ? deps.sessionsRepo.findById(sessionId) : null;+ if (!row) {+ throw new HttpError(+ 404,+ "session_not_found",+ "Session does not exist or you do not have access.",+ );+ }+ try {+ deps.projectService.requireProjectAccess(c.var.user.userId, row.projectId);+ } catch {+ throw new HttpError(+ 404,+ "session_not_found",+ "Session does not exist or you do not have access.",+ );+ }+ return row;+ };++ const feishuResponse = (sessionId: string): FeishuBindingResponse => {+ const row = deps.messagingRepo.find(sessionId, "feishu");+ return {+ binding: row ? toFeishuInfo(row) : null,+ status: deps.messaging.statusOf(sessionId, "feishu"),+ };+ };++ const telegramResponse = (sessionId: string): TelegramBindingResponse => {+ const row = deps.messagingRepo.find(sessionId, "telegram");+ return {+ binding: row ? toTelegramInfo(row) : null,+ status: deps.messaging.statusOf(sessionId, "telegram"),+ };+ };++ /**+ * The one-enabled-per-session rule plus the secret prerequisite, checked before an+ * enable flips intent. Disabling is always allowed.+ */+ const guardEnable = (sessionId: string, channel: string, row: MessagingBindingRow): void => {+ const enabledRow = deps.messagingRepo.findEnabled(sessionId);+ if (enabledRow !== null && enabledRow.channel !== channel) {+ throw new HttpError(+ 409,+ "another_channel_enabled",+ "Another channel's connection is enabled on this Session: disable it first.",+ );+ }+ const secret =+ channel === "feishu" ? feishuFieldsOf(row).appSecret : telegramFieldsOf(row).botToken;+ if (secret === "") {+ const code = channel === "feishu" ? "feishu_secret_required" : "telegram_token_required";+ throw new HttpError(400, code, "The stored config has no credential: save one first.");+ }+ };++ // The channel-agnostic read: every saved channel config with its runtime status. The+ // channel-aware binding editor loads this one endpoint and renders both channel forms+ // (and the at-most-one-enabled state) from it.+ app.get("/:sessionId/messaging", (c) => {+ const row = resolveSession(c);+ const bindings: MessagingChannelState[] = [];+ for (const stored of deps.messagingRepo.listForSession(row.sessionId)) {+ const binding = toBindingInfo(stored);+ if (binding === null) continue;+ bindings.push({ binding, status: deps.messaging.statusOf(row.sessionId, stored.channel) });+ }+ return c.json({ bindings } satisfies MessagingBindingsResponse);+ });++ // —— Feishu ————————————————————————————————————————————————————————————————++ app.get("/:sessionId/messaging/feishu", (c) => {+ const row = resolveSession(c);+ return c.json(feishuResponse(row.sessionId));+ });++ app.put("/:sessionId/messaging/feishu", async (c) => {+ const row = resolveSession(c);+ deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);+ const body = await readJson(c);+ const appId = requireString(body, "appId", { minLen: 1, maxLen: 200 }).trim();+ if (appId === "") throw badRequest("appId must not be blank.");+ const secretInput = optionalString(body, "appSecret", { maxLen: 500 })?.trim();+ const clearSecret = (body as { clearAppSecret?: unknown }).clearAppSecret === true;+ const baseDomain = parseBaseDomain(optionalString(body, "baseDomain", { maxLen: 500 }));+ const existing = deps.messagingRepo.find(row.sessionId, "feishu");+ const typed = secretInput !== undefined && secretInput !== "" ? secretInput : undefined;+ // Blank keeps the stored secret; the clear flag (models idiom — a typed secret wins+ // over it) drops it, refused while the binding is enabled: a live connection must+ // never be running on a credential the store no longer has.+ let appSecret: string;+ if (typed !== undefined) appSecret = typed;+ else if (clearSecret && existing !== null) {+ if (existing.enabled) {+ throw new HttpError(+ 409,+ "messaging_disable_before_clear",+ "Disable the connection before clearing its credential.",+ );+ }+ appSecret = "";+ } else {+ const stored = existing !== null ? feishuFieldsOf(existing).appSecret : "";+ if (stored === "") {+ throw new HttpError(400, "feishu_secret_required", "appSecret is required to bind.");+ }+ appSecret = stored;+ }+ const result = 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);+ return c.json(feishuResponse(row.sessionId));+ });++ // The state toggle: enabling connects with the STORED credentials, disabling terminates+ // the connection. Separate from PUT on purpose — saving and connecting are different+ // intents, and the toggle must work without re-submitting any credential.+ app.post("/:sessionId/messaging/feishu/state", async (c) => {+ const row = resolveSession(c);+ deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);+ const enabled = await readStateBody(c);+ const binding = deps.messagingRepo.find(row.sessionId, "feishu");+ if (binding === null) {+ throw new HttpError(404, "feishu_not_bound", "This Session has no Feishu binding.");+ }+ if (enabled) guardEnable(row.sessionId, "feishu", binding);+ deps.messagingRepo.setEnabled(row.sessionId, "feishu", enabled);+ await deps.messaging.sync(row.sessionId);+ return c.json(feishuResponse(row.sessionId));+ });++ // Full removal of the channel's config. Kept for API completeness: the web UI's removal+ // affordance is the per-field clear (PUT clear flag), not this.+ app.delete("/:sessionId/messaging/feishu", (c) => {+ const row = resolveSession(c);+ deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);+ deps.messaging.unbind(row.sessionId, "feishu");+ return c.body(null, 204);+ });++ // Credential test with the request's draft values, each falling back to the stored+ // binding: the form can probe before saving without ever round-tripping the secret.+ app.post("/:sessionId/messaging/feishu/test", async (c) => {+ const row = resolveSession(c);+ const body = await readJson(c);+ const stored = deps.messagingRepo.find(row.sessionId, "feishu");+ const storedFields = stored !== null ? feishuFieldsOf(stored) : null;+ const appId = optionalString(body, "appId", { maxLen: 200 })?.trim() || storedFields?.appId;+ const appSecret =+ optionalString(body, "appSecret", { maxLen: 500 })?.trim() || storedFields?.appSecret;+ const rawDomain = optionalString(body, "baseDomain", { maxLen: 500 })?.trim();+ const baseDomain = parseBaseDomain(+ rawDomain !== undefined && rawDomain !== "" ? rawDomain : storedFields?.baseDomain,+ );+ if (appId === undefined || appId === "") {+ throw badRequest("appId is required (no stored binding to fall back to).");+ }+ if (appSecret === undefined || appSecret === "") {+ throw new HttpError(400, "feishu_secret_required", "appSecret is required to test.");+ }+ const result = await deps.messaging.testCredentials("feishu", { appId, appSecret, baseDomain });+ return c.json({+ ok: result.ok,+ ...(result.latencyMs !== undefined ? { latencyMs: result.latencyMs } : {}),+ ...(result.error !== undefined ? { error: result.error } : {}),+ } satisfies FeishuTestResponse);+ });++ // Short fixed text into the binding's last known chat: proves the outbound leg+ // end to end. Before any inbound message no chat is known — the UI explains that the+ // user must message the bot once in Feishu first.+ app.post("/:sessionId/messaging/feishu/test-message", async (c) => {+ const row = resolveSession(c);+ const binding = deps.messagingRepo.find(row.sessionId, "feishu");+ if (!binding) {+ throw new HttpError(404, "feishu_not_bound", "This Session has no Feishu binding.");+ }+ if (binding.lastChatId === null) {+ throw new HttpError(+ 409,+ "feishu_no_chat",+ "No Feishu chat is known yet: message the bot once in Feishu first.",+ );+ }+ try {+ await deps.messaging.sendTestMessage(binding);+ } catch (err) {+ throw new HttpError(+ 502,+ "feishu_send_failed",+ err instanceof Error ? err.message : String(err),+ );+ }+ return c.json({ ok: true } satisfies MessagingTestMessageResponse);+ });++ // —— Telegram ——————————————————————————————————————————————————————————————++ app.get("/:sessionId/messaging/telegram", (c) => {+ const row = resolveSession(c);+ return c.json(telegramResponse(row.sessionId));+ });++ app.put("/:sessionId/messaging/telegram", async (c) => {+ const row = resolveSession(c);+ deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);+ const body = await readJson(c);+ const tokenInput = optionalString(body, "botToken", { maxLen: 200 })?.trim();+ const clearToken = (body as { clearBotToken?: unknown }).clearBotToken === true;+ const existing = deps.messagingRepo.find(row.sessionId, "telegram");+ const typed = tokenInput !== undefined && tokenInput !== "" ? tokenInput : undefined;+ // Same ladder as the Feishu PUT: typed wins, then the clear flag (disable first),+ // then the stored token; a first bind must carry one. A cleared config keeps its bot+ // identity — the token half in front of the colon never changes for a bot.+ let botToken: string;+ let botId: string;+ if (typed !== undefined) {+ const id = telegramBotIdOf(typed);+ if (id === null) {+ throw new HttpError(+ 400,+ "telegram_token_invalid",+ "botToken must look like <numeric bot id>:<secret> (as issued by @BotFather).",+ );+ }+ botToken = typed;+ botId = id;+ } else if (clearToken && existing !== null) {+ if (existing.enabled) {+ throw new HttpError(+ 409,+ "messaging_disable_before_clear",+ "Disable the connection before clearing its credential.",+ );+ }+ botToken = "";+ botId = existing.accountId;+ } else {+ const stored = existing !== null ? telegramFieldsOf(existing).botToken : "";+ if (stored === "" || existing === null) {+ throw new HttpError(400, "telegram_token_required", "botToken is required to bind.");+ }+ botToken = stored;+ botId = existing.accountId;+ }+ const result = 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);+ return c.json(telegramResponse(row.sessionId));+ });++ app.post("/:sessionId/messaging/telegram/state", async (c) => {+ const row = resolveSession(c);+ deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);+ const enabled = await readStateBody(c);+ const binding = deps.messagingRepo.find(row.sessionId, "telegram");+ if (binding === null) {+ throw new HttpError(404, "telegram_not_bound", "This Session has no Telegram binding.");+ }+ if (enabled) guardEnable(row.sessionId, "telegram", binding);+ deps.messagingRepo.setEnabled(row.sessionId, "telegram", enabled);+ await deps.messaging.sync(row.sessionId);+ return c.json(telegramResponse(row.sessionId));+ });++ app.delete("/:sessionId/messaging/telegram", (c) => {+ const row = resolveSession(c);+ deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);+ deps.messaging.unbind(row.sessionId, "telegram");+ return c.body(null, 204);+ });++ // Credential test: the draft token, falling back to the stored one — and the success+ // feedback names the bot (`getMe`'s username), which is the confirmation a user can+ // actually check against @BotFather.+ app.post("/:sessionId/messaging/telegram/test", async (c) => {+ const row = resolveSession(c);+ const body = await readJson(c);+ const stored = deps.messagingRepo.find(row.sessionId, "telegram");+ const botToken =+ optionalString(body, "botToken", { maxLen: 200 })?.trim() ||+ (stored !== null ? telegramFieldsOf(stored).botToken || undefined : undefined);+ if (botToken === undefined || botToken === "") {+ throw new HttpError(400, "telegram_token_required", "botToken is required to test.");+ }+ const result = await deps.messaging.testCredentials("telegram", { botToken });+ return c.json({+ ok: result.ok,+ ...(result.latencyMs !== undefined ? { latencyMs: result.latencyMs } : {}),+ ...(result.accountLabel !== undefined ? { botUsername: result.accountLabel } : {}),+ ...(result.error !== undefined ? { error: result.error } : {}),+ } satisfies TelegramTestResponse);+ });++ app.post("/:sessionId/messaging/telegram/test-message", async (c) => {+ const row = resolveSession(c);+ const binding = deps.messagingRepo.find(row.sessionId, "telegram");+ if (!binding) {+ throw new HttpError(404, "telegram_not_bound", "This Session has no Telegram binding.");+ }+ if (binding.lastChatId === null) {+ throw new HttpError(+ 409,+ "telegram_no_chat",+ "No Telegram chat is known yet: message the bot once in Telegram first.",+ );+ }+ try {+ await deps.messaging.sendTestMessage(binding);+ } catch (err) {+ throw new HttpError(+ 502,+ "telegram_send_failed",+ err instanceof Error ? err.message : String(err),+ );+ }+ return c.json({ ok: true } satisfies MessagingTestMessageResponse);+ });++ return app;+}++/** The state toggle's `{enabled}` body, shared by both channels. */+async function readStateBody(c: Context<AppEnv>): Promise<boolean> {+ const body = await readJson(c);+ const enabled = (body as Partial<MessagingBindingStateRequest>).enabled;+ if (typeof enabled !== "boolean") throw badRequest("enabled must be a boolean.");+ return enabled;+}diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.tsindex 16dab265..405ff721 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -707,6 +707,10 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {);deps.sessionsRepo.deleteById(row.sessionId);deps.goalsRepo.deleteBySession(row.sessionId);+ // A bound Session takes its messaging bindings with it: close the channel+ // connection and drop every channel's row (no-op when unbound; bulk Agent/Project+ // deletes are reconciled by the bridge's next start()).+ deps.messaging.unbindSession(row.sessionId);// Drop the derived-origin entry along with the Session (bulk Agent/Project deletion// may leave stale entries; session ids are never reused, so they are never matched).deps.sessionSources.delete(row.sessionId);diff --git a/packages/server/src/runtime/error-recorder.ts b/packages/server/src/runtime/error-recorder.tsindex c7599651..0d3ff932 100644--- a/packages/server/src/runtime/error-recorder.ts+++ b/packages/server/src/runtime/error-recorder.ts@@ -66,7 +66,8 @@ export type ErrorSource =| "title"| "subagent"| "process"- | "schedule";+ | "schedule"+ | "messaging";/** Error classification: see file header — the criterion is "does a human need to step in". */export type ErrorKind = "expected" | "unexpected";diff --git a/packages/server/src/runtime/messaging/bridge.ts b/packages/server/src/runtime/messaging/bridge.tsnew file mode 100644index 00000000..43673862--- /dev/null+++ b/packages/server/src/runtime/messaging/bridge.ts@@ -0,0 +1,488 @@+/**+ * Messaging bridge: a Web server runtime component connecting Sessions to external chat+ * platforms through channel connectors (Feishu and Telegram today — see+ * feishu-connector.ts / telegram-connector.ts). Started by the platform next to the+ * Scheduler, stopped when the+ * App is disposed — a hot swap hard-stops it like the scheduler. A Session may keep a+ * saved config per channel, but AT MOST ONE of them is enabled (the state route enforces+ * that), so the bridge holds at most one inbound event connection per Session — the+ * enabled binding's. `enabled` is stored intent the state toggle owns — saving+ * credentials never opens or closes a connection (with one deliberate exception:+ * re-saving an enabled binding restarts its connector with the new credentials, so the+ * stored config and the live connection never diverge).+ *+ * Inbound (channel → Session): every inbound message first records its chat as the+ * binding's reply target; a text message then starts a Task on the bound Session as an+ * ordinary user input — exactly as if typed into the web composer, no marker block and no+ * special sender (the model deliberately does not learn where the message came from) —+ * with `queueIfBusy`: a busy Session queues it as a follow-up, never 409. Any non-text+ * message gets a polite bilingual "text only" reply.+ *+ * Outbound (Session → channel): the bridge subscribes to the Session's in-process channel+ * and relays each of the main conversation's completed assistant messages on its own, the+ * moment it completes — a run that writes working notes between tool calls before its+ * answer reaches the chat as that same sequence of messages, so the chat follows the run+ * as it happens. Each is sent to the last known chat, chunked under the channel's+ * text-size limits, and the sends of one entry are serialised through a promise chain:+ * several messages completing in quick succession must reach the chat in the order they+ * completed. In a group chat the run's FIRST outbound message threads onto the inbound+ * one and everything after it is a plain send — one reply-to anchors the exchange, where+ * repeating it per message would stack a quote header over each of them; a direct chat is+ * plain sends throughout. EVERY completed assistant message mirrors once a chat is known+ * — web-initiated turns included; before the first inbound message no chat is known and+ * nothing is sent. Compaction output (the summary the model streams between compaction+ * events) is not a reply and is skipped, and+ * a connection joining mid-run relays nothing from that run rather than mirroring half a+ * reply. An `approval_request` additionally sends a one-line notice that a tool call is+ * waiting in the web UI.+ */+import { userText } from "@prismshadow/penguin-core";+import type { OmniMessage } from "@prismshadow/penguin-core";+import type { MessagingRuntimeStatus } from "../../api/types.js";+import type {+ MessagingBindingRow,+ MessagingBindingsRepo,+} from "../../db/repos/messaging-bindings.js";+import type { ChannelEvent, ChannelHub } from "../channel.js";+import type { ErrorSink } from "../error-recorder.js";+import type {+ MessagingChannelConnector,+ MessagingClient,+ MessagingInboundMessage,+} from "./connector.js";++/**+ * Max characters per outbound text message, shared by every channel: it must sit under+ * the tightest hard cap across them. Telegram rejects a `sendMessage` text over 4096+ * characters (counted as UTF-16 units, which is what a JS string length measures), and+ * Feishu caps a text message's `content` around 150KB — 4000 stays under both while+ * keeping replies in a handful of bubbles.+ */+export const MESSAGING_TEXT_CHUNK_CHARS = 4000;++// The three fixed outbound notices are user-facing chat content, deliberately bilingual+// like the rest of the product's user-facing copy (the server has no locale for an+// external chat, so both languages ride each notice).+export const MESSAGING_TEXT_ONLY_NOTICE =+ "Only text messages are supported for now. 目前仅支持文本消息。";+export const MESSAGING_APPROVAL_NOTICE =+ "A tool call is waiting for your approval in the PenguinHarness web UI. 有工具调用正在等待你在网页端审批。";+export const MESSAGING_TEST_MESSAGE =+ "PenguinHarness test message: this Session's messaging binding works. 测试消息:该会话的消息绑定工作正常。";++/**+ * Splits an outbound reply into channel-sized chunks, preferring newline boundaries so a+ * split lands between paragraphs rather than mid-sentence when it can.+ */+export function chunkMessagingText(text: string, max = MESSAGING_TEXT_CHUNK_CHARS): string[] {+ const out: string[] = [];+ let rest = text;+ while (rest.length > max) {+ const window = rest.slice(0, max);+ const nl = window.lastIndexOf("\n");+ // Only a newline in the window's back half is worth splitting at — an early one would+ // produce a tiny fragment and many more messages.+ const cut = nl > max / 2 ? nl : max;+ out.push(rest.slice(0, cut));+ rest = rest.slice(cut).replace(/^\n+/, "");+ }+ if (rest.length > 0) out.push(rest);+ return out;+}++/** Minimal dependency on SessionManager (eases test doubles; mirrors ScheduleTaskRunner). */+export interface MessagingTaskRunner {+ statusOf(sessionId: string): string;+ startTask(+ sessionId: string,+ input: OmniMessage[],+ opts: { queueIfBusy: boolean },+ ): Promise<{ sessionId: string; queued: boolean }>;+}++/** Minimal dependency on the sessions index (existence checks for reconcile/cascade). */+export interface MessagingSessionIndex {+ findById(sessionId: string): object | null;+}++export interface MessagingBridgeDeps {+ repo: MessagingBindingsRepo;+ sessions: MessagingSessionIndex;+ channels: ChannelHub;+ runner: MessagingTaskRunner;+ /** One connector per channel; a stored binding whose channel has no connector is skipped with an error record. */+ connectors: readonly MessagingChannelConnector[];+ errors: ErrorSink;+ log?: (line: string) => void;+ now?: () => number;+}++/** One connected (or connecting/errored) binding's in-memory state. */+interface BridgeEntry {+ sessionId: string;+ /** The connected binding's channel (a Session's OTHER saved channels read as disconnected). */+ channel: string;+ connector: MessagingChannelConnector;+ config: Record<string, unknown>;+ status: MessagingRuntimeStatus;+ connection: { close(): void } | null;+ unsubscribe: (() => void) | null;+ /** Cached outbound client (created lazily from `config`). */+ client: MessagingClient | null;+ /** Inbound group message to thread replies onto (memory only; direct chats clear it). */+ lastInboundMessageId: string | null;+ /** Last observed run state on the Session channel. */+ active: string;+ /** False while joined mid-run: that run's partial tail must not mirror as half a reply. */+ armed: boolean;+ /** Between compaction_begin/_end: the streamed summary is not a reply. */+ inCompaction: boolean;+ /** The run in progress already threaded its first outbound message onto the inbound one. */+ threadedThisRun: boolean;+ /**+ * Tail of this entry's outbound sends. Each relayed message is appended rather than+ * started on its own, so messages completing in quick succession cannot race each other+ * into the chat out of order. It never rejects — deliverReply records its own failures —+ * so one slow or failing send delays this Session's later messages and nothing else.+ */+ sendChain: Promise<void>;+}++export class MessagingBridge {+ private readonly entries = new Map<string, BridgeEntry>();+ private readonly connectors: ReadonlyMap<string, MessagingChannelConnector>;+ private readonly now: () => number;+ private readonly log: (line: string) => void;++ constructor(private readonly deps: MessagingBridgeDeps) {+ this.connectors = new Map(deps.connectors.map((c) => [c.channel, c]));+ this.now = deps.now ?? (() => Date.now());+ this.log = deps.log ?? (() => {});+ }++ /**+ * Server startup: connect every ENABLED binding (disabled ones keep their credentials+ * and stay dark; at most one per Session is enabled). A binding whose Session no longer+ * exists (deleted while this server was down, or by a bulk Agent/Project delete that+ * bypassed the per-session cascade) is reconciled away instead of connected.+ */+ async start(): Promise<void> {+ for (const row of this.deps.repo.listAll()) {+ if (this.deps.sessions.findById(row.sessionId) === null) {+ this.deps.repo.delete(row.sessionId, row.channel);+ continue;+ }+ if (row.enabled) await this.connect(row);+ }+ }++ /** App dispose: close every connection; bindings persist for the successor's start(). */+ stop(): void {+ for (const sessionId of [...this.entries.keys()]) this.disconnect(sessionId);+ }++ /**+ * Align the live connection with the stored intent: an enabled binding exists →+ * (re)connect with its CURRENT config, none → disconnect. The state toggle calls this+ * after flipping intent, and a credential save calls it only while the saved binding is+ * enabled — the restart that keeps stored config and live connection from diverging.+ */+ async sync(sessionId: string): Promise<void> {+ const row = this.deps.repo.findEnabled(sessionId);+ if (row === null) {+ this.disconnect(sessionId);+ return;+ }+ await this.connect(row);+ }++ /** Route DELETE: disconnect (when this channel holds the connection) and drop the row. No-op when unbound. */+ unbind(sessionId: string, channel: string): void {+ if (this.entries.get(sessionId)?.channel === channel) this.disconnect(sessionId);+ this.deps.repo.delete(sessionId, channel);+ }++ /** Session-delete cascade: disconnect and drop every channel's config. */+ unbindSession(sessionId: string): void {+ this.disconnect(sessionId);+ this.deps.repo.deleteSession(sessionId);+ }++ /** One channel's runtime status (only the connected channel is ever anything but disconnected). */+ statusOf(sessionId: string, channel: string): MessagingRuntimeStatus {+ const entry = this.entries.get(sessionId);+ if (!entry || entry.channel !== channel) return { state: "disconnected" };+ return entry.status;+ }++ /**+ * Credential probe for the test endpoints: ok/error with latency, never a throw. A+ * channel whose check identifies the account (Telegram: the bot's @username) passes+ * that label through for the route's success feedback.+ */+ async testCredentials(+ channel: string,+ config: Record<string, unknown>,+ ): Promise<{ ok: boolean; latencyMs?: number; accountLabel?: string; error?: string }> {+ const startedAt = this.now();+ try {+ const client = await this.connectorFor(channel).createClient(config);+ const info = await client.checkCredentials();+ return {+ ok: true,+ latencyMs: this.now() - startedAt,+ ...(info?.accountLabel !== undefined ? { accountLabel: info.accountLabel } : {}),+ };+ } catch (err) {+ return { ok: false, error: err instanceof Error ? err.message : String(err) };+ }+ }++ /**+ * Test-message endpoints: a short fixed text to the binding's last known chat. The+ * route has already established that the binding and its chat exist; a race that+ * removed either since surfaces as the send failing.+ */+ async sendTestMessage(row: MessagingBindingRow): Promise<void> {+ if (row.lastChatId === null) throw new Error("no chat is known yet");+ const client = await this.clientFor(row.sessionId, row);+ await client.sendText(row.lastChatId, MESSAGING_TEST_MESSAGE);+ }++ // -------------------------------------------------------------------------++ private connectorFor(channel: string): MessagingChannelConnector {+ const connector = this.connectors.get(channel);+ if (!connector) throw new Error(`no messaging connector for channel "${channel}"`);+ return connector;+ }++ private async connect(row: MessagingBindingRow): Promise<void> {+ this.disconnect(row.sessionId);+ let connector: MessagingChannelConnector;+ try {+ connector = this.connectorFor(row.channel);+ } catch (err) {+ this.recordError(row.sessionId, err, "messaging_channel_unknown");+ return;+ }+ // Mirror arming: a connection made while the Session is mid-run must not mirror that+ // run's partial tail — it arms at the next idle flip instead.+ const runState = this.deps.runner.statusOf(row.sessionId);+ const entry: BridgeEntry = {+ sessionId: row.sessionId,+ channel: row.channel,+ connector,+ config: row.config,+ status: { state: "connecting", changedAt: new Date(this.now()).toISOString() },+ connection: null,+ unsubscribe: null,+ client: null,+ lastInboundMessageId: null,+ active: runState,+ armed: runState === "idle",+ inCompaction: false,+ threadedThisRun: false,+ sendChain: Promise.resolve(),+ };+ this.entries.set(row.sessionId, entry);+ entry.unsubscribe = this.deps.channels+ .get(row.sessionId)+ .subscribe((evt) => this.observe(entry, evt));+ try {+ const connection = await connector.connect(row.config, {+ onMessage: (msg) => this.onInbound(entry, msg),+ onReady: () => this.setStatus(entry, { state: "connected" }),+ onError: (err) => {+ const detail = err instanceof Error ? err.message : String(err);+ this.setStatus(entry, { state: "error", lastError: detail });+ this.recordError(entry.sessionId, err, "messaging_connect_failed");+ },+ });+ if (this.entries.get(row.sessionId) !== entry) {+ // A concurrent sync/unbind replaced this attempt while the channel was loading.+ connection.close();+ return;+ }+ entry.connection = connection;+ } catch (err) {+ const detail = err instanceof Error ? err.message : String(err);+ this.setStatus(entry, { state: "error", lastError: detail });+ this.recordError(row.sessionId, err, "messaging_connect_failed");+ }+ }++ private disconnect(sessionId: string): void {+ const entry = this.entries.get(sessionId);+ if (!entry) return;+ this.entries.delete(sessionId);+ entry.unsubscribe?.();+ try {+ entry.connection?.close();+ } catch (err) {+ this.log(`[messaging] close failed: ${err instanceof Error ? err.message : String(err)}`);+ }+ }++ /** Status write, guarded against a stale entry (replaced by a newer connect). */+ private setStatus(entry: BridgeEntry, patch: Omit<MessagingRuntimeStatus, "changedAt">): void {+ if (this.entries.get(entry.sessionId) !== entry) return;+ entry.status = { ...patch, changedAt: new Date(this.now()).toISOString() };+ }++ private recordError(sessionId: string, err: unknown, code: string): void {+ this.deps.errors.record({ source: "messaging", err, code, ctx: { sessionId } });+ }++ private async clientFor(sessionId: string, row: MessagingBindingRow): Promise<MessagingClient> {+ // The cached client belongs to the CONNECTED channel; another channel's caller (a+ // test message on a saved-but-dark binding) gets a fresh client instead.+ const entry = this.entries.get(sessionId);+ const cacheable = entry !== undefined && entry.channel === row.channel;+ if (cacheable && entry.client) return entry.client;+ const client = await this.connectorFor(row.channel).createClient(row.config);+ if (cacheable) entry.client = client;+ return client;+ }++ // —— Inbound ——————————————————————————————————————————————————————————————++ private async onInbound(entry: BridgeEntry, msg: MessagingInboundMessage): Promise<void> {+ if (this.entries.get(entry.sessionId) !== entry) return; // stale connection+ try {+ const isDirect = msg.chatKind === "direct";+ // The chat becomes the reply target BEFORE any processing: even a rejected message+ // type teaches the bridge where the user is.+ this.deps.repo.recordChat(entry.sessionId, entry.channel, msg.chatId, isDirect);+ entry.lastInboundMessageId = isDirect ? null : msg.messageId;+ if (msg.text === null || msg.text.trim() === "") {+ await this.replyInbound(entry, msg, MESSAGING_TEXT_ONLY_NOTICE);+ return;+ }+ // An ordinary user input, exactly as if typed into the web composer: no marker+ // block, no special sender — the model deliberately does not learn the message+ // arrived through a messaging channel.+ await this.deps.runner.startTask(entry.sessionId, [userText(msg.text)], {+ queueIfBusy: true,+ });+ } catch (err) {+ this.recordError(entry.sessionId, err, "messaging_inbound_failed");+ }+ }++ /** Reply to the inbound message itself: threaded reply in groups, plain send in direct chats. */+ private async replyInbound(+ entry: BridgeEntry,+ msg: MessagingInboundMessage,+ text: string,+ ): Promise<void> {+ const row = this.deps.repo.find(entry.sessionId, entry.channel);+ if (!row) return;+ const client = await this.clientFor(entry.sessionId, row);+ if (msg.chatKind === "direct") await client.sendText(msg.chatId, text);+ else await client.replyText(msg.messageId, text);+ }++ // —— Outbound ——————————————————————————————————————————————————————————————++ /** Channel tap: each main-conversation completed assistant message + the run-state flips. */+ private observe(entry: BridgeEntry, evt: ChannelEvent): void {+ if (this.entries.get(entry.sessionId) !== entry) return;+ let data: unknown;+ try {+ data = JSON.parse(evt.data);+ } catch {+ return;+ }+ if (evt.event === "server_event") {+ const event = data as { type?: string; state?: string };+ if (event.type === "task_state" && typeof event.state === "string") {+ this.onTaskState(entry, event.state);+ } else if (event.type === "approval_request") {+ void this.deliverNotice(entry, MESSAGING_APPROVAL_NOTICE);+ }+ return;+ }+ const msg = data as OmniMessage;+ if (msg.origin !== undefined && msg.origin.length > 0) return; // subagent output is not the reply+ const payload = msg.payload as { type?: string; role?: string; text?: string };+ if (msg.type === "event_msg") {+ if (payload.type === "compaction_begin") entry.inCompaction = true;+ else if (payload.type === "compaction_end") entry.inCompaction = false;+ return;+ }+ if (msg.type !== "model_msg" || entry.inCompaction) return;+ // Completed assistant text only: partials, thinking and tool traffic never mirror.+ if (payload.type === "text" && payload.role === "assistant" && payload.text !== undefined) {+ this.relay(entry, payload.text);+ }+ }++ /**+ * Queues one completed assistant message for the bound chat. Appended to the entry's+ * send chain rather than started here: a run can complete several messages within+ * milliseconds, and two sends racing would reach the chat in the wrong order. Returns+ * immediately either way, so a slow channel never blocks the Session's stream handling.+ */+ private relay(entry: BridgeEntry, text: string): void {+ if (!entry.armed) return; // joined mid-run: this run's messages are not a reply+ const body = text.trim();+ if (body === "") return;+ entry.sendChain = entry.sendChain.then(() => this.deliverReply(entry, body));+ }++ private onTaskState(entry: BridgeEntry, state: string): void {+ if (state === "running") {+ // A fresh run observed from its start gets one thread reply again. Only a real+ // idle -> running edge counts: task_state is re-published mid-run for queue and+ // steering changes, and re-arming there would thread every message of the run.+ if (entry.active !== "running") entry.threadedThisRun = false;+ } else if (state === "idle") {+ // A run joined midway ends here; from the next one on its messages mirror.+ entry.armed = true;+ }+ entry.active = state;+ }++ /**+ * Sends one completed assistant message to the last known chat, in chunks under the+ * channel's cap; a send failure is recorded, never thrown, so the chain behind it keeps+ * moving. In a group the run's first outbound chunk threads onto the inbound message and+ * everything after it is a plain send: the reply-to relation names which message is being+ * answered, and one of them says it — repeating it per message and per chunk stacks quote+ * headers over the whole conversation.+ */+ private async deliverReply(entry: BridgeEntry, text: string): Promise<void> {+ try {+ const row = this.deps.repo.find(entry.sessionId, entry.channel);+ if (!row || row.lastChatId === null) return; // no chat known yet: nothing mirrors+ const client = await this.clientFor(entry.sessionId, row);+ for (const chunk of chunkMessagingText(text)) {+ const threadOnto =+ !row.lastChatIsDirect && entry.lastInboundMessageId !== null && !entry.threadedThisRun+ ? entry.lastInboundMessageId+ : null;+ if (threadOnto !== null) {+ entry.threadedThisRun = true;+ await client.replyText(threadOnto, chunk);+ } else {+ await client.sendText(row.lastChatId, chunk);+ }+ }+ } catch (err) {+ this.recordError(entry.sessionId, err, "messaging_send_failed");+ }+ }++ /** One-line notice (approval waiting) to the last known chat; silent before one exists. */+ private async deliverNotice(entry: BridgeEntry, text: string): Promise<void> {+ try {+ const row = this.deps.repo.find(entry.sessionId, entry.channel);+ if (!row || row.lastChatId === null) return;+ const client = await this.clientFor(entry.sessionId, row);+ await client.sendText(row.lastChatId, text);+ } catch (err) {+ this.recordError(entry.sessionId, err, "messaging_send_failed");+ }+ }+}diff --git a/packages/server/src/runtime/messaging/connector.ts b/packages/server/src/runtime/messaging/connector.tsnew file mode 100644index 00000000..bea0eb5e--- /dev/null+++ b/packages/server/src/runtime/messaging/connector.ts@@ -0,0 +1,85 @@+/**+ * The messaging-channel connector seam: what the MessagingBridge needs from one chat+ * platform (Feishu and Telegram today; further channels implement the same interface and+ * register in app assembly). A connector owns everything channel-specific — credential+ * shape, wire protocol, event normalization — and hands the bridge a channel-neutral+ * view: a client for outbound sends and credential checks, and a long-lived event+ * connection delivering normalized inbound messages.+ *+ * Config documents are the repo's stored per-channel JSON (`MessagingBindingRow.config`);+ * every connector method validates its own shape and throws a readable error on a+ * malformed one — the bridge treats that like any other channel failure.+ */++/** Known messaging channels (the DB stores the discriminator as text; unknown values are skipped defensively). */+export type MessagingChannel = "feishu" | "telegram";++/** One inbound chat message, normalized across channels. */+export interface MessagingInboundMessage {+ /** Channel-scoped chat id (the reply target for direct chats). */+ chatId: string;+ /** Direct chat with the bot, or a group chat (groups prefer reply-to-message). */+ chatKind: "direct" | "group";+ /**+ * Channel-scoped id of the inbound message itself (the group reply target). Opaque to+ * the bridge: the connector both mints it here and consumes it in `replyText`, so a+ * channel whose native message ids are not globally unique encodes whatever context a+ * reply needs (Telegram packs `chatId:messageId`).+ */+ messageId: string;+ /**+ * The message's plain text; null for anything that is not a text message (stickers,+ * images, …) — the bridge answers those with the text-only notice.+ */+ text: string | null;+ /** Sender display name when the channel's event carries one. */+ senderName?: string;+}++export interface MessagingConnectorHandlers {+ onMessage(msg: MessagingInboundMessage): void | Promise<void>;+ /** The connection completed a handshake (may fire again after an automatic reconnect). */+ onReady?(): void;+ /** The connection failed and the channel gave up (or the initial connect failed). */+ onError?(err: unknown): void;+}++/** A live inbound event stream; `close` ends it (idempotent). */+export interface MessagingConnection {+ close(): void;+}++/**+ * A successful credential check's optional payload: a short human-readable label of the+ * account the credentials sign in as (Telegram: the bot's `@username`), surfaced in the+ * test endpoint's success feedback. Channels with no cheap label return null.+ */+export interface MessagingAccountInfo {+ accountLabel?: string;+}++/** Outbound half of one bound account. Every method throws on failure with a readable reason. */+export interface MessagingClient {+ /** Credential check (used by the test endpoint); resolving means the config signs in. */+ checkCredentials(): Promise<MessagingAccountInfo | null>;+ /** Sends a text message into a chat by chat id. */+ sendText(chatId: string, text: string): Promise<void>;+ /** Replies a text message to a specific inbound message (threads correctly in group chats). */+ replyText(messageId: string, text: string): Promise<void>;+}++export interface MessagingChannelConnector {+ readonly channel: MessagingChannel;+ /** Builds the outbound client for one stored config (throws on a malformed document). */+ createClient(config: Record<string, unknown>): Promise<MessagingClient>;+ /**+ * Opens the inbound event stream for one stored config. Resolves as soon as the+ * connection is constructed and connecting — lifecycle arrives via the handlers+ * (`onReady` / `onError`), because channels reconnect on their own and a single promise+ * cannot carry a lifecycle.+ */+ connect(+ config: Record<string, unknown>,+ handlers: MessagingConnectorHandlers,+ ): Promise<MessagingConnection>;+}diff --git a/packages/server/src/runtime/messaging/feishu-connector.ts b/packages/server/src/runtime/messaging/feishu-connector.tsnew file mode 100644index 00000000..724b9bb3--- /dev/null+++ b/packages/server/src/runtime/messaging/feishu-connector.ts@@ -0,0 +1,86 @@+/**+ * Feishu (Lark) messaging connector — the first implementation of the+ * MessagingChannelConnector seam (telegram-connector.ts is the second). It owns+ * everything Feishu-specific: the config document's shape, the SDK adapter behind it+ * (injectable for tests — see feishu-sdk.ts), and the reduction of+ * `im.message.receive_v1` events to the bridge's normalized inbound shape (text extracted+ * from the content JSON; anything non-text reads as `text: null`).+ */+import type {+ MessagingChannelConnector,+ MessagingClient,+ MessagingConnection,+ MessagingConnectorHandlers,+} from "./connector.js";+import type { FeishuCredentials, FeishuSdk } from "./feishu-sdk.js";++/** Default Feishu open-platform domain (Lark tenants override it in the form). */+export const FEISHU_DEFAULT_DOMAIN = "https://open.feishu.cn";++/** The Feishu binding's stored config document (`messaging_bindings.config_json`). */+export interface FeishuBindingConfig extends Record<string, unknown> {+ appId: string;+ appSecret: string;+ baseDomain: string;+}++/** Narrows a stored config document; throws a readable error on a malformed one. */+export function feishuConfigOf(config: Record<string, unknown>): FeishuBindingConfig {+ const { appId, appSecret } = config;+ const baseDomain = config.baseDomain ?? FEISHU_DEFAULT_DOMAIN;+ if (+ typeof appId !== "string" ||+ appId === "" ||+ typeof appSecret !== "string" ||+ appSecret === "" ||+ typeof baseDomain !== "string"+ ) {+ throw new Error("malformed feishu binding config (appId/appSecret/baseDomain)");+ }+ return { appId, appSecret, baseDomain };+}++/** The `text` field of a Feishu text message's content JSON (null when unparseable). */+function textOfContent(content: string): string | null {+ try {+ const parsed = JSON.parse(content) as { text?: unknown };+ return typeof parsed.text === "string" ? parsed.text : null;+ } catch {+ return null;+ }+}++export class FeishuConnector implements MessagingChannelConnector {+ readonly channel = "feishu" as const;++ constructor(private readonly sdk: FeishuSdk) {}++ private credsOf(config: Record<string, unknown>): FeishuCredentials {+ return feishuConfigOf(config);+ }++ createClient(config: Record<string, unknown>): Promise<MessagingClient> {+ // FeishuApiClient already satisfies MessagingClient member for member.+ return this.sdk.createClient(this.credsOf(config));+ }++ connect(+ config: Record<string, unknown>,+ handlers: MessagingConnectorHandlers,+ ): Promise<MessagingConnection> {+ return this.sdk.connect(this.credsOf(config), {+ onMessage: (evt) =>+ handlers.onMessage({+ chatId: evt.chatId,+ chatKind: evt.chatType === "p2p" ? "direct" : "group",+ messageId: evt.messageId,+ // Only `text` messages carry text; every other message type normalizes to null+ // (the bridge answers those with the text-only notice).+ text: evt.messageType === "text" ? textOfContent(evt.content) : null,+ ...(evt.senderName !== undefined ? { senderName: evt.senderName } : {}),+ }),+ ...(handlers.onReady ? { onReady: handlers.onReady } : {}),+ ...(handlers.onError ? { onError: handlers.onError } : {}),+ });+ }+}diff --git a/packages/server/src/runtime/messaging/feishu-sdk.ts b/packages/server/src/runtime/messaging/feishu-sdk.tsnew file mode 100644index 00000000..14046f25--- /dev/null+++ b/packages/server/src/runtime/messaging/feishu-sdk.ts@@ -0,0 +1,257 @@+/**+ * The Feishu (Lark) SDK seam: the narrow slice of `@larksuiteoapi/node-sdk` the Feishu+ * connector uses, behind an injectable factory so unit tests substitute a fake and never+ * open real network. The real implementation loads the SDK lazily (dynamic import on+ * first use): the SDK is CJS and heavyweight, and a server with no Feishu bindings never+ * pays for it.+ *+ * The SDK's own types are deliberately not imported — its bundled .d.ts is ~300k lines,+ * which would tax every typecheck for the handful of calls made here; the local interfaces+ * below are the contract, and the adapter casts the loaded module once.+ */++/** One credential set (a binding's stored values, or a test request's draft). */+export interface FeishuCredentials {+ appId: string;+ appSecret: string;+ /** Feishu open-platform domain, e.g. https://open.feishu.cn. */+ baseDomain: string;+}++/** One inbound `im.message.receive_v1` event, reduced to what the connector consumes. */+export interface FeishuInboundEvent {+ chatId: string;+ /** `p2p` for a direct chat with the bot, `group` for a group chat. */+ chatType: string;+ messageId: string;+ /** Feishu message type (`text`, `image`, `sticker`, …); only `text` is processed. */+ messageType: string;+ /** Raw message content JSON (for `text`: `{"text":"..."}`). */+ content: string;+ /** Sender display name when the event carries one (the standard event does not). */+ senderName?: string;+}++/** OpenAPI half of the seam: credential probe + text sends. Every method throws on failure. */+export interface FeishuApiClient {+ /**+ * Credential check: obtains a tenant access token (no scopes needed); throws with a+ * readable reason. Resolves null — the token exchange yields no account label to+ * surface (`MessagingClient.checkCredentials`' optional payload).+ */+ checkCredentials(): Promise<null>;+ /** Sends a text message into a chat by chat_id. */+ sendText(chatId: string, text: string): Promise<void>;+ /** Replies a text message to a specific inbound message (threads correctly in group chats). */+ replyText(messageId: string, text: string): Promise<void>;+}++export interface FeishuEventHandlers {+ onMessage(evt: FeishuInboundEvent): void | Promise<void>;+ /** The long connection completed a handshake (fires again after an automatic reconnect). */+ onReady?(): void;+ /** The connection failed and the SDK gave up (or the initial connect failed). */+ onError?(err: unknown): void;+}++/** A live long-connection event stream; `close` ends it (idempotent). */+export interface FeishuConnection {+ close(): void;+}++/** Factory the Feishu connector is built over: the production Lark adapter, or a test fake. */+export interface FeishuSdk {+ createClient(creds: FeishuCredentials): Promise<FeishuApiClient>;+ /**+ * Opens the long-connection event stream for one app. Resolves as soon as the client is+ * constructed and connecting — connection state arrives via the handlers (`onReady` /+ * `onError`), because the SDK reconnects on its own and a single promise cannot carry a+ * lifecycle.+ */+ connect(creds: FeishuCredentials, handlers: FeishuEventHandlers): Promise<FeishuConnection>;+}++// ---------------------------------------------------------------------------+// Production adapter over @larksuiteoapi/node-sdk+// ---------------------------------------------------------------------------++/** The slice of the SDK module the adapter instantiates (cast once at load). */+interface LarkModule {+ Client: new (params: {+ appId: string;+ appSecret: string;+ domain: string;+ loggerLevel: number;+ }) => LarkClient;+ WSClient: new (params: {+ appId: string;+ appSecret: string;+ domain: string;+ loggerLevel: number;+ autoReconnect: boolean;+ onReady?: () => void;+ onError?: (err: Error) => void;+ }) => LarkWsClient;+ EventDispatcher: new (params: Record<string, never>) => LarkEventDispatcher;+ LoggerLevel: { error: number };+}++/** `{code, msg}` response envelope shared by the SDK's OpenAPI calls (0 = success). */+interface LarkResponse {+ code?: number;+ msg?: string;+}++interface LarkClient {+ auth: {+ v3: {+ tenantAccessToken: {+ internal(payload: { data: { app_id: string; app_secret: string } }): Promise<LarkResponse>;+ };+ };+ };+ im: {+ v1: {+ message: {+ create(payload: {+ params: { receive_id_type: "chat_id" };+ data: { receive_id: string; content: string; msg_type: "text" };+ }): Promise<LarkResponse>;+ reply(payload: {+ path: { message_id: string };+ data: { content: string; msg_type: "text" };+ }): Promise<LarkResponse>;+ };+ };+ };+}++interface LarkWsClient {+ start(params: { eventDispatcher: LarkEventDispatcher }): Promise<void>;+ close(params?: { force?: boolean }): void;+}++interface LarkEventDispatcher {+ register(handlers: {+ "im.message.receive_v1": (data: {+ message: {+ message_id: string;+ chat_id: string;+ chat_type: string;+ message_type: string;+ content: string;+ };+ }) => Promise<void>;+ }): LarkEventDispatcher;+}++/** Readable failure text out of the SDK's throw shapes (axios errors carry the API body). */+function larkErrorText(err: unknown): string {+ const axios = err as { response?: { data?: { msg?: string; code?: number } }; message?: string };+ const body = axios.response?.data;+ if (body?.msg) return body.code !== undefined ? `${body.msg} (code ${body.code})` : body.msg;+ return err instanceof Error ? err.message : String(err);+}++/** Non-zero `{code}` envelopes come back as resolved responses; converge them to throws. */+function ensureOk(res: LarkResponse, what: string): void {+ if (res.code !== undefined && res.code !== 0) {+ throw new Error(`${what} failed: ${res.msg ?? "unknown error"} (code ${res.code})`);+ }+}++/** The production factory: lazy-loads the Lark SDK on first use. */+export function createLarkSdk(): FeishuSdk {+ let modPromise: Promise<LarkModule> | null = null;+ const load = (): Promise<LarkModule> => {+ modPromise ??= import("@larksuiteoapi/node-sdk").then(+ // CJS interop: depending on the loader the namespace or its `default` carries the exports.+ (m) => ((m as { default?: unknown }).default ?? m) as LarkModule,+ );+ return modPromise;+ };++ return {+ async createClient(creds: FeishuCredentials): Promise<FeishuApiClient> {+ const lark = await load();+ const client = new lark.Client({+ appId: creds.appId,+ appSecret: creds.appSecret,+ domain: creds.baseDomain,+ loggerLevel: lark.LoggerLevel.error,+ });+ return {+ async checkCredentials(): Promise<null> {+ let res: LarkResponse;+ try {+ res = await client.auth.v3.tenantAccessToken.internal({+ data: { app_id: creds.appId, app_secret: creds.appSecret },+ });+ } catch (err) {+ throw new Error(larkErrorText(err));+ }+ ensureOk(res, "Credential check");+ return null;+ },+ async sendText(chatId: string, text: string): Promise<void> {+ let res: LarkResponse;+ try {+ res = await client.im.v1.message.create({+ params: { receive_id_type: "chat_id" },+ data: { receive_id: chatId, content: JSON.stringify({ text }), msg_type: "text" },+ });+ } catch (err) {+ throw new Error(larkErrorText(err));+ }+ ensureOk(res, "Message send");+ },+ async replyText(messageId: string, text: string): Promise<void> {+ let res: LarkResponse;+ try {+ res = await client.im.v1.message.reply({+ path: { message_id: messageId },+ data: { content: JSON.stringify({ text }), msg_type: "text" },+ });+ } catch (err) {+ throw new Error(larkErrorText(err));+ }+ ensureOk(res, "Message reply");+ },+ };+ },++ async connect(+ creds: FeishuCredentials,+ handlers: FeishuEventHandlers,+ ): Promise<FeishuConnection> {+ const lark = await load();+ const dispatcher = new lark.EventDispatcher({}).register({+ "im.message.receive_v1": async (data) => {+ await handlers.onMessage({+ chatId: data.message.chat_id,+ chatType: data.message.chat_type,+ messageId: data.message.message_id,+ messageType: data.message.message_type,+ content: data.message.content,+ });+ },+ });+ const ws = new lark.WSClient({+ appId: creds.appId,+ appSecret: creds.appSecret,+ domain: creds.baseDomain,+ loggerLevel: lark.LoggerLevel.error,+ autoReconnect: true,+ ...(handlers.onReady ? { onReady: handlers.onReady } : {}),+ ...(handlers.onError ? { onError: handlers.onError } : {}),+ });+ // start() settles only once the connect flow does; failures surface through onError+ // (and are re-routed here for the shapes that reject instead), so connect() itself+ // stays non-blocking.+ void ws.start({ eventDispatcher: dispatcher }).catch((err: unknown) => {+ handlers.onError?.(err);+ });+ return { close: () => ws.close() };+ },+ };+}diff --git a/packages/server/src/runtime/messaging/telegram-api.ts b/packages/server/src/runtime/messaging/telegram-api.tsnew file mode 100644index 00000000..d55df3c0--- /dev/null+++ b/packages/server/src/runtime/messaging/telegram-api.ts@@ -0,0 +1,173 @@+/**+ * The Telegram Bot API seam: the three methods the Telegram connector uses (`getMe`,+ * `sendMessage`, `getUpdates`), behind an injectable transport so unit tests substitute a+ * fake and never open real network. Telegram needs no SDK — the Bot API is plain HTTPS+ * POSTs against https://api.telegram.org — so the production transport is a thin fetch+ * wrapper.+ *+ * Wire types below mirror the Bot API JSON verbatim (snake_case): the transport does not+ * reshape payloads, so a test fake constructs exactly what the real API returns.+ */++/** Telegram Bot API host. Deliberately not configurable: bindings carry only the token. */+export const TELEGRAM_API_BASE = "https://api.telegram.org";++/** One credential set (a binding's stored token, or a test request's draft). */+export interface TelegramCredentials {+ /** The whole credential: `<numeric bot id>:<secret>` as issued by @BotFather. */+ botToken: string;+}++/** `getMe` result — the slice of the Bot API `User` object the connector consumes. */+export interface TelegramBotUser {+ id: number;+ first_name?: string;+ username?: string;+}++/** The slice of a Bot API `Message` the connector consumes. */+export interface TelegramMessage {+ message_id: number;+ chat: {+ id: number;+ /** `private` for a direct chat with the bot; `group` / `supergroup` / `channel` otherwise. */+ type: string;+ };+ /** Present only for text messages; anything else (photo, sticker, voice, …) omits it. */+ text?: string;+ from?: {+ first_name?: string;+ username?: string;+ };+}++/** One `getUpdates` entry. Only `message` updates are processed; the rest are skipped. */+export interface TelegramUpdate {+ update_id: number;+ message?: TelegramMessage;+}++/** Bot API half of the seam, bound to one token. Every method throws on failure with a readable reason. */+export interface TelegramBotClient {+ /** Credential probe: resolves the bot's own account (the test endpoint surfaces its username). */+ getMe(): Promise<TelegramBotUser>;+ /** Sends a text message into a chat; `replyToMessageId` threads it under an inbound message. */+ sendMessage(args: { chatId: string; text: string; replyToMessageId?: number }): Promise<void>;+ /**+ * Long-poll for updates: blocks up to `timeoutSec` (0 = return immediately) and resolves+ * the pending updates at or after `offset` (confirming everything before it; -1 means+ * "the newest update only", the connector's connect-time backlog drain). `signal` aborts+ * an in-flight poll when the connection closes.+ */+ getUpdates(args: {+ offset?: number;+ timeoutSec: number;+ signal: AbortSignal;+ }): Promise<TelegramUpdate[]>;+}++/** Factory the Telegram connector is built over: the production fetch adapter, or a test fake. */+export interface TelegramTransport {+ createClient(creds: TelegramCredentials): TelegramBotClient;+}++// ---------------------------------------------------------------------------+// Production adapter over fetch+// ---------------------------------------------------------------------------++/** Overall per-request deadline for the short calls (getMe / sendMessage / the drain). */+const CALL_TIMEOUT_MS = 15_000;++/** The `{ok, result, description, error_code}` envelope every Bot API response carries. */+interface TelegramEnvelope<T> {+ ok?: boolean;+ result?: T;+ description?: string;+ error_code?: number;+}++/**+ * Readable failure text out of fetch's throw shapes. The request URL embeds the bot+ * token, so nothing here may echo the URL — only the cause's own message (connect/DNS+ * errors name the address, never the path).+ */+function fetchErrorText(err: unknown): string {+ if (err instanceof Error) {+ if (err.name === "TimeoutError" || err.name === "AbortError") return "request timed out";+ const cause = (err as { cause?: unknown }).cause;+ if (cause instanceof Error && cause.message !== "") return cause.message;+ return err.message;+ }+ return String(err);+}++/** The production factory: plain HTTPS against the Bot API. */+export function createTelegramTransport(): TelegramTransport {+ return {+ createClient(creds: TelegramCredentials): TelegramBotClient {+ const call = async <T>(+ method: string,+ payload: Record<string, unknown>,+ opts?: { signal?: AbortSignal; timeoutMs?: number },+ ): Promise<T> => {+ const deadline = AbortSignal.timeout(opts?.timeoutMs ?? CALL_TIMEOUT_MS);+ const signal = opts?.signal ? AbortSignal.any([opts.signal, deadline]) : deadline;+ let res: Response;+ try {+ res = await fetch(`${TELEGRAM_API_BASE}/bot${creds.botToken}/${method}`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(payload),+ signal,+ });+ } catch (err) {+ throw new Error(`${method} failed: ${fetchErrorText(err)}`);+ }+ const body = (await res.json().catch(() => null)) as TelegramEnvelope<T> | null;+ if (body === null || body.ok !== true) {+ const detail = body?.description ?? `HTTP ${res.status}`;+ const code = body?.error_code !== undefined ? ` (code ${body.error_code})` : "";+ throw new Error(`${method} failed: ${detail}${code}`);+ }+ return body.result as T;+ };++ // Chat ids are stored as text; the API wants the numeric form back (a string works+ // for @channel usernames only), so safe integers are converted.+ const wireChatId = (chatId: string): number | string => {+ const n = Number(chatId);+ return Number.isSafeInteger(n) && chatId.trim() !== "" ? n : chatId;+ };++ return {+ getMe: () => call<TelegramBotUser>("getMe", {}),+ async sendMessage({ chatId, text, replyToMessageId }): Promise<void> {+ await call("sendMessage", {+ chat_id: wireChatId(chatId),+ text,+ // Degrade to a plain send when the replied-to message is gone, rather than fail.+ ...(replyToMessageId !== undefined+ ? {+ reply_parameters: {+ message_id: replyToMessageId,+ allow_sending_without_reply: true,+ },+ }+ : {}),+ });+ },+ getUpdates: ({ offset, timeoutSec, signal }) =>+ call<TelegramUpdate[]>(+ "getUpdates",+ {+ timeout: timeoutSec,+ allowed_updates: ["message"],+ ...(offset !== undefined ? { offset } : {}),+ },+ // The overall deadline must outlive the server-side long poll.+ { signal, timeoutMs: (timeoutSec + 15) * 1000 },+ ),+ };+ },+ };+}diff --git a/packages/server/src/runtime/messaging/telegram-connector.ts b/packages/server/src/runtime/messaging/telegram-connector.tsnew file mode 100644index 00000000..3bbc3493--- /dev/null+++ b/packages/server/src/runtime/messaging/telegram-connector.ts@@ -0,0 +1,221 @@+/**+ * Telegram messaging connector — the second implementation of the+ * MessagingChannelConnector seam, and the proof the seam is channel-neutral. It owns+ * everything Telegram-specific: the config document's shape (a single bot token), the+ * Bot API transport behind it (injectable for tests — see telegram-api.ts), and the+ * inbound side as a `getUpdates` long-poll loop — Telegram pushes nothing without a+ * public webhook URL, so the connector pulls, which keeps local deployments working+ * exactly like the Feishu long connection does.+ *+ * The poll loop's lifecycle: one `getMe` probe (a bad token surfaces immediately as the+ * connection error instead of an eternally failing poll), then a one-time backlog drain+ * (`offset: -1` confirms everything sent while no connection existed — a disabled binding+ * must not replay its dark period as a task flood, matching Feishu, where missed events+ * are simply gone), then long polls advancing `offset` past each processed update.+ * Failures back off exponentially and report once per outage; recovery re-probes and+ * fires `onReady` again, so the bridge's status tracks the outage. A save-while-enabled+ * restart can briefly race Telegram's one-poller-per-token rule (409 until the server+ * notices the old poll is gone) — that resolves through the same retry path.+ */+import type {+ MessagingChannelConnector,+ MessagingClient,+ MessagingConnection,+ MessagingConnectorHandlers,+ MessagingInboundMessage,+} from "./connector.js";+import type {+ TelegramBotClient,+ TelegramCredentials,+ TelegramTransport,+ TelegramUpdate,+} from "./telegram-api.js";++/** The Telegram binding's stored config document (`messaging_bindings.config_json`). */+export interface TelegramBindingConfig extends Record<string, unknown> {+ botToken: string;+}++/**+ * The token shape @BotFather issues: `<numeric bot id>:<secret>`. The id half is the+ * channel-scoped account identity (`messaging_bindings.account_id`), which is what makes+ * per-bot uniqueness robust against token rotation — a re-issued token keeps the id.+ */+const TELEGRAM_TOKEN_RE = /^(\d+):[A-Za-z0-9_-]{5,}$/;++/** The numeric bot id in front of the token's colon, or null when the token is malformed. */+export function telegramBotIdOf(botToken: string): string | null {+ const m = TELEGRAM_TOKEN_RE.exec(botToken);+ return m === null ? null : m[1]!;+}++/** Narrows a stored config document; throws a readable error on a malformed one. */+export function telegramConfigOf(config: Record<string, unknown>): TelegramBindingConfig {+ const { botToken } = config;+ if (typeof botToken !== "string" || botToken === "") {+ throw new Error("malformed telegram binding config (botToken)");+ }+ return { botToken };+}++/** Long-poll window. Telegram holds the request open up to this long when no update is pending. */+const POLL_TIMEOUT_SEC = 30;++/** Poll-failure backoff: 1s doubling to a 60s ceiling (a revoked token retries once a minute). */+function defaultRetryDelayMs(failures: number): number {+ return Math.min(1000 * 2 ** (failures - 1), 60_000);+}++export interface TelegramConnectorOpts {+ /** Test hook: backoff between failed polls (default: exponential, 1s → 60s). */+ retryDelayMs?: (failures: number) => number;+}++/** Reply refs pack the chat id in with the message id: Telegram message ids are only unique per chat. */+function replyRefOf(chatId: number, messageId: number): string {+ return `${chatId}:${messageId}`;+}++function parseReplyRef(ref: string): { chatId: string; messageId: number } {+ const i = ref.indexOf(":");+ const messageId = i >= 0 ? Number(ref.slice(i + 1)) : NaN;+ if (i <= 0 || !Number.isSafeInteger(messageId)) {+ throw new Error(`malformed telegram reply ref "${ref}"`);+ }+ return { chatId: ref.slice(0, i), messageId };+}++/** Abortable sleep (the backoff must not outlive a closed connection). */+function sleep(ms: number, signal: AbortSignal): Promise<void> {+ return new Promise((resolve) => {+ if (signal.aborted || ms <= 0) {+ resolve();+ return;+ }+ const timer = setTimeout(done, ms);+ function done(): void {+ signal.removeEventListener("abort", done);+ clearTimeout(timer);+ resolve();+ }+ signal.addEventListener("abort", done);+ });+}++/** One update reduced to the bridge's normalized shape; null for updates that are not chat messages. */+function normalizeUpdate(update: TelegramUpdate): MessagingInboundMessage | null {+ const msg = update.message;+ if (msg === undefined) return null;+ const senderName = msg.from?.first_name ?? msg.from?.username;+ return {+ chatId: String(msg.chat.id),+ chatKind: msg.chat.type === "private" ? "direct" : "group",+ messageId: replyRefOf(msg.chat.id, msg.message_id),+ // Only text messages carry `text`; every other message type normalizes to null (the+ // bridge answers those with the text-only notice).+ text: typeof msg.text === "string" ? msg.text : null,+ ...(senderName !== undefined ? { senderName } : {}),+ };+}++export class TelegramConnector implements MessagingChannelConnector {+ readonly channel = "telegram" as const;+ private readonly retryDelayMs: (failures: number) => number;++ constructor(+ private readonly transport: TelegramTransport,+ opts: TelegramConnectorOpts = {},+ ) {+ this.retryDelayMs = opts.retryDelayMs ?? defaultRetryDelayMs;+ }++ private credsOf(config: Record<string, unknown>): TelegramCredentials {+ return telegramConfigOf(config);+ }++ async createClient(config: Record<string, unknown>): Promise<MessagingClient> {+ const bot = this.transport.createClient(this.credsOf(config));+ return {+ async checkCredentials() {+ const me = await bot.getMe();+ return me.username !== undefined ? { accountLabel: `@${me.username}` } : null;+ },+ async sendText(chatId, text) {+ await bot.sendMessage({ chatId, text });+ },+ async replyText(messageRef, text) {+ const { chatId, messageId } = parseReplyRef(messageRef);+ await bot.sendMessage({ chatId, text, replyToMessageId: messageId });+ },+ };+ }++ async connect(+ config: Record<string, unknown>,+ handlers: MessagingConnectorHandlers,+ ): Promise<MessagingConnection> {+ const bot = this.transport.createClient(this.credsOf(config));+ const abort = new AbortController();+ let closed = false;+ void this.poll(bot, handlers, abort.signal, () => closed);+ return {+ close: () => {+ closed = true;+ abort.abort();+ },+ };+ }++ private async poll(+ bot: TelegramBotClient,+ handlers: MessagingConnectorHandlers,+ signal: AbortSignal,+ isClosed: () => boolean,+ ): Promise<void> {+ /** Probe + drain done and onReady fired for the current up-streak. */+ let ready = false;+ /** The backlog drain runs once per connection, never again after an outage: messages sent during a mere blip still deliver. */+ let drained = false;+ let failures = 0;+ let offset: number | undefined;+ while (!isClosed()) {+ try {+ if (!ready) {+ await bot.getMe();+ if (isClosed()) return;+ if (!drained) {+ const backlog = await bot.getUpdates({ offset: -1, timeoutSec: 0, signal });+ if (isClosed()) return;+ const newest = backlog.at(-1);+ if (newest !== undefined) offset = newest.update_id + 1;+ drained = true;+ }+ ready = true;+ failures = 0;+ handlers.onReady?.();+ continue;+ }+ const updates = await bot.getUpdates({+ ...(offset !== undefined ? { offset } : {}),+ timeoutSec: POLL_TIMEOUT_SEC,+ signal,+ });+ if (isClosed()) return;+ failures = 0;+ for (const update of updates) {+ offset = update.update_id + 1;+ const msg = normalizeUpdate(update);+ if (msg !== null) await handlers.onMessage(msg);+ }+ } catch (err) {+ if (isClosed()) return;+ failures += 1;+ // One report per outage: the first failure flips the bridge to `error` and lands+ // one error record; the retries stay quiet until recovery re-fires onReady.+ if (failures === 1) handlers.onError?.(err);+ ready = false;+ await sleep(this.retryDelayMs(failures), signal);+ }+ }+ }+}diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.tsindex 7c480f58..c1fb0d23 100644--- a/packages/server/src/services/session-service.ts+++ b/packages/server/src/services/session-service.ts@@ -18,6 +18,7 @@ import { agentsDir, createAgent, isSessionMeta } from "@prismshadow/penguin-coreimport type { ControlEnvContext, ProxyEnvPolicy } from "@prismshadow/penguin-core";import type {ApprovalMode,+ MessagingChannel,SessionCategory,SessionCategoryCounts,SessionInfo,@@ -65,6 +66,14 @@ export interface SessionServiceDeps {* agents can drive the harness back through the CLI/API.*/controlEnv?: (ctx: ControlEnvContext) => Record<string, string>;+ /**+ * The channel of the Session's ENABLED messaging binding, or null when none is enabled+ * (SessionInfo.messagingChannel, the sidebar row's per-channel indicator — saved-but-+ * disabled configs stay off the row). A lookup lambda rather than the repo, so the+ * service stays decoupled from the bindings table; absent (older assemblies/tests)+ * means the field is never set.+ */+ messagingChannel?: (sessionId: string) => MessagingChannel | null;}export class SessionService {@@ -78,6 +87,7 @@ export class SessionService {*/async toInfo(row: SessionRow, hasTrace: boolean): Promise<SessionInfo> {const source = await this.sourceOf(row, hasTrace);+ const messagingChannel = this.deps.messagingChannel?.(row.sessionId) ?? null;return {sessionId: row.sessionId,projectId: row.projectId,@@ -96,6 +106,7 @@ export class SessionService {pendingFollowUpCount: this.deps.manager.pendingFollowUpCount(row.sessionId),hasTrace,archived: (row.archivedAt ?? null) !== null,+ ...(messagingChannel !== null ? { messagingChannel } : {}),};}diff --git a/packages/server/test/messaging-telegram.test.ts b/packages/server/test/messaging-telegram.test.tsnew file mode 100644index 00000000..37af19f7--- /dev/null+++ b/packages/server/test/messaging-telegram.test.ts@@ -0,0 +1,708 @@+/**+ * 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+ * 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,+ * per-message mirroring with one reply thread per run in groups, 4096-safe chunking,+ * non-text notices, and poll-failure status flips. No test opens real network.+ */+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { assistantText } from "@prismshadow/penguin-core";+import type { OmniMessage, TextPayload } from "@prismshadow/penguin-core";+import type {+ FeishuBindingResponse,+ MessagingBindingsResponse,+ TelegramBindingResponse,+ TelegramTestResponse,+} from "../src/api/types.js";+import type { SessionRow } from "../src/db/repos/sessions.js";+import type { RuntimeSession } from "../src/runtime/session-manager.js";+import {+ MESSAGING_TEXT_ONLY_NOTICE,+ MESSAGING_TEST_MESSAGE,+} from "../src/runtime/messaging/bridge.js";+import type {+ TelegramBotClient,+ TelegramBotUser,+ TelegramCredentials,+ TelegramUpdate,+} from "../src/runtime/messaging/telegram-api.js";+import { telegramBotIdOf } from "../src/runtime/messaging/telegram-connector.js";+import type {+ FeishuApiClient,+ FeishuCredentials,+ FeishuEventHandlers,+ FeishuSdk,+} from "../src/runtime/messaging/feishu-sdk.js";+import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";+import type { TestApp } from "./helpers.js";++const SID = "session-2026-08-26-10-00-00-t9000001";+const SID2 = "session-2026-08-26-10-00-01-t9000002";+const BASE = (sid: string) => `/api/sessions/${sid}/messaging/telegram`;+const TOKEN = "7000000001:test-secret-AAAA-1111";++// ---------------------------------------------------------------------------+// Fake transport: one shared server-side update queue (as Telegram holds one per bot),+// per-client send records, and parked long polls the tests resolve by pushing updates.+// ---------------------------------------------------------------------------++interface SentMessage {+ chatId: string;+ text: string;+ replyTo?: number;+}++class FakeBotClient implements TelegramBotClient {+ readonly sends: SentMessage[] = [];+ getMeCalls = 0;+ /** A long poll is currently parked waiting for an update. */+ parked = false;+ /** A parked long poll was ended by the connection's abort (the close path ran). */+ sawAbort = false;+ constructor(+ readonly creds: TelegramCredentials,+ private readonly t: FakeTelegramTransport,+ ) {}++ async getMe(): Promise<TelegramBotUser> {+ this.getMeCalls++;+ if (this.t.failGetMe !== null) throw new Error(this.t.failGetMe);+ return {+ id: Number(telegramBotIdOf(this.creds.botToken) ?? "0"),+ first_name: "Penguin Test",+ username: "penguin_test_bot",+ };+ }++ async sendMessage(args: {+ chatId: string;+ text: string;+ replyToMessageId?: number;+ }): Promise<void> {+ if (this.t.failSend !== null) throw new Error(this.t.failSend);+ this.sends.push({+ chatId: args.chatId,+ text: args.text,+ ...(args.replyToMessageId !== undefined ? { replyTo: args.replyToMessageId } : {}),+ });+ }++ getUpdates(args: {+ offset?: number;+ timeoutSec: number;+ signal: AbortSignal;+ }): Promise<TelegramUpdate[]> {+ if (this.t.failPolls > 0) {+ this.t.failPolls--;+ return Promise.reject(new Error("poll failed"));+ }+ // Bot API semantics: a negative offset addresses updates from the end of the queue+ // (-1 = the newest one only) without confirming anything.+ if (args.offset === -1) {+ const newest = this.t.pending.at(-1);+ return Promise.resolve(newest !== undefined ? [newest] : []);+ }+ // A non-negative offset confirms (drops) everything before it; unconfirmed updates+ // are re-delivered, which is what makes the connector's offset bookkeeping visible.+ if (args.offset !== undefined) {+ this.t.pending = this.t.pending.filter((u) => u.update_id >= args.offset!);+ }+ if (this.t.pending.length > 0 || args.timeoutSec === 0) {+ return Promise.resolve([...this.t.pending]);+ }+ return new Promise((resolve, reject) => {+ const waiter = (updates: TelegramUpdate[]) => {+ args.signal.removeEventListener("abort", onAbort);+ this.parked = false;+ resolve(updates);+ };+ const onAbort = () => {+ this.t.waiters = this.t.waiters.filter((w) => w !== waiter);+ this.parked = false;+ this.sawAbort = true;+ reject(new Error("aborted"));+ };+ if (args.signal.aborted) {+ onAbort();+ return;+ }+ args.signal.addEventListener("abort", onAbort, { once: true });+ this.parked = true;+ this.t.waiters.push(waiter);+ });+ }+}++class FakeTelegramTransport {+ readonly clients: FakeBotClient[] = [];+ /** The bot's server-side update queue (survives reconnects, seeds the drain). */+ pending: TelegramUpdate[] = [];+ waiters: Array<(updates: TelegramUpdate[]) => void> = [];+ /** Non-null makes getMe throw with this message. */+ failGetMe: string | null = null;+ /** Non-null makes sendMessage throw with this message. */+ failSend: string | null = null;+ /** Fails this many upcoming getUpdates calls. */+ failPolls = 0;+ private nextUpdateId = 100;++ createClient(creds: TelegramCredentials): FakeBotClient {+ const client = new FakeBotClient(creds, this);+ this.clients.push(client);+ return client;+ }++ /** A new inbound update: queued, and every parked long poll resolves with the queue. */+ push(message: TelegramUpdate["message"]): void {+ this.pending.push({ update_id: this.nextUpdateId++, message: message! });+ const waiters = this.waiters;+ this.waiters = [];+ for (const w of waiters) w([...this.pending]);+ }++ /** A non-message update (edited_message, chat-member change, …): no `message` field. */+ pushNonMessage(): void {+ this.pending.push({ update_id: this.nextUpdateId++ });+ const waiters = this.waiters;+ this.waiters = [];+ for (const w of waiters) w([...this.pending]);+ }++ lastClient(): FakeBotClient {+ const client = this.clients.at(-1);+ if (!client) throw new Error("no fake telegram client was created");+ return client;+ }++ allSends(): SentMessage[] {+ return this.clients.flatMap((c) => c.sends);+ }+}++/**+ * Minimal fake Feishu SDK for the cross-channel tests (enabling the feishu side must not+ * import the real Lark SDK or open network): connects instantly, records nothing.+ */+class FakeFeishuSdk implements FeishuSdk {+ async createClient(_creds: FeishuCredentials): Promise<FeishuApiClient> {+ return {+ async checkCredentials() {+ return null;+ },+ async sendText() {},+ async replyText() {},+ };+ }+ async connect(_creds: FeishuCredentials, handlers: FeishuEventHandlers) {+ handlers.onReady?.();+ return { close: () => {} };+ }+}++/** A private-chat text message from a fixed user. */+function privateText(text: string, messageId = 1): TelegramUpdate["message"] {+ return {+ message_id: messageId,+ chat: { id: 42424242, type: "private" },+ text,+ from: { first_name: "Ada" },+ };+}++/** Fake Session: records each run's input payloads and replies with a fixed assistant text. */+function echoFakeSession(+ sessionId: string,+ runs: TextPayload[][],+ reply = "Reply text",+): RuntimeSession {+ return {+ sessionId,+ toolPermission: () => "rw",+ generateTitle: async () => ({ title: null, usage: null }),+ compactability: () => "ok" as const,+ steer: () => false,+ skipReconnectWait: () => false,+ async *run(input: OmniMessage[]) {+ runs.push(input.map((m) => m.payload as TextPayload));+ yield assistantText(reply);+ },+ async *compact() {},+ };+}++/**+ * Fake Session that completes several assistant messages in ONE run. `gate`, when given,+ * holds the last message back: what lets a test observe the earlier ones already in the+ * chat while the run is still running.+ */+function multiMessageFakeSession(+ sessionId: string,+ texts: readonly string[],+ gate?: Promise<void>,+): RuntimeSession {+ return {+ sessionId,+ toolPermission: () => "rw",+ generateTitle: async () => ({ title: null, usage: null }),+ compactability: () => "ok" as const,+ steer: () => false,+ skipReconnectWait: () => false,+ async *run() {+ for (let i = 0; i < texts.length; i += 1) {+ if (gate !== undefined && i === texts.length - 1) await gate;+ yield assistantText(texts[i]!);+ }+ },+ async *compact() {},+ };+}++function sessionRowOf(sessionId: string, projectId: string): SessionRow {+ return {+ sessionId,+ projectId,+ agentId: "default_agent",+ provider: "custom",+ modelId: "m1",+ workspace: "/tmp/w",+ approvalMode: "allow-all",+ title: null,+ createdAt: new Date().toISOString(),+ lastActiveAt: new Date().toISOString(),+ };+}++describe("telegramBotIdOf", () => {+ it("reads the numeric id in front of the colon and rejects malformed tokens", () => {+ expect(telegramBotIdOf(TOKEN)).toBe("7000000001");+ expect(telegramBotIdOf("no-colon")).toBeNull();+ expect(telegramBotIdOf("abc:def-ghi-jkl")).toBeNull();+ expect(telegramBotIdOf("123:")).toBeNull();+ });+});++describe("telegram binding routes and connector loop", () => {+ let t: TestApp;+ let api: ReturnType<typeof apiClient>;+ let fake: FakeTelegramTransport;+ let projectId: string;+ let runs: TextPayload[][];++ /** Save the token, then flip the toggle on and wait for the poll loop's handshake. */+ const bindEnabled = async (sid: string, botToken = TOKEN) => {+ expect((await api.put(BASE(sid), { botToken })).status).toBe(200);+ expect((await api.post(`${BASE(sid)}/state`, { enabled: true })).status).toBe(200);+ await waitFor(() => t.deps.messaging.statusOf(sid, "telegram").state === "connected");+ };++ beforeEach(async () => {+ fake = new FakeTelegramTransport();+ t = await createTestApp({+ telegramTransport: fake,+ telegramRetryDelayMs: () => 1,+ feishuSdk: new FakeFeishuSdk(),+ });+ const { cookie } = await provisionUser(t.app, "birder");+ api = apiClient(t.app, cookie);+ projectId = "birder-default_project";+ runs = [];+ const row = sessionRowOf(SID, projectId);+ t.deps.sessionsRepo.insert(row);+ t.deps.manager.adopt(row, echoFakeSession(SID, runs));+ });+ afterEach(async () => {+ await t.cleanup();+ });++ it("PUT saves the token only (masked, bot id extracted, disabled, no poll); blank keeps the stored token", async () => {+ const res = await api.put(BASE(SID), { botToken: TOKEN });+ expect(res.status).toBe(200);+ const body = (await res.json()) as TelegramBindingResponse;+ expect(body.binding?.channel).toBe("telegram");+ expect(body.binding?.botId).toBe("7000000001");+ // Site-wide mask rule: first4…last4, never the plaintext.+ expect(body.binding?.botTokenMasked).toBe("7000…1111");+ expect(JSON.stringify(body)).not.toContain(TOKEN);+ expect(body.binding?.enabled).toBe(false);+ expect(body.status.state).toBe("disconnected");+ expect(fake.clients).toHaveLength(0);+ const stored = t.deps.messagingRepo.find(SID, "telegram")!;+ expect(stored.channel).toBe("telegram");+ expect(stored.accountId).toBe("7000000001");++ // Re-save with a blank token: the stored one stays; still disabled, still dark.+ const resave = await api.put(BASE(SID), { botToken: "" });+ expect(resave.status).toBe(200);+ expect(t.deps.messagingRepo.find(SID, "telegram")?.config.botToken).toBe(TOKEN);+ expect(fake.clients).toHaveLength(0);++ // First-time bind without a token, and a token whose bot id cannot be read: refused.+ t.deps.messagingRepo.delete(SID, "telegram");+ const bare = await api.put(BASE(SID), {});+ expect(bare.status).toBe(400);+ expect(((await bare.json()) as { error: { code: string } }).error.code).toBe(+ "telegram_token_required",+ );+ const malformed = await api.put(BASE(SID), { botToken: "not-a-token" });+ expect(malformed.status).toBe(400);+ expect(((await malformed.json()) as { error: { code: string } }).error.code).toBe(+ "telegram_token_invalid",+ );+ });++ it("POST /state owns the connection: enable probes getMe and polls, disable aborts the poll", async () => {+ expect((await api.post(`${BASE(SID)}/state`, { enabled: true })).status).toBe(404);+ await api.put(BASE(SID), { botToken: TOKEN });++ const on = await api.post(`${BASE(SID)}/state`, { enabled: true });+ expect(on.status).toBe(200);+ expect(((await on.json()) as TelegramBindingResponse).binding?.enabled).toBe(true);+ await waitFor(() => t.deps.messaging.statusOf(SID, "telegram").state === "connected");+ // Connected with the STORED token — the toggle carries none of its own.+ expect(fake.lastClient().creds.botToken).toBe(TOKEN);+ expect(fake.lastClient().getMeCalls).toBeGreaterThan(0);+ await waitFor(() => fake.lastClient().parked);++ const off = await api.post(`${BASE(SID)}/state`, { enabled: false });+ const offBody = (await off.json()) as TelegramBindingResponse;+ expect(offBody.binding?.enabled).toBe(false);+ expect(offBody.status.state).toBe("disconnected");+ expect(fake.lastClient().sawAbort).toBe(true);+ });++ it("saving a new token while enabled restarts the poll loop with it (never-diverge rule)", async () => {+ await bindEnabled(SID);+ await waitFor(() => fake.lastClient().parked);+ const rotated = "7000000001:test-secret-BBBB-2222";+ const res = await api.put(BASE(SID), { botToken: rotated });+ expect(res.status).toBe(200);+ expect(((await res.json()) as TelegramBindingResponse).binding?.enabled).toBe(true);+ // The old poll was aborted and a fresh client runs on the just-saved token.+ expect(fake.clients[0]!.sawAbort).toBe(true);+ await waitFor(() => t.deps.messaging.statusOf(SID, "telegram").state === "connected");+ 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 });+ 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",+ );+ expect(t.deps.messagingRepo.find(SID2, "telegram")).toBeNull();+ });++ it("GET /messaging lists every saved channel config; both channels sit saved side by side", async () => {+ // Nothing saved: an empty list.+ const before = await api.get(`/api/sessions/${SID}/messaging`);+ expect((await before.json()) as MessagingBindingsResponse).toEqual({ bindings: [] });++ // Save BOTH channels (telegram enabled, feishu dark): both configs coexist.+ await bindEnabled(SID);+ const feishuSave = await api.put(`/api/sessions/${SID}/messaging/feishu`, {+ appId: "cli_side_by_side",+ appSecret: "feishu-secret-000111",+ });+ expect(feishuSave.status).toBe(200);+ // Saving the second channel must not disturb the first one's live connection.+ expect(t.deps.messaging.statusOf(SID, "telegram").state).toBe("connected");++ const res = await api.get(`/api/sessions/${SID}/messaging`);+ const body = (await res.json()) as MessagingBindingsResponse;+ expect(body.bindings.map((b) => b.binding.channel)).toEqual(["feishu", "telegram"]);+ const feishu = body.bindings[0]!;+ const telegram = body.bindings[1]!;+ expect(feishu.binding.enabled).toBe(false);+ expect(feishu.status.state).toBe("disconnected");+ expect(telegram.binding.enabled).toBe(true);+ expect(telegram.binding.channel === "telegram" && telegram.binding.botId).toBe("7000000001");+ expect(telegram.status.state).toBe("connected");+ expect(JSON.stringify(body)).not.toContain(TOKEN);+ expect(JSON.stringify(body)).not.toContain("feishu-secret-000111");++ // The feishu-scoped test-message probe still 409s on ITS channel's missing chat, not+ // the telegram one's.+ const probe = await api.post(`/api/sessions/${SID}/messaging/feishu/test-message`, {});+ expect(probe.status).toBe(409);+ expect(((await probe.json()) as { error: { code: string } }).error.code).toBe("feishu_no_chat");+ });++ it("enabling is mutually exclusive per Session: the second channel answers 409 another_channel_enabled", async () => {+ await bindEnabled(SID);+ await api.put(`/api/sessions/${SID}/messaging/feishu`, {+ appId: "cli_exclusive",+ appSecret: "feishu-secret-222333",+ });+ const refused = await api.post(`/api/sessions/${SID}/messaging/feishu/state`, {+ enabled: true,+ });+ expect(refused.status).toBe(409);+ expect(((await refused.json()) as { error: { code: string } }).error.code).toBe(+ "another_channel_enabled",+ );+ // Turn telegram off, and the same enable goes through (the telegram poll is aborted).+ expect((await api.post(`${BASE(SID)}/state`, { enabled: false })).status).toBe(200);+ expect(fake.lastClient().sawAbort).toBe(true);+ const on = await api.post(`/api/sessions/${SID}/messaging/feishu/state`, { enabled: true });+ expect(on.status).toBe(200);+ expect(((await on.json()) as FeishuBindingResponse).binding?.enabled).toBe(true);+ expect(t.deps.messaging.statusOf(SID, "telegram").state).toBe("disconnected");+ });++ it("the clear flag drops the stored token after disabling, and re-enabling is refused until one is saved", async () => {+ await bindEnabled(SID);+ const blocked = await api.put(BASE(SID), { clearBotToken: true });+ expect(blocked.status).toBe(409);+ expect(((await blocked.json()) as { error: { code: string } }).error.code).toBe(+ "messaging_disable_before_clear",+ );+ await api.post(`${BASE(SID)}/state`, { enabled: false });+ const cleared = await api.put(BASE(SID), { clearBotToken: true });+ expect(cleared.status).toBe(200);+ const body = (await cleared.json()) as TelegramBindingResponse;+ // No stored token -> no mask; the row keeps its bot identity.+ expect(body.binding?.botTokenMasked).toBeUndefined();+ expect(body.binding?.botId).toBe("7000000001");+ expect(t.deps.messagingRepo.find(SID, "telegram")?.config.botToken).toBe("");+ const on = await api.post(`${BASE(SID)}/state`, { enabled: true });+ expect(on.status).toBe(400);+ expect(((await on.json()) as { error: { code: string } }).error.code).toBe(+ "telegram_token_required",+ );+ });++ it("POST /test probes getMe and surfaces the bot username; failures are ok:false", async () => {+ const draft = await api.post(`${BASE(SID)}/test`, { botToken: TOKEN });+ expect(draft.status).toBe(200);+ const ok = (await draft.json()) as TelegramTestResponse;+ expect(ok.ok).toBe(true);+ expect(ok.botUsername).toBe("@penguin_test_bot");+ expect(typeof ok.latencyMs).toBe("number");++ // Stored fallback: an empty body tests the saved binding.+ await api.put(BASE(SID), { botToken: TOKEN });+ const stored = await api.post(`${BASE(SID)}/test`, {});+ expect(((await stored.json()) as TelegramTestResponse).ok).toBe(true);+ expect(fake.lastClient().creds.botToken).toBe(TOKEN);++ // A rejected token is ok:false with the reason, not an HTTP error.+ fake.failGetMe = "getMe failed: Unauthorized (code 401)";+ const bad = await api.post(`${BASE(SID)}/test`, {});+ expect(bad.status).toBe(200);+ expect((await bad.json()) as TelegramTestResponse).toEqual({+ ok: false,+ error: "getMe failed: Unauthorized (code 401)",+ });++ // No stored binding and no draft token: the telegram 400 shape.+ t.deps.messagingRepo.delete(SID, "telegram");+ const none = await api.post(`${BASE(SID)}/test`, {});+ expect(none.status).toBe(400);+ expect(((await none.json()) as { error: { code: string } }).error.code).toBe(+ "telegram_token_required",+ );+ });++ it("POST /test-message: 404 unbound, 409 telegram_no_chat before a chat is known, sends after one", async () => {+ expect((await api.post(`${BASE(SID)}/test-message`, {})).status).toBe(404);+ await bindEnabled(SID);+ const early = await api.post(`${BASE(SID)}/test-message`, {});+ expect(early.status).toBe(409);+ expect(((await early.json()) as { error: { code: string } }).error.code).toBe(+ "telegram_no_chat",+ );++ fake.push(privateText("hello"));+ await waitFor(() => t.deps.messagingRepo.find(SID, "telegram")?.lastChatId === "42424242");+ const res = await api.post(`${BASE(SID)}/test-message`, {});+ expect(res.status).toBe(200);+ expect(fake.allSends()).toContainEqual({+ chatId: "42424242",+ text: MESSAGING_TEST_MESSAGE,+ });+ });++ it("inbound text starts an ordinary user task (no marker, no sender), advances the offset, and mirrors the reply", async () => {+ await bindEnabled(SID);+ fake.push(privateText("how is the build?", 11));+ await waitFor(() => runs.length === 1);+ // Exactly as if typed into the web composer: the text verbatim, no marker block, and+ // the default human sender (no `sender` field at all).+ const input = runs[0]![0]!;+ expect(input.text).toBe("how is the build?");+ expect(input.role).toBe("user");+ expect("sender" in input).toBe(false);+ const row = t.deps.messagingRepo.find(SID, "telegram")!;+ expect(row.lastChatId).toBe("42424242");+ expect(row.lastChatIsDirect).toBe(true);+ // Task end mirrors the assistant text to that chat as a plain send (direct chat).+ await waitFor(() => fake.allSends().length > 0);+ expect(fake.allSends()).toContainEqual({ chatId: "42424242", text: "Reply text" });++ // A second message is processed exactly once: the loop confirmed the first update+ // via its offset, so nothing re-delivers.+ fake.push(privateText("second", 12));+ await waitFor(() => runs.length === 2);+ expect(runs.map((r) => r[0]!.text)).toEqual(["how is the build?", "second"]);+ });++ it("group messages thread the reply onto the inbound message; non-message updates are skipped", async () => {+ await bindEnabled(SID);+ // A non-message update (edited message, membership change, …): skipped entirely —+ // no task, no notice — but still confirmed by the advancing offset.+ fake.pushNonMessage();+ fake.push({+ message_id: 77,+ chat: { id: -1002233445566, type: "supergroup" },+ text: "ping from the group",+ from: { first_name: "Ada" },+ });+ await waitFor(() => runs.length === 1);+ const row = t.deps.messagingRepo.find(SID, "telegram")!;+ expect(row.lastChatId).toBe("-1002233445566");+ expect(row.lastChatIsDirect).toBe(false);+ await waitFor(() => fake.allSends().length > 0);+ // The reply names the chat AND the message: Telegram message ids are chat-scoped, so+ // the connector packs both into the reply ref.+ expect(fake.allSends()).toContainEqual({+ chatId: "-1002233445566",+ text: "Reply text",+ replyTo: 77,+ });+ });++ it("non-text messages get the bilingual text-only reply and start no task", async () => {+ await bindEnabled(SID);+ // A photo message: a `message` update with no `text` field.+ fake.push({+ message_id: 21,+ chat: { id: 42424242, type: "private" },+ from: { first_name: "Ada" },+ });+ await waitFor(() => fake.allSends().length > 0);+ expect(fake.allSends()).toContainEqual({+ chatId: "42424242",+ text: MESSAGING_TEXT_ONLY_NOTICE,+ });+ expect(runs).toHaveLength(0);+ // Even a rejected type teaches the bridge where the user is.+ expect(t.deps.messagingRepo.find(SID, "telegram")?.lastChatId).toBe("42424242");+ });++ it("relays each completed assistant message separately, in order, as it completes", async () => {+ const row2 = sessionRowOf(SID2, projectId);+ t.deps.sessionsRepo.insert(row2);+ let release = () => {};+ const gate = new Promise<void>((r) => {+ release = r;+ });+ t.deps.manager.adopt(row2, multiMessageFakeSession(SID2, ["step one", "step two"], gate));+ await bindEnabled(SID2, "7000000003:test-secret-EEEE-5555");+ fake.push(privateText("go"));+ // The first message is already in the chat while the run is still running.+ await waitFor(() => fake.allSends().length === 1);+ expect(t.deps.manager.statusOf(SID2)).toBe("running");+ expect(fake.allSends()).toEqual([{ chatId: "42424242", text: "step one" }]);+ release();+ await waitFor(() => fake.allSends().length === 2);+ expect(fake.allSends()).toEqual([+ { chatId: "42424242", text: "step one" },+ { chatId: "42424242", text: "step two" },+ ]);+ });++ it("in a group only the run's first message carries the reply ref", async () => {+ const row2 = sessionRowOf(SID2, projectId);+ t.deps.sessionsRepo.insert(row2);+ t.deps.manager.adopt(row2, multiMessageFakeSession(SID2, ["first", "second"]));+ await bindEnabled(SID2, "7000000004:test-secret-FFFF-6666");+ fake.push({+ message_id: 91,+ chat: { id: -1002233445566, type: "supergroup" },+ text: "ping",+ from: { first_name: "Ada" },+ });+ await waitFor(() => fake.allSends().length === 2);+ // One reply-to anchors the exchange; the follow-up is a plain send into the same chat.+ expect(fake.allSends()).toEqual([+ { chatId: "-1002233445566", text: "first", replyTo: 91 },+ { chatId: "-1002233445566", text: "second" },+ ]);+ });++ it("chunks a long reply under the shared 4000-char cap (inside Telegram's 4096 limit)", async () => {+ const row2 = sessionRowOf(SID2, projectId);+ t.deps.sessionsRepo.insert(row2);+ t.deps.manager.adopt(row2, echoFakeSession(SID2, runs, "x".repeat(9000)));+ await bindEnabled(SID2, "7000000002:test-secret-DDDD-4444");+ fake.push(privateText("long one"));+ await waitFor(() => fake.allSends().length >= 3);+ const sends = fake.allSends();+ expect(sends.map((s) => s.text.length)).toEqual([4000, 4000, 1000]);+ expect(sends.every((s) => s.chatId === "42424242")).toBe(true);+ expect(sends.map((s) => s.text).join("")).toBe("x".repeat(9000));+ });++ it("connect drains the dark-period backlog: only messages after enabling reach the Session", async () => {+ await api.put(BASE(SID), { botToken: TOKEN });+ // Messages sent while the binding was saved-but-disabled pile up server-side …+ fake.push(privateText("sent while dark", 1));+ fake.push(privateText("also dark", 2));+ expect((await api.post(`${BASE(SID)}/state`, { enabled: true })).status).toBe(200);+ await waitFor(() => t.deps.messaging.statusOf(SID, "telegram").state === "connected");+ // … and are skipped by the connect-time drain; only live traffic starts tasks.+ fake.push(privateText("live", 3));+ await waitFor(() => runs.length === 1);+ expect(runs[0]![0]!.text).toBe("live");+ });++ it("poll failures flip the status to error once and recovery re-probes back to connected", async () => {+ await bindEnabled(SID);+ await waitFor(() => fake.lastClient().parked);+ // Break the loop: the parked poll resolves with a message, the next poll fails, and+ // the recovery probe keeps failing until the outage ends.+ fake.failPolls = 1;+ fake.failGetMe = "getUpdates failed: ECONNRESET";+ fake.push(privateText("before the outage", 5));+ await waitFor(() => t.deps.messaging.statusOf(SID, "telegram").state === "error");+ fake.failGetMe = null;+ await waitFor(() => t.deps.messaging.statusOf(SID, "telegram").state === "connected");+ // The message delivered ahead of the failure was processed; recovery kept the offset,+ // so it does not re-deliver.+ await waitFor(() => runs.length === 1);+ fake.push(privateText("after recovery", 6));+ await waitFor(() => runs.length === 2);+ expect(runs.map((r) => r[0]!.text)).toEqual(["before the outage", "after recovery"]);+ });++ it("start() connects an enabled telegram binding with the stored token", async () => {+ t.deps.messagingRepo.upsert({+ sessionId: SID,+ channel: "telegram",+ accountId: "7000000001",+ config: { botToken: TOKEN },+ });+ t.deps.messagingRepo.setEnabled(SID, "telegram", true);+ await t.deps.messaging.start();+ await waitFor(() => t.deps.messaging.statusOf(SID, "telegram").state === "connected");+ expect(fake.lastClient().creds.botToken).toBe(TOKEN);+ await waitFor(() => fake.lastClient().parked);+ t.deps.messaging.stop();+ expect(fake.lastClient().sawAbort).toBe(true);+ });++ it("the session list marks a telegram-ENABLED row with messagingChannel telegram", async () => {+ await bindEnabled(SID);+ const res = await api.get(`/api/projects/${projectId}/agents/default_agent/sessions`);+ const body = (await res.json()) as {+ sessions: Array<{ sessionId: string; messagingChannel?: string }>;+ };+ expect(body.sessions.find((s) => s.sessionId === SID)?.messagingChannel).toBe("telegram");+ });+});diff --git a/packages/server/test/messaging.test.ts b/packages/server/test/messaging.test.tsnew file mode 100644index 00000000..fdc666b0--- /dev/null+++ b/packages/server/test/messaging.test.ts@@ -0,0 +1,699 @@+/**+ * Messaging-binding tests, Feishu side (the Telegram connector's mirror suite is+ * messaging-telegram.test.ts): the repo's two uniqueness rules, 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+ * Feishu SDK — inbound text becomes an ordinary user task+ * exactly as if typed in the composer (no marker, no special sender; queueIfBusy),+ * non-text gets the bilingual text-only reply, each completed assistant message mirrors on+ * its own to the last known chat as soon as it completes (the run's first one threaded onto+ * the inbound message in groups), and an approval_request sends the one-line notice. No+ * test opens real network.+ */+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import {+ assistantText,+ approvalDecision,+ compactionBegin,+ compactionEnd,+ toolCall,+} from "@prismshadow/penguin-core";+import type { ApproveFn, OmniMessage, TextPayload } from "@prismshadow/penguin-core";+import type { FeishuBindingResponse, FeishuTestResponse } from "../src/api/types.js";+import type { SessionRow } from "../src/db/repos/sessions.js";+import type { RuntimeSession } from "../src/runtime/session-manager.js";+import {+ MESSAGING_APPROVAL_NOTICE,+ MESSAGING_TEST_MESSAGE,+ MESSAGING_TEXT_ONLY_NOTICE,+ chunkMessagingText,+} from "../src/runtime/messaging/bridge.js";+import type {+ FeishuApiClient,+ FeishuCredentials,+ FeishuEventHandlers,+ FeishuInboundEvent,+ FeishuSdk,+} from "../src/runtime/messaging/feishu-sdk.js";+import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";+import type { TestApp } from "./helpers.js";++const SID = "session-2026-08-25-10-00-00-fe15aa01";+const SID2 = "session-2026-08-25-10-00-01-fe15aa02";+const BASE = (sid: string) => `/api/sessions/${sid}/messaging/feishu`;++// ---------------------------------------------------------------------------+// Fake SDK: records every client call and hands inbound events back to the connector.+// ---------------------------------------------------------------------------++interface SentText {+ kind: "send" | "reply";+ target: string;+ text: string;+}++class FakeClient implements FeishuApiClient {+ readonly sends: SentText[] = [];+ checks = 0;+ constructor(+ readonly creds: FeishuCredentials,+ private readonly sdk: FakeSdk,+ ) {}+ async checkCredentials(): Promise<null> {+ this.checks++;+ if (this.sdk.failCheck !== null) throw new Error(this.sdk.failCheck);+ return null;+ }+ async sendText(chatId: string, text: string): Promise<void> {+ this.sends.push({ kind: "send", target: chatId, text });+ }+ async replyText(messageId: string, text: string): Promise<void> {+ this.sends.push({ kind: "reply", target: messageId, text });+ }+}++class FakeConnection {+ closed = false;+ constructor(+ readonly creds: FeishuCredentials,+ readonly handlers: FeishuEventHandlers,+ ) {}+ close(): void {+ this.closed = true;+ }+ fire(evt: FeishuInboundEvent): Promise<void> {+ return Promise.resolve(this.handlers.onMessage(evt));+ }+}++class FakeSdk implements FeishuSdk {+ readonly clients: FakeClient[] = [];+ readonly connections: FakeConnection[] = [];+ /** Non-null makes checkCredentials throw with this message. */+ failCheck: string | null = null;+ async createClient(creds: FeishuCredentials): Promise<FeishuApiClient> {+ const client = new FakeClient(creds, this);+ this.clients.push(client);+ return client;+ }+ async connect(creds: FeishuCredentials, handlers: FeishuEventHandlers): Promise<FakeConnection> {+ const conn = new FakeConnection(creds, handlers);+ this.connections.push(conn);+ handlers.onReady?.();+ return conn;+ }+ /** All texts sent through any client, in order. */+ allSends(): SentText[] {+ return this.clients.flatMap((c) => c.sends);+ }+ lastConnection(): FakeConnection {+ const conn = this.connections.at(-1);+ if (!conn) throw new Error("no fake connection was opened");+ return conn;+ }+}++/** Fake Session: records each run's input payloads and replies with a fixed assistant text. */+function echoFakeSession(+ sessionId: string,+ runs: TextPayload[][],+ reply = "Reply text",+): RuntimeSession {+ return {+ sessionId,+ toolPermission: () => "rw",+ generateTitle: async () => ({ title: null, usage: null }),+ compactability: () => "ok" as const,+ steer: () => false,+ skipReconnectWait: () => false,+ async *run(input: OmniMessage[]) {+ runs.push(input.map((m) => m.payload as TextPayload));+ yield assistantText(reply);+ },+ async *compact() {},+ };+}++/** Fake Session that parks on one approval per run (drives an approval_request event). */+function parkingFakeSession(sessionId: string): RuntimeSession {+ return {+ sessionId,+ toolPermission: () => "rw",+ generateTitle: async () => ({ title: null, usage: null }),+ compactability: () => "ok" as const,+ steer: () => false,+ skipReconnectWait: () => false,+ async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {+ const tc = toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-feishu" });+ yield tc;+ const decision = await opts.approve(tc);+ yield approvalDecision(decision, "tc-feishu");+ yield assistantText("after approval");+ },+ async *compact() {},+ };+}++/**+ * Fake Session that completes several assistant messages in ONE run. `gate`, when given,+ * holds the last message back: what lets a test observe the earlier ones already in the+ * chat while the run is still running.+ */+function multiMessageFakeSession(+ sessionId: string,+ texts: readonly string[],+ gate?: Promise<void>,+): RuntimeSession {+ return {+ sessionId,+ toolPermission: () => "rw",+ generateTitle: async () => ({ title: null, usage: null }),+ compactability: () => "ok" as const,+ steer: () => false,+ skipReconnectWait: () => false,+ async *run() {+ for (let i = 0; i < texts.length; i += 1) {+ if (gate !== undefined && i === texts.length - 1) await gate;+ yield assistantText(texts[i]!);+ }+ },+ async *compact() {},+ };+}++/** Fake Session that streams a compaction summary mid-run, then the actual answer. */+function compactingFakeSession(sessionId: string): RuntimeSession {+ const bounds = { reason: "context", mode: "summarize" } as const;+ return {+ sessionId,+ toolPermission: () => "rw",+ generateTitle: async () => ({ title: null, usage: null }),+ compactability: () => "ok" as const,+ steer: () => false,+ skipReconnectWait: () => false,+ async *run() {+ yield compactionBegin({ ...bounds, context: 90, turns: 12 });+ yield assistantText("SUMMARY that is not a reply");+ yield compactionEnd({ ...bounds, status: "completed" });+ yield assistantText("the actual answer");+ },+ async *compact() {},+ };+}++function sessionRowOf(sessionId: string, projectId: string): SessionRow {+ return {+ sessionId,+ projectId,+ agentId: "default_agent",+ provider: "custom",+ modelId: "m1",+ workspace: "/tmp/w",+ approvalMode: "allow-all",+ title: null,+ createdAt: new Date().toISOString(),+ lastActiveAt: new Date().toISOString(),+ };+}++const PUT_BODY = {+ appId: "cli_test_app_0001",+ appSecret: "secret-value-abcdef-123456",+ baseDomain: "https://open.feishu.cn",+};++describe("chunkMessagingText", () => {+ it("returns short text whole and splits long text at newline boundaries under the cap", () => {+ expect(chunkMessagingText("short")).toEqual(["short"]);+ const chunks = chunkMessagingText(`${"a".repeat(30)}\n${"b".repeat(30)}`, 40);+ expect(chunks).toEqual(["a".repeat(30), "b".repeat(30)]);+ // No usable newline: a hard split at the cap.+ const hard = chunkMessagingText("x".repeat(90), 40);+ expect(hard.map((c) => c.length)).toEqual([40, 40, 10]);+ expect(hard.join("")).toBe("x".repeat(90));+ });+});++describe("messaging binding routes and bridge", () => {+ let t: TestApp;+ let api: ReturnType<typeof apiClient>;+ let fake: FakeSdk;+ let projectId: string;+ let runs: TextPayload[][];++ /** Save credentials, then flip the toggle on — the two-step flow the flow tests need. */+ const bindEnabled = async (sid: string, body: Record<string, unknown> = PUT_BODY) => {+ expect((await api.put(BASE(sid), body)).status).toBe(200);+ expect((await api.post(`${BASE(sid)}/state`, { enabled: true })).status).toBe(200);+ };++ beforeEach(async () => {+ fake = new FakeSdk();+ t = await createTestApp({ feishuSdk: fake });+ const { cookie } = await provisionUser(t.app, "birder");+ api = apiClient(t.app, cookie);+ projectId = "birder-default_project";+ runs = [];+ const row = sessionRowOf(SID, projectId);+ t.deps.sessionsRepo.insert(row);+ t.deps.manager.adopt(row, echoFakeSession(SID, runs));+ });+ afterEach(async () => {+ await t.cleanup();+ });++ it("GET reports unbound + disconnected before any PUT", async () => {+ const res = await api.get(BASE(SID));+ expect(res.status).toBe(200);+ expect((await res.json()) as FeishuBindingResponse).toEqual({+ binding: null,+ status: { state: "disconnected" },+ });+ });++ it("PUT saves credentials only (masked, disabled, no connection); blank secret keeps the stored one", async () => {+ const res = await api.put(BASE(SID), PUT_BODY);+ expect(res.status).toBe(200);+ const body = (await res.json()) as FeishuBindingResponse;+ expect(body.binding?.channel).toBe("feishu");+ expect(body.binding?.appId).toBe(PUT_BODY.appId);+ // Site-wide mask rule: first4…last4, never the plaintext.+ expect(body.binding?.appSecretMasked).toBe("secr…3456");+ expect(JSON.stringify(body)).not.toContain(PUT_BODY.appSecret);+ expect(body.binding?.lastChatKnown).toBe(false);+ // Saving is not connecting: the binding starts disabled and nothing was opened.+ expect(body.binding?.enabled).toBe(false);+ expect(body.status.state).toBe("disconnected");+ expect(fake.connections).toHaveLength(0);+ // The stored row carries the channel discriminator and the account identity.+ const stored = t.deps.messagingRepo.find(SID, "feishu")!;+ expect(stored.channel).toBe("feishu");+ expect(stored.accountId).toBe(PUT_BODY.appId);++ // Re-save with a blank secret: the stored one stays; still disabled, still dark.+ const resave = await api.put(BASE(SID), { appId: PUT_BODY.appId, appSecret: "" });+ expect(resave.status).toBe(200);+ expect(t.deps.messagingRepo.find(SID, "feishu")?.config.appSecret).toBe(PUT_BODY.appSecret);+ expect(fake.connections).toHaveLength(0);++ // First-time bind without a secret is refused.+ t.deps.messagingRepo.delete(SID, "feishu");+ const bare = await api.put(BASE(SID), { appId: "cli_other" });+ expect(bare.status).toBe(400);+ expect(((await bare.json()) as { error: { code: string } }).error.code).toBe(+ "feishu_secret_required",+ );+ });++ it("the clear flag drops the stored secret (disable first), and enabling without one is refused", async () => {+ await api.put(BASE(SID), PUT_BODY);+ await api.post(`${BASE(SID)}/state`, { enabled: true });+ // Clearing while enabled is refused: a live connection must never outrun its stored credential.+ const blocked = await api.put(BASE(SID), { appId: PUT_BODY.appId, clearAppSecret: true });+ expect(blocked.status).toBe(409);+ expect(((await blocked.json()) as { error: { code: string } }).error.code).toBe(+ "messaging_disable_before_clear",+ );+ await api.post(`${BASE(SID)}/state`, { enabled: false });+ const cleared = await api.put(BASE(SID), { appId: PUT_BODY.appId, clearAppSecret: true });+ expect(cleared.status).toBe(200);+ const body = (await cleared.json()) as FeishuBindingResponse;+ // No stored secret -> no mask; the row and its non-secret fields stay.+ expect(body.binding?.appSecretMasked).toBeUndefined();+ expect(body.binding?.appId).toBe(PUT_BODY.appId);+ expect(t.deps.messagingRepo.find(SID, "feishu")?.config.appSecret).toBe("");+ // A typed secret wins over a stale clear flag (the models idiom).+ const typed = await api.put(BASE(SID), {+ appId: PUT_BODY.appId,+ appSecret: "fresh-secret-123456",+ clearAppSecret: true,+ });+ expect(((await typed.json()) as FeishuBindingResponse).binding?.appSecretMasked).toBe(+ "fres…3456",+ );+ // Clear again, then try to enable: the state toggle refuses a credential-less config.+ await api.put(BASE(SID), { appId: PUT_BODY.appId, clearAppSecret: true });+ const on = await api.post(`${BASE(SID)}/state`, { enabled: true });+ expect(on.status).toBe(400);+ expect(((await on.json()) as { error: { code: string } }).error.code).toBe(+ "feishu_secret_required",+ );+ });++ it("POST /state owns the connection: enable connects with stored credentials, disable terminates", async () => {+ // Unbound: nothing to toggle.+ expect((await api.post(`${BASE(SID)}/state`, { enabled: true })).status).toBe(404);+ await api.put(BASE(SID), PUT_BODY);++ const on = await api.post(`${BASE(SID)}/state`, { enabled: true });+ expect(on.status).toBe(200);+ const onBody = (await on.json()) as FeishuBindingResponse;+ expect(onBody.binding?.enabled).toBe(true);+ expect(onBody.status.state).toBe("connected");+ expect(fake.connections).toHaveLength(1);+ // Connected with the STORED credentials — the toggle carries none of its own.+ expect(fake.connections[0]!.creds.appId).toBe(PUT_BODY.appId);+ expect(fake.connections[0]!.creds.appSecret).toBe(PUT_BODY.appSecret);++ const off = await api.post(`${BASE(SID)}/state`, { enabled: false });+ const offBody = (await off.json()) as FeishuBindingResponse;+ expect(offBody.binding?.enabled).toBe(false);+ expect(offBody.status.state).toBe("disconnected");+ expect(fake.connections[0]!.closed).toBe(true);+ expect((await api.post(`${BASE(SID)}/state`, { enabled: "yes" })).status).toBe(400);+ });++ it("saving new credentials while enabled restarts the connector with them (never-diverge rule)", async () => {+ await bindEnabled(SID);+ expect(fake.connections).toHaveLength(1);+ const res = await api.put(BASE(SID), { ...PUT_BODY, appSecret: "rotated-secret-9999" });+ expect(res.status).toBe(200);+ // The old connection is torn down and a new one runs on the just-saved secret.+ expect(fake.connections).toHaveLength(2);+ expect(fake.connections[0]!.closed).toBe(true);+ expect(fake.connections[1]!.creds.appSecret).toBe("rotated-secret-9999");+ 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",+ );+ 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 () => {+ await api.put(BASE(SID), PUT_BODY);+ const outsider = apiClient(t.app, (await provisionUser(t.app, "outsider")).cookie);+ expect((await outsider.get(BASE(SID))).status).toBe(404);++ const mate = await provisionUser(t.app, "mate");+ await api.post(`/api/projects/${projectId}/members`, { userId: "mate" });+ const member = apiClient(t.app, mate.cookie);+ expect((await member.get(BASE(SID))).status).toBe(200);+ expect((await member.put(BASE(SID), PUT_BODY)).status).toBe(403);+ expect((await member.post(`${BASE(SID)}/state`, { enabled: true })).status).toBe(403);+ expect((await member.delete(BASE(SID))).status).toBe(403);+ });++ it("POST /test probes draft values falling back to stored ones, reporting ok/error", async () => {+ // Draft-only test (nothing stored yet).+ const draft = await api.post(`${BASE(SID)}/test`, {+ appId: "cli_draft",+ appSecret: "draft-secret",+ });+ expect(draft.status).toBe(200);+ expect(((await draft.json()) as FeishuTestResponse).ok).toBe(true);+ expect(fake.clients.at(-1)?.creds.appId).toBe("cli_draft");++ // Stored fallback: an empty body tests the saved binding — enabling is not required.+ await api.put(BASE(SID), PUT_BODY);+ const stored = await api.post(`${BASE(SID)}/test`, {});+ expect(((await stored.json()) as FeishuTestResponse).ok).toBe(true);+ expect(fake.clients.at(-1)?.creds.appId).toBe(PUT_BODY.appId);+ expect(fake.clients.at(-1)?.creds.appSecret).toBe(PUT_BODY.appSecret);++ // A rejected credential is ok:false with the reason, not an HTTP error.+ fake.failCheck = "app not found";+ const bad = await api.post(`${BASE(SID)}/test`, {});+ expect(bad.status).toBe(200);+ expect((await bad.json()) as FeishuTestResponse).toEqual({+ ok: false,+ error: "app not found",+ });++ // No stored binding and no draft appId: a plain 400.+ t.deps.messagingRepo.delete(SID, "feishu");+ expect((await api.post(`${BASE(SID)}/test`, {})).status).toBe(400);+ });++ it("POST /test-message: 404 unbound, 409 before a chat is known, sends after one", async () => {+ expect((await api.post(`${BASE(SID)}/test-message`, {})).status).toBe(404);+ await bindEnabled(SID);+ const early = await api.post(`${BASE(SID)}/test-message`, {});+ expect(early.status).toBe(409);+ expect(((await early.json()) as { error: { code: string } }).error.code).toBe("feishu_no_chat");++ await fake.lastConnection().fire({+ chatId: "oc_chat_1",+ chatType: "p2p",+ messageId: "om_1",+ messageType: "text",+ content: JSON.stringify({ text: "hello" }),+ });+ const res = await api.post(`${BASE(SID)}/test-message`, {});+ expect(res.status).toBe(200);+ expect(fake.allSends()).toContainEqual({+ kind: "send",+ target: "oc_chat_1",+ text: MESSAGING_TEST_MESSAGE,+ });+ });++ it("inbound text starts an ordinary user task (no marker, no sender) and the reply mirrors back (direct chat)", async () => {+ await bindEnabled(SID);+ await fake.lastConnection().fire({+ chatId: "oc_chat_1",+ chatType: "p2p",+ messageId: "om_1",+ messageType: "text",+ content: JSON.stringify({ text: "how is the build?" }),+ });+ await waitFor(() => runs.length === 1);+ // Exactly as if typed into the web composer: the text verbatim, no marker block, and+ // the default human sender (no `sender` field at all).+ const input = runs[0]![0]!;+ expect(input.text).toBe("how is the build?");+ expect(input.role).toBe("user");+ expect("sender" in input).toBe(false);+ // The inbound chat became the reply target.+ const row = t.deps.messagingRepo.find(SID, "feishu")!;+ expect(row.lastChatId).toBe("oc_chat_1");+ expect(row.lastChatIsDirect).toBe(true);+ // Task end mirrors the assistant text to that chat.+ await waitFor(() => fake.allSends().some((s) => s.kind === "send" && s.target === "oc_chat_1"));+ expect(fake.allSends()).toContainEqual({+ kind: "send",+ target: "oc_chat_1",+ text: "Reply text",+ });+ // The queue path (busy sessions) is exercised end to end by followup.test.ts; here the+ // idle path must have started immediately.+ expect(t.deps.manager.pendingFollowUpCount(SID)).toBe(0);+ });++ it("group chats reply to the inbound message; web-initiated turns mirror too", async () => {+ await bindEnabled(SID);+ await fake.lastConnection().fire({+ chatId: "oc_group_9",+ chatType: "group",+ messageId: "om_group_1",+ messageType: "text",+ content: JSON.stringify({ text: "ping" }),+ });+ await waitFor(() => fake.allSends().length > 0);+ expect(fake.allSends()).toContainEqual({+ kind: "reply",+ target: "om_group_1",+ text: "Reply text",+ });++ // A turn started from the web mirrors to the same chat once it completes.+ const sent = fake.allSends().length;+ const res = await api.post(`/api/sessions/${SID}/tasks`, {+ input: [{ type: "text", text: "from the web" }],+ });+ expect(res.status).toBe(202);+ await waitFor(() => fake.allSends().length > sent);+ expect(fake.allSends().at(-1)).toEqual({+ kind: "reply",+ target: "om_group_1",+ text: "Reply text",+ });+ });++ it("relays every completed assistant message on its own, as it completes, never joined", async () => {+ const row2 = sessionRowOf(SID2, projectId);+ t.deps.sessionsRepo.insert(row2);+ let release = () => {};+ const gate = new Promise<void>((r) => {+ release = r;+ });+ t.deps.manager.adopt(+ row2,+ multiMessageFakeSession(SID2, ["working on it", "still going", "here is the answer"], gate),+ );+ await bindEnabled(SID2, { ...PUT_BODY, appId: "cli_streamer" });+ await fake.lastConnection().fire({+ chatId: "oc_chat_5",+ chatType: "p2p",+ messageId: "om_5",+ messageType: "text",+ content: JSON.stringify({ text: "go" }),+ });+ // The first two are in the chat while the run is still running — the whole point:+ // the chat follows the run instead of receiving it as one block at the end.+ await waitFor(() => fake.allSends().length === 2);+ expect(t.deps.manager.statusOf(SID2)).toBe("running");+ expect(fake.allSends().map((s) => s.text)).toEqual(["working on it", "still going"]);+ release();+ await waitFor(() => fake.allSends().length === 3);+ // Order preserved, and no message carries another one's text: nothing was joined.+ expect(fake.allSends().map((s) => s.text)).toEqual([+ "working on it",+ "still going",+ "here is the answer",+ ]);+ expect(fake.allSends().every((s) => !s.text.includes("\n\n"))).toBe(true);+ expect(fake.allSends().every((s) => s.kind === "send" && s.target === "oc_chat_5")).toBe(true);+ });++ it("in a group only the run's first message threads onto the inbound one", async () => {+ const row2 = sessionRowOf(SID2, projectId);+ t.deps.sessionsRepo.insert(row2);+ t.deps.manager.adopt(row2, multiMessageFakeSession(SID2, ["first", "second", "third"]));+ await bindEnabled(SID2, { ...PUT_BODY, appId: "cli_grouped" });+ await fake.lastConnection().fire({+ chatId: "oc_group_7",+ chatType: "group",+ messageId: "om_group_7",+ messageType: "text",+ content: JSON.stringify({ text: "ping" }),+ });+ await waitFor(() => fake.allSends().length === 3);+ // One reply-to anchors the exchange; the rest are plain sends into the same chat, so+ // the group does not get a stack of quote headers.+ expect(fake.allSends()).toEqual([+ { kind: "reply", target: "om_group_7", text: "first" },+ { kind: "send", target: "oc_group_7", text: "second" },+ { kind: "send", target: "oc_group_7", text: "third" },+ ]);+ });++ it("the streamed compaction summary is not a reply and never reaches the chat", async () => {+ const row2 = sessionRowOf(SID2, projectId);+ t.deps.sessionsRepo.insert(row2);+ t.deps.manager.adopt(row2, compactingFakeSession(SID2));+ await bindEnabled(SID2, { ...PUT_BODY, appId: "cli_compactor" });+ await fake.lastConnection().fire({+ chatId: "oc_chat_6",+ chatType: "p2p",+ messageId: "om_6",+ messageType: "text",+ content: JSON.stringify({ text: "summarize" }),+ });+ await waitFor(() => t.deps.manager.statusOf(SID2) === "idle");+ expect(fake.allSends().map((s) => s.text)).toEqual(["the actual answer"]);+ });++ it("non-text messages get the bilingual text-only reply and start no task", async () => {+ await bindEnabled(SID);+ await fake.lastConnection().fire({+ chatId: "oc_chat_1",+ chatType: "p2p",+ messageId: "om_2",+ messageType: "image",+ content: JSON.stringify({ image_key: "img_1" }),+ });+ await waitFor(() => fake.allSends().length > 0);+ expect(fake.allSends()).toContainEqual({+ kind: "send",+ target: "oc_chat_1",+ text: MESSAGING_TEXT_ONLY_NOTICE,+ });+ expect(runs).toHaveLength(0);+ // Even a rejected type teaches the bridge where the user is.+ expect(t.deps.messagingRepo.find(SID, "feishu")?.lastChatId).toBe("oc_chat_1");+ });++ it("an approval_request sends the waiting-for-approval notice", async () => {+ const row2 = sessionRowOf(SID2, projectId);+ row2.approvalMode = "always-ask";+ t.deps.sessionsRepo.insert(row2);+ t.deps.manager.adopt(row2, parkingFakeSession(SID2));+ await bindEnabled(SID2, { ...PUT_BODY, appId: "cli_approver" });+ await fake.lastConnection().fire({+ chatId: "oc_chat_2",+ chatType: "p2p",+ messageId: "om_3",+ messageType: "text",+ content: JSON.stringify({ text: "do something risky" }),+ });+ await waitFor(() =>+ fake.allSends().some((s) => s.text === MESSAGING_APPROVAL_NOTICE && s.target === "oc_chat_2"),+ );+ t.deps.manager.decideApproval(SID2, "tc-feishu", "allow");+ await waitFor(() => t.deps.manager.statusOf(SID2) === "idle");+ });++ it("DELETE unbinds + disconnects, and deleting the Session cascades the binding away", async () => {+ await bindEnabled(SID);+ expect((await api.delete(BASE(SID))).status).toBe(204);+ expect(t.deps.messagingRepo.find(SID, "feishu")).toBeNull();+ expect(fake.connections[0]!.closed).toBe(true);+ expect(t.deps.messaging.statusOf(SID, "feishu").state).toBe("disconnected");++ // Rebind + enable, then delete the Session itself: the binding goes with it.+ await bindEnabled(SID);+ expect((await api.delete(`/api/sessions/${SID}`)).status).toBe(204);+ expect(t.deps.messagingRepo.find(SID, "feishu")).toBeNull();+ expect(fake.connections[1]!.closed).toBe(true);+ });++ it("the session list marks rows with the ENABLED channel only", async () => {+ // Saved but disabled: no indicator — the row marks live connections, not stored configs.+ await api.put(BASE(SID), PUT_BODY);+ const saved = await api.get(`/api/projects/${projectId}/agents/default_agent/sessions`);+ const savedBody = (await saved.json()) as {+ sessions: Array<{ sessionId: string; messagingChannel?: string }>;+ };+ expect("messagingChannel" in savedBody.sessions.find((s) => s.sessionId === SID)!).toBe(false);++ await api.post(`${BASE(SID)}/state`, { enabled: true });+ const res = await api.get(`/api/projects/${projectId}/agents/default_agent/sessions`);+ const body = (await res.json()) as {+ sessions: Array<{ sessionId: string; messagingChannel?: string }>;+ };+ expect(body.sessions.find((s) => s.sessionId === SID)?.messagingChannel).toBe("feishu");+ });++ it("start() connects only enabled bindings and reconciles away rows whose Session is gone", async () => {+ t.deps.messagingRepo.upsert({+ sessionId: SID,+ channel: "feishu",+ accountId: "cli_boot",+ config: { appId: "cli_boot", appSecret: "boot-secret", baseDomain: "https://open.feishu.cn" },+ });+ t.deps.messagingRepo.setEnabled(SID, "feishu", true);+ // A saved-but-disabled binding keeps its credentials and stays dark across restarts.+ t.deps.sessionsRepo.insert(sessionRowOf(SID2, projectId));+ t.deps.messagingRepo.upsert({+ sessionId: SID2,+ channel: "feishu",+ accountId: "cli_dark",+ config: { appId: "cli_dark", appSecret: "dark-secret", baseDomain: "https://open.feishu.cn" },+ });+ t.deps.messagingRepo.upsert({+ sessionId: "session-2026-08-25-10-00-02-dead0001",+ channel: "feishu",+ accountId: "cli_orphan",+ config: {+ appId: "cli_orphan",+ appSecret: "orphan-secret",+ baseDomain: "https://open.feishu.cn",+ },+ });+ await t.deps.messaging.start();+ expect(fake.connections.map((c) => c.creds.appId)).toEqual(["cli_boot"]);+ expect(t.deps.messagingRepo.find("session-2026-08-25-10-00-02-dead0001", "feishu")).toBeNull();+ expect(t.deps.messagingRepo.find(SID2, "feishu")?.enabled).toBe(false);+ t.deps.messaging.stop();+ expect(fake.connections[0]!.closed).toBe(true);+ });+});diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 1da2a8c1..e3269e91 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -36,6 +36,10 @@ import type {DirListResponse,EndpointModelListRequest,EndpointModelListResponse,+ FeishuBindingPutRequest,+ FeishuBindingResponse,+ FeishuTestRequest,+ FeishuTestResponse,FilesStatRequest,FilesStatResponse,GoalResponse,@@ -51,6 +55,9 @@ import type {MemoryOverviewResponse,MemoryScopeExport,MessagesResponse,+ MessagingBindingsResponse,+ MessagingChannel,+ MessagingTestMessageResponse,ModelOAuthCodeResponse,ModelOAuthStartRequest,ModelOAuthStartResponse,@@ -95,6 +102,10 @@ import type {SubagentMessageResponse,TaskCreateRequest,TaskCreateResponse,+ TelegramBindingPutRequest,+ TelegramBindingResponse,+ TelegramTestRequest,+ TelegramTestResponse,TraceAnalysisResponse,TraceEventsResponse,TraceImportRequest,@@ -496,6 +507,58 @@ export const patchSession = (sessionId: string, body: SessionPatchRequest) =>export const deleteSession = (sessionId: string) =>apiFetch<void>(`/api/sessions/${encodeURIComponent(sessionId)}`, { method: "DELETE" });+// Messaging bindings ----------------------------------------------------------++/** The channel-agnostic read: every saved channel config + status (the channel-aware editor's load + poll). */+export const getMessagingBinding = (sessionId: string) =>+ apiFetch<MessagingBindingsResponse>(`/api/sessions/${encodeURIComponent(sessionId)}/messaging`);++/** Saves Feishu credentials only — the connection toggle is setMessagingBindingState (an enabled binding restarts on save so config and connection never diverge). */+export const putFeishuBinding = (sessionId: string, body: FeishuBindingPutRequest) =>+ apiFetch<FeishuBindingResponse>(+ `/api/sessions/${encodeURIComponent(sessionId)}/messaging/feishu`,+ { method: "PUT", body },+ );++/** Saves the Telegram token only — the same save/enable split as the Feishu PUT. */+export const putTelegramBinding = (sessionId: string, body: TelegramBindingPutRequest) =>+ apiFetch<TelegramBindingResponse>(+ `/api/sessions/${encodeURIComponent(sessionId)}/messaging/telegram`,+ { method: "PUT", body },+ );++/** The connection toggle: enable connects with the STORED credentials (409 `another_channel_enabled` while the other channel is enabled), disable terminates. */+export const setMessagingBindingState = (+ sessionId: string,+ channel: MessagingChannel,+ enabled: boolean,+) =>+ apiFetch<FeishuBindingResponse | TelegramBindingResponse>(+ `/api/sessions/${encodeURIComponent(sessionId)}/messaging/${channel}/state`,+ { method: "POST", body: { enabled } },+ );++/** Feishu credential probe with the form's draft values; omitted fields fall back to the stored binding. */+export const testFeishuBinding = (sessionId: string, body: FeishuTestRequest) =>+ apiFetch<FeishuTestResponse>(+ `/api/sessions/${encodeURIComponent(sessionId)}/messaging/feishu/test`,+ { method: "POST", body },+ );++/** Telegram credential probe (`getMe`); success additionally names the bot's @username. */+export const testTelegramBinding = (sessionId: string, body: TelegramTestRequest) =>+ apiFetch<TelegramTestResponse>(+ `/api/sessions/${encodeURIComponent(sessionId)}/messaging/telegram/test`,+ { method: "POST", body },+ );++/** Short fixed text to the binding's last known chat (409 `feishu_no_chat` / `telegram_no_chat` before one exists). */+export const sendMessagingTestMessage = (sessionId: string, channel: MessagingChannel) =>+ apiFetch<MessagingTestMessageResponse>(+ `/api/sessions/${encodeURIComponent(sessionId)}/messaging/${channel}/test-message`,+ { method: "POST", body: {} },+ );+/** Windowed history request: the newest N units (tail), or the N units before a cursor. */export type MessagesPageQuery ={ kind: "tail"; limit: number } | { kind: "before"; cursor: string; limit: number };diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex 1e49af20..ae0f6657 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -120,7 +120,7 @@ import {} from "../ui/session-row-menu";import type { SessionRowAction } from "../ui/session-row-menu";import { AgentAvatar } from "../ui/agent-avatar";-import { CheckIcon, ChevronDown, GEAR_ICON, NAV_ICONS } from "../ui/icons";+import { CheckIcon, ChevronDown, GEAR_ICON, MESSAGING_RELAY_ICON, NAV_ICONS } from "../ui/icons";import {FOLDER_ICON,FOLDER_OPEN_ICON,@@ -147,6 +147,7 @@ import { Input, noAutofill } from "../ui/input";import { SkeletonList } from "../ui/skeleton";import { UpdateDot } from "../ui/update-dot";import { DRAFT_SESSION_ID } from "../../features/chat/chat-page";+import { MessagingBindingModal } from "../../features/messaging/messaging-binding-modal";import { WorkspaceSelect } from "../../features/chat/workspace-select";import { clearDraft, sessionDraftKey } from "../../features/chat/draft-cache";import {@@ -487,6 +488,8 @@ export function Sidebar({const [renameText, setRenameText] = useState("");const [renameBusy, setRenameBusy] = useState(false);const [renameError, setRenameError] = useState<string | null>(null);+ /** Session whose messaging-binding dialog is open (null = none). */+ const [messagingSession, setMessagingSession] = useState<SessionInfo | null>(null);const setGroupMode = (mode: GroupMode) => {storeGroupMode(mode);@@ -1258,6 +1261,7 @@ export function Sidebar({setRenameText(x.title ?? "");setRenamingSession(x);}}+ onMessaging={(x) => setMessagingSession(x)}onDelete={(x) => setDeletingSession(x)}onToggleArchive={(x) => void toggleArchive(x)}/>@@ -2333,6 +2337,23 @@ export function Sidebar({/></Modal>+ {/* Messaging binding dialog (row menu "Messaging binding…"): the row indicator+ updates in place from the dialog's own save/unbind outcome. */}+ {messagingSession && (+ <MessagingBindingModal+ sessionId={messagingSession.sessionId}+ onClose={() => setMessagingSession(null)}+ onChanged={(sessionId, channel) => {+ const current = sessions.find((x) => x.sessionId === sessionId);+ if (!current) return;+ const updated = { ...current };+ if (channel !== null) updated.messagingChannel = channel;+ else delete updated.messagingChannel;+ replace(updated);+ }}+ />+ )}+{/* Rename workspace (alias edit, same Modal + Input idiom as rename chat): the aliasreplaces the directory basename as the group label; leaving it blank reverts tothe basename — so an empty save is valid here, unlike the chat rename. */}@@ -2573,6 +2594,7 @@ function SessionRow({onOpen,onTogglePin,onRename,+ onMessaging,onDelete,onToggleArchive,}: {@@ -2600,6 +2622,7 @@ function SessionRow({onOpen: (s: SessionInfo) => void;onTogglePin: (s: SessionInfo) => void;onRename: (s: SessionInfo) => void;+ onMessaging: (s: SessionInfo) => void;onDelete: (s: SessionInfo) => void;onToggleArchive: (s: SessionInfo) => void;}) {@@ -2610,6 +2633,7 @@ function SessionRow({const handler: Record<SessionRowAction, (x: SessionInfo) => void> = {pin: onTogglePin,rename: onRename,+ messaging: onMessaging,archive: onToggleArchive,delete: onDelete,};@@ -2705,6 +2729,18 @@ function SessionRow({<span className="sr-only">{S.chat.pinnedSession}</span></span>)}+ {/* Enabled-messaging indicator: one glyph for every channel, the channel named in+ the tooltip and sr text. Same dim treatment as the pin (saved-but-disabled+ configs stay off the row; the binding dialog lives in the row menu). */}+ {s.messagingChannel !== undefined && (+ <span+ title={S.messaging.enabledIndicator[s.messagingChannel]}+ className="shrink-0 text-gray-400 dark:text-gray-500"+ >+ <Icon d={MESSAGING_RELAY_ICON} size={12} />+ <span className="sr-only">{S.messaging.enabledIndicator[s.messagingChannel]}</span>+ </span>+ )}{/* No per-row source tag: subagent / scheduled Sessions live in their own labelled, collapsed folders, so a badge on the title would just repeat the folder. */}<StatusGlyph activity={activity} />{s.pendingApprovalCount > 0 && (@@ -2727,7 +2763,12 @@ function SessionRow({{/* No hover pill on these (a fill as wide as the date read ugly); feedback isthe glyph color deepening — red for delete. */}<div className="peer absolute right-0 top-1/2 flex -translate-y-1/2 items-center">- <SessionRowHoverActions actions={HOVER_ROW_ACTIONS} state={rowState} onRun={run} />+ <SessionRowHoverActions+ actions={HOVER_ROW_ACTIONS}+ state={rowState}+ onRun={run}+ onMore={ctx.openAt}+ /></div>{lastActive !== "" && (<spandiff --git a/packages/web/src/components/ui/context-menu.tsx b/packages/web/src/components/ui/context-menu.tsxindex 2b2b6a27..7a7dd344 100644--- a/packages/web/src/components/ui/context-menu.tsx+++ b/packages/web/src/components/ui/context-menu.tsx@@ -64,6 +64,12 @@ export interface RowContextMenu {* row's click handler calls it first so opening the menu does not also open the row.*/consumeLongPressClick: () => boolean;+ /**+ * Programmatic open at a given viewport box (the row's ellipsis "more" button anchors+ * the panel at itself). Same direct setAnchor path as the keyboard chord — no hold+ * lifecycle is involved, and the Dropdown's dismiss stack takes over once open.+ */+ openAt: (rect: AnchorRect) => void;/** Close from inside the panel (an item ran). */close: () => void;}@@ -188,6 +194,7 @@ export function useRowContextMenu(): RowContextMenu {anchor,returnFocus: () => row.current?.querySelector<HTMLElement>("button") ?? null,consumeLongPressClick: () => dispatch({ kind: "click" }).swallow,+ openAt: setAnchor,close,};}diff --git a/packages/web/src/components/ui/help-fold.tsx b/packages/web/src/components/ui/help-fold.tsxindex 78216901..42c9cbde 100644--- a/packages/web/src/components/ui/help-fold.tsx+++ b/packages/web/src/components/ui/help-fold.tsx@@ -17,6 +17,10 @@** The chevron is the app's one collapse indicator, the same glyph every other collapsible* rotates; a help fold that announced itself differently would be a second pattern for no reason.+ *+ * A lone row reads "More info" and borrows its subject from `label`. Several stacked into an FAQ+ * take `title` instead and say what each one holds, because a column of identical "More info" rows+ * tells a reader nothing about which one answers their question.*/import { useId, useState } from "react";import type { ReactNode } from "react";@@ -27,6 +31,7 @@ import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";export function HelpFold({children,label,+ title,className = "",}: {/** The explanation. Revealed only on request — a description that shows up uninvited is what this replaces. */@@ -37,6 +42,13 @@ export function HelpFold({* user tabbing past knows what the fold is about without the panel repeating the tab bar.*/label?: string;+ /**+ * A fold that names its own subject ("Set up the bot"), replacing the generic row text — for a+ * stack of folds, where a column of identical "More info" rows would say nothing about which+ * one to open. A title IS the accessible name, so it takes `label`'s place rather than joining+ * it: two names for one trigger is what breaks "label in name".+ */+ title?: string;className?: string;}) {const [open, setOpen] = useState(false);@@ -49,12 +61,14 @@ export function HelpFold({aria-controls={panelId}// The visible text is a prefix of the accessible name, so "label in name" holds and a// voice-control user can still say what they see.- {...(label !== undefined ? { "aria-label": S.common.moreInfoAbout(label) } : {})}+ {...(title === undefined && label !== undefined+ ? { "aria-label": S.common.moreInfoAbout(label) }+ : {})}onClick={() => setOpen((v) => !v)}className={`flex items-center ${ICON_GAP.tight} rounded text-xs text-gray-500 transition-colors duration-150 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200`}><Chevron open={open} size={ICON_SIZE.chevronDense} />- {S.common.moreInfo}+ {title ?? S.common.moreInfo}</button>{/* pl-4.5 = the chevron's 12px plus the row's gap, so the body lines up under the label. */}<divdiff --git a/packages/web/src/components/ui/icons.tsx b/packages/web/src/components/ui/icons.tsxindex dd17e28e..b3a65530 100644--- a/packages/web/src/components/ui/icons.tsx+++ b/packages/web/src/components/ui/icons.tsx@@ -164,6 +164,16 @@ export function CloseButton({/** Info circle: the app's 9-radius status circle with a bar and a dot inside it. */export const INFO_ICON = "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM12 11v5m0-8h.01";+/** Chat bubble: the messaging binding's channel-neutral mark (dock panel tab, row-menu action). */+export const MESSAGING_ICON = "M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z";++/**+ * Paper plane: the session-row mark for a Session that is relaying through a messaging+ * channel. One shape for every channel — shape alone is not the carrier, so the row+ * pairs it with the channel's name in a tooltip and in sr-only text.+ */+export const MESSAGING_RELAY_ICON = "M22 2 11 13M22 2l-7 20-4-9-9-4z";+/** Standard gear (lucide settings): full tooth outline + center circle, crisp and undistorted at 16px. */export const GEAR_ICON ="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2zM15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0z";diff --git a/packages/web/src/components/ui/session-row-menu.tsx b/packages/web/src/components/ui/session-row-menu.tsxindex b37a32b7..595e1995 100644--- a/packages/web/src/components/ui/session-row-menu.tsx+++ b/packages/web/src/components/ui/session-row-menu.tsx@@ -4,18 +4,25 @@* The row carries a **pared-back hover affordance** and a **full context menu**, and this* module owns which actions belong to each so the two cannot drift:*- * - Hovering a row reveals archive and delete as direct icon buttons — the shape the row- * had in every released version up to v0.2.2, restored here after the 0.3 line had- * folded them into an ellipsis dropdown.- * - Right-clicking a row (or holding it on touch, or Shift+F10 on the keyboard) opens the- * whole set — pin, rename, archive, delete — as a labelled menu.+ * - Hovering a row reveals archive as a direct icon button plus an ellipsis "more"+ * button that opens the context menu anchored at itself. The menu grew configuration+ * actions (messaging binding) that right-click alone left undiscoverable, so the+ * pointer entry is the ellipsis; delete moved inside the menu with them (still+ * danger-styled there), keeping the hover surface to one safe direct action.+ * - Right-clicking a row (or holding it on touch, Shift+F10 on the keyboard, or clicking+ * the ellipsis) opens the whole set — pin, rename, messaging, archive, delete — as a+ * labelled menu.*- * Rename therefore keeps a home: `design/specs/06-PROTOTYPE.md` requires that every- * Session支持重命名、归档与删除, and paring the hover affordance down would otherwise have- * dropped rename off the row entirely.+ * Rename therefore keeps a home: every Session must stay renamable, archivable and+ * deletable, and paring the hover affordance down would otherwise have dropped rename+ * off the row entirely.*/+import type { MouseEvent as ReactMouseEvent } from "react";+import type { AnchorRect } from "../../lib/context-menu";import { S } from "../../lib/strings";+import { GlyphIcon } from "./glyph-icon";import { Icon } from "./group-list";+import { MESSAGING_ICON } from "./icons";/** Pushpin (lucide pin: head + body + stem), the group-header pin toggle / pinned indicator. */export const PIN_ICON =@@ -29,6 +36,14 @@ export const UNARCHIVE_ICON ="M3 8h18M5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8M4 8l1.5-3h13L20 8M12 17v-5m-2.5 2L12 11l2.5 3";export const TRASH_ICON ="M4 6h16M9 6V4.5A1.5 1.5 0 0 1 10.5 3h3A1.5 1.5 0 0 1 15 4.5V6M6 6v13a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V6M10 10.5v6M14 10.5v6";+/**+ * Three-dot ellipsis, drawn as FILLED circles: the hover "more" button. Hairline-stroke+ * dots vanish at row-glyph size, so this mark renders through GlyphIcon's `filled` mode —+ * the stroke rides on top of the fill, landing the dots at the visual weight of the+ * archive glyph beside it.+ */+export const ELLIPSIS_ICON =+ "M4.5 10a2 2 0 1 0 0 4 2 2 0 0 0 0-4zM12 10a2 2 0 1 0 0 4 2 2 0 0 0 0-4zM19.5 10a2 2 0 1 0 0 4 2 2 0 0 0 0-4z";/** Compact overflow-menu row (session row menu + workspace group menu): small text, leading thin-line glyph. */export const overflowMenuRowClass =@@ -46,7 +61,7 @@ export const overflowMenuGlyph = (d: string) => ();/** One thing a Session row can do to its Session. */-export type SessionRowAction = "pin" | "rename" | "archive" | "delete";+export type SessionRowAction = "pin" | "rename" | "messaging" | "archive" | "delete";/** Row state the labels and glyphs read (both of the toggles flip on it). */export interface SessionRowState {@@ -55,18 +70,22 @@ export interface SessionRowState {}/**- * The hover affordance's actions, restored to the released shape: archive and delete,- * nothing else. Everything else on the row is one right-click away.+ * The hover affordance's direct actions: archive alone. Everything else — delete+ * included — lives in the context menu, whose discoverable pointer entry is the+ * ellipsis button `SessionRowHoverActions` renders after these (see the module header).*/-export const HOVER_ROW_ACTIONS: readonly SessionRowAction[] = ["archive", "delete"];+export const HOVER_ROW_ACTIONS: readonly SessionRowAction[] = ["archive"];/*** The context menu's actions. Pin only reorders rows in the active list, so folder rows* (archived / subagent / scheduled) offer the rest without it — the same gate the- * ellipsis menu applied before this moved.+ * ellipsis menu applied before this moved. The messaging binding sits with the other+ * configuration actions, before the archive/delete pair.*/export function contextMenuActions(canPin: boolean): readonly SessionRowAction[] {- return canPin ? ["pin", "rename", "archive", "delete"] : ["rename", "archive", "delete"];+ return canPin+ ? ["pin", "rename", "messaging", "archive", "delete"]+ : ["rename", "messaging", "archive", "delete"];}export interface SessionRowMenuItem {@@ -91,6 +110,8 @@ export function sessionRowMenuItem(};case "rename":return { label: S.chat.renameSession, icon: PENCIL_ICON, danger: false };+ case "messaging":+ return { label: S.messaging.bindAction, icon: MESSAGING_ICON, danger: false };case "archive":return {label: state.archived ? S.chat.unarchiveSession : S.chat.archiveSession,@@ -139,15 +160,21 @@ export function SessionRowMenuRows({);}+/** The hover buttons' shared reveal classes (see SessionRowHoverActions on why pointer events are gated with opacity). */+const hoverButtonClass =+ "pointer-events-none flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 opacity-0 transition-all duration-150 focus:pointer-events-auto focus:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100";+/**- * Hover affordance: icon-only buttons that fade in over the row, the pre-0.3 treatment.- * Deliberately hover/focus-gated and therefore desktop-only — Tailwind scopes `hover:`- * behind `@media (hover: hover)`, so these never appear on a touch screen, where the same- * actions are reached by holding the row instead.+ * Hover affordance: icon-only buttons that fade in over the row — the direct actions+ * (archive), then an ellipsis that opens the row's context menu anchored at itself, so+ * every menu action is one visible click away rather than right-click-only. Deliberately+ * hover/focus-gated and therefore desktop-only — Tailwind scopes `hover:` behind+ * `@media (hover: hover)`, so these never appear on a touch screen, where the same menu+ * is reached by holding the row instead.** Which is why they are **pointer-events-gated on exactly the same conditions as their* opacity**, not just faded out: an invisible button still takes taps, so a bare- * `opacity-0` would leave a phantom delete target sitting over the right end of every row+ * `opacity-0` would leave a phantom tap target sitting over the right end of every row* for the one class of user who can never see it. Keyboard focus is unaffected by* `pointer-events`, so Tab still reaches them and revealing them re-arms the click.*/@@ -155,11 +182,18 @@ export function SessionRowHoverActions({actions,state,onRun,+ onMore,}: {actions: readonly SessionRowAction[];state: SessionRowState;onRun: (action: SessionRowAction) => void;+ /** Opens the row's context menu anchored at the ellipsis button's own box. */+ onMore: (anchor: AnchorRect) => void;}) {+ const openMore = (e: ReactMouseEvent<HTMLButtonElement>) => {+ const r = e.currentTarget.getBoundingClientRect();+ onMore({ top: r.top, bottom: r.bottom, left: r.left, right: r.right });+ };return (<>{actions.map((action) => {@@ -171,7 +205,7 @@ export function SessionRowHoverActions({title={item.label}aria-label={item.label}onClick={() => onRun(action)}- className={`pointer-events-none flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 opacity-0 transition-all duration-150 focus:pointer-events-auto focus:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100 ${+ className={`${hoverButtonClass} ${item.danger? "hover:text-red-600 dark:hover:text-red-400": "hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200"@@ -181,6 +215,16 @@ export function SessionRowHoverActions({</button>);})}+ <button+ type="button"+ title={S.chat.moreActions}+ aria-label={S.chat.moreActions}+ aria-haspopup="menu"+ onClick={openMore}+ className={`${hoverButtonClass} hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200`}+ >+ <GlyphIcon d={ELLIPSIS_ICON} size={14} filled />+ </button></>);}diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex a149d40a..be6c88cc 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -105,6 +105,7 @@ import { useMemoryListing } from "./use-memory-listing";import { deletedChangeKeys } from "./memory-nav";import { SubagentsView } from "./subagents-view";import { TracePanel } from "../traces/trace-panel";+import { MessagingPanel } from "../messaging/messaging-panel";import { DockPanel } from "../dock/dock-panel";import { useDockMount } from "../dock/use-dock-mount";import { panelLabel } from "../dock/panel-meta";@@ -1511,6 +1512,10 @@ export function ChatPage() {);case "trace":return <TracePanel key={selected.sessionId} session={selected} active={active} />;+ case "messaging":+ return (+ <MessagingPanel key={selected.sessionId} sessionId={selected.sessionId} active={active} />+ );}};diff --git a/packages/web/src/features/dock/dock-panel.tsx b/packages/web/src/features/dock/dock-panel.tsxindex b1f45501..adf2de90 100644--- a/packages/web/src/features/dock/dock-panel.tsx+++ b/packages/web/src/features/dock/dock-panel.tsx@@ -276,6 +276,7 @@ function DockPicker({{row("workspace")}{row("memory")}{row("trace")}+ {row("messaging")}</div></div>);diff --git a/packages/web/src/features/dock/dock-state.ts b/packages/web/src/features/dock/dock-state.tsindex 543ce40f..450a6837 100644--- a/packages/web/src/features/dock/dock-state.ts+++ b/packages/web/src/features/dock/dock-state.ts@@ -38,9 +38,15 @@ const MAX_SCOPES = 40;export type DockPosition = "right" | "bottom";/** The singleton panel kinds. Terminals are the one multi-instance tab kind. */-export type PanelKind = "agents" | "workspace" | "memory" | "trace";--export const PANEL_KINDS: readonly PanelKind[] = ["agents", "workspace", "memory", "trace"];+export type PanelKind = "agents" | "workspace" | "memory" | "trace" | "messaging";++export const PANEL_KINDS: readonly PanelKind[] = [+ "agents",+ "workspace",+ "memory",+ "trace",+ "messaging",+];export type DockTab ={ kind: "panel"; panel: PanelKind } | { kind: "terminal"; terminalId: string };diff --git a/packages/web/src/features/dock/panel-meta.tsx b/packages/web/src/features/dock/panel-meta.tsxindex 438a6464..1512c199 100644--- a/packages/web/src/features/dock/panel-meta.tsx+++ b/packages/web/src/features/dock/panel-meta.tsx@@ -7,7 +7,7 @@ import type { ReactNode } from "react";import { S } from "../../lib/strings";import { GlyphIcon } from "../../components/ui/glyph-icon";import { FOLDER_ICON } from "../../components/ui/group-list";-import { NAV_ICONS } from "../../components/ui/icons";+import { MESSAGING_ICON, NAV_ICONS } from "../../components/ui/icons";import { ICON_SIZE } from "../../lib/icon-scale";import type { PanelKind } from "./dock-state";@@ -48,6 +48,8 @@ export function panelLabel(kind: PanelKind): string {return S.chat.memoryViewTitle;case "trace":return S.nav.traces;+ case "messaging":+ return S.messaging.panelTitle;}}@@ -61,5 +63,7 @@ export function panelGlyph(kind: PanelKind, size: number = ICON_SIZE.iconButton)return <GlyphIcon d={MEMORY_ICON} size={size} />;case "trace":return <GlyphIcon d={NAV_ICONS.traces} size={size} />;+ case "messaging":+ return <GlyphIcon d={MESSAGING_ICON} size={size} />;}}diff --git a/packages/web/src/features/messaging/messaging-binding-editor.tsx b/packages/web/src/features/messaging/messaging-binding-editor.tsxnew file mode 100644index 00000000..dc4fdb1a--- /dev/null+++ b/packages/web/src/features/messaging/messaging-binding-editor.tsx@@ -0,0 +1,688 @@+/**+ * Shared messaging binding editor — ONE implementation behind both the session-row dialog+ * and the conversation's Messaging dock panel (the two hosts differ only in where they+ * place the Save action and the FAQ folds, so the state machine is a hook and the pieces+ * are body components; neither host forks the form).+ *+ * Channel model: a Session keeps at most one saved config PER channel — both may sit+ * saved side by side — and AT MOST ONE of them is enabled. The channel selector switches+ * freely between the two channel forms (each independently savable, each showing its own+ * configured/enabled state); enabling one channel while the other is enabled is gated+ * with a "turn that one off first" hint (the server refuses it too, 409).+ *+ * The form opens on the connection controls and the credential fields trail them: the two+ * channels' field lists differ in length, so controls placed under the fields would sit at+ * a different height in each channel and move on every switch. The explanation lives in+ * collapsed FAQ folds below the save area (`MessagingBindingHelp`), and the channel's+ * leading credential field — where the console values start being pasted — carries the+ * developer-console link at its label's top-right corner (the models-page "get API key"+ * idiom, which puts the link on the field, not in a row of its own). Secrets follow that+ * 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.+ *+ * The GET is re-polled while the host shows the editor (the hook's `poll` flag) so+ * connect/error flips show up live.+ */+import { useEffect, useRef, useState } from "react";+import type { ReactNode } from "react";+import type {+ MessagingBindingInfo,+ MessagingBindingsResponse,+ MessagingChannel,+ MessagingRuntimeStatus,+} from "@prismshadow/penguin-server/api";+import * as api from "../../api/endpoints";+import { S } from "../../lib/strings";+import { apiErrorText } from "../../lib/api-error";+import { toneInk, type Tone } from "../../lib/tone";+import { Button } from "../../components/ui/button";+import { FieldLabel } from "../../components/ui/field";+import { HelpFold } from "../../components/ui/help-fold";+import { Input } from "../../components/ui/input";+import { PasswordInput } from "../../components/ui/password-input";+import { Segmented } from "../../components/ui/segmented";+import { Switch } from "../../components/ui/switch";+import { toastError, toastSuccess } from "../../components/ui/toast";+import {+ bindingsToForm,+ emptyMessagingForm,+ formDirty,+ formTestable,+ formToPut,+ formToTest,+ type MessagingFormErrors,+ type MessagingFormState,+} from "./messaging-binding-form";++/** How often the visible editor refreshes the runtime status (connects settle within a poll or two). */+const STATUS_POLL_MS = 3000;++/** Per-channel external links: the walkthrough (setup FAQ fold) and the console where the credential is fetched (field corner). */+const CHANNEL_LINKS: Record<MessagingChannel, { tutorial: string; console: string }> = {+ feishu: {+ // Feishu's own echo-bot walkthrough: creating a self-built app and its long connection.+ tutorial: "https://open.feishu.cn/document/develop-an-echo-bot/introduction",+ console: "https://open.feishu.cn/app",+ },+ telegram: {+ tutorial: "https://core.telegram.org/bots/tutorial",+ console: "https://core.telegram.org/bots/api",+ },+};++const STATUS_TONE: Record<MessagingRuntimeStatus["state"], Tone> = {+ disconnected: "muted",+ connecting: "busy",+ connected: "success",+ error: "danger",+};++function errorText(code: MessagingFormErrors[keyof MessagingFormErrors]): string | undefined {+ if (code === undefined) return undefined;+ if (code === "required") return S.common.requiredField;+ if (code === "token_invalid") return S.telegram.invalidToken;+ return S.feishu.invalidDomain;+}++/** One channel's server-side facts, as the editor renders them (the form fields stay client-side). */+export interface MessagingChannelFacts {+ /** A secret is stored (a cleared config keeps its row but loses this). */+ secretConfigured: boolean;+ /** The stored secret's site-wide mask (display-only, never round-trips); null without one. */+ secretMasked: string | null;+ enabled: boolean;+ status: MessagingRuntimeStatus;+ lastChatKnown: boolean;+}++const EMPTY_FACTS: MessagingChannelFacts = {+ secretConfigured: false,+ secretMasked: null,+ enabled: false,+ status: { state: "disconnected" },+ lastChatKnown: false,+};++type ChannelFactsMap = Record<MessagingChannel, MessagingChannelFacts>;++function factsOf(+ binding: MessagingBindingInfo | null,+ status: MessagingRuntimeStatus,+): MessagingChannelFacts {+ if (binding === null) return { ...EMPTY_FACTS, status };+ const masked = binding.channel === "telegram" ? binding.botTokenMasked : binding.appSecretMasked;+ return {+ secretConfigured: masked !== undefined,+ secretMasked: masked ?? null,+ enabled: binding.enabled,+ status,+ lastChatKnown: binding.lastChatKnown,+ };+}++function factsFromList(res: MessagingBindingsResponse): ChannelFactsMap {+ const map: ChannelFactsMap = { feishu: EMPTY_FACTS, telegram: EMPTY_FACTS };+ for (const entry of res.bindings) {+ map[entry.binding.channel] = factsOf(entry.binding, entry.status);+ }+ return map;+}++/** Everything a host renders the editor from: state + handlers, one instance per session. */+export interface MessagingBindingEditorState {+ /** null until the stored bindings have been loaded (hosts show nothing until then). */+ form: MessagingFormState | null;+ patchForm(patch: Partial<MessagingFormState>): void;+ /** The selector's write: switches which channel's form shows (both stay editable). */+ selectChannel(channel: MessagingChannel): void;+ /** Per-channel server-side facts (secret / enabled / status / chat-known). */+ channels: ChannelFactsMap;+ fieldErrors: MessagingFormErrors;+ /** Unsaved edits on the SELECTED channel (a typed secret and a checked clear box count). */+ dirty: boolean;+ busy: boolean;+ toggling: boolean;+ testing: boolean;+ sendingTest: boolean;+ /** The credential probe needs a testable credential: the selected channel's draft or stored secret. */+ testable: boolean;+ /** The enable switch is gated (see toggleHint for the reason shown to the user). */+ toggleBlocked: boolean;+ /** Why the switch is gated, when a reason is worth showing (null otherwise). */+ toggleHint: string | null;+ save(): Promise<void>;+ toggleEnabled(next: boolean): Promise<void>;+ testConnection(): Promise<void>;+ sendTestMessage(): Promise<void>;+}++export function useMessagingBinding(+ sessionId: string,+ opts: {+ /** Keep the status poll running (hosts pass their visibility, e.g. the dock tab's `active`). */+ poll: boolean;+ /** Fired when the ENABLED channel changed (null = none); callers refresh their row/list indicator. */+ onChanged?: (sessionId: string, channel: MessagingChannel | null) => void;+ /** Fired when the initial load fails (the dialog closes itself; the panel shows its own retry). */+ onLoadFailed?: () => void;+ },+): MessagingBindingEditorState {+ const { poll, onChanged, onLoadFailed } = opts;+ const [form, setForm] = useState<MessagingFormState | null>(null);+ /** What the form last loaded/saved — the dirty check compares against it. */+ const [baseline, setBaseline] = useState<MessagingFormState | null>(null);+ const [channels, setChannels] = useState<ChannelFactsMap>({+ feishu: EMPTY_FACTS,+ telegram: EMPTY_FACTS,+ });+ const [fieldErrors, setFieldErrors] = useState<MessagingFormErrors>({});+ const [busy, setBusy] = useState(false);+ const [toggling, setToggling] = useState(false);+ const [testing, setTesting] = useState(false);+ const [sendingTest, setSendingTest] = useState(false);++ /** Which session the form was loaded for (the initial load runs once per session, not per poll flip). */+ const loadedFor = useRef<string | null>(null);++ // Initial load fills the form; the poll afterwards refreshes ONLY the per-channel+ // facts (stored / secret / enabled / status / chat-known), never the fields being+ // edited. A re-shown editor (the dock keeps hidden tabs mounted, `poll` flips back on)+ // only resumes that refresh: the form survives hide/show untouched.+ useEffect(() => {+ let cancelled = false;+ let initialDone = loadedFor.current === sessionId;+ const refresh = async (initial: boolean) => {+ try {+ const res = await api.getMessagingBinding(sessionId);+ if (cancelled) return;+ setChannels(factsFromList(res));+ if (initial) {+ const initialForm = bindingsToForm(res.bindings.map((b) => b.binding));+ setForm(initialForm);+ setBaseline(initialForm);+ initialDone = true;+ }+ } catch (e) {+ if (cancelled) return;+ if (initial) {+ initialDone = true; // reported; a retry is the host's call, not a silent loop+ toastError(apiErrorText(e));+ onLoadFailed?.();+ }+ }+ };+ if (loadedFor.current !== sessionId) {+ loadedFor.current = sessionId;+ // A swapped session must never show the previous one's fields while its load runs.+ setForm(null);+ setBaseline(null);+ void refresh(true);+ }+ const timer = poll ? setInterval(() => void refresh(false), STATUS_POLL_MS) : null;+ return () => {+ cancelled = true;+ if (timer !== null) clearInterval(timer);+ // An initial load cancelled mid-flight (poll flipped, host unmounted) must retry on+ // the next run instead of leaving the form permanently unloaded.+ if (!initialDone && loadedFor.current === sessionId) loadedFor.current = null;+ };+ // Only sessionId/poll may restart the effect: onLoadFailed's identity would+ // otherwise re-run it every render.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [sessionId, poll]);++ const patchForm = (patch: Partial<MessagingFormState>) => {+ setForm((prev) => (prev ? { ...prev, ...patch } : prev));+ setFieldErrors({});+ };++ const selectChannel = (channel: MessagingChannel) => {+ patchForm({ channel });+ };++ const selected: MessagingChannel = form?.channel ?? "feishu";+ const facts = channels[selected];+ const enabledChannel: MessagingChannel | null = channels.feishu.enabled+ ? "feishu"+ : channels.telegram.enabled+ ? "telegram"+ : null;+ const otherEnabled = enabledChannel !== null && enabledChannel !== selected;+ const dirty = form !== null && baseline !== null && formDirty(form, baseline);++ /** One channel's PUT/state response lands only in that channel's facts + form baseline. */+ const applyChannel = (+ channel: MessagingChannel,+ binding: MessagingBindingInfo | null,+ status: MessagingRuntimeStatus,+ ): void => {+ setChannels((prev) => ({ ...prev, [channel]: factsOf(binding, status) }));+ if (binding !== null) {+ const fresh = bindingsToForm([binding]);+ const sub = channel === "feishu" ? { feishu: fresh.feishu } : { telegram: fresh.telegram };+ setForm((prev) => (prev ? { ...prev, ...sub } : prev));+ setBaseline((prev) => (prev ? { ...prev, ...sub } : prev));+ }+ };++ const testConnection = async () => {+ if (!form) return;+ setTesting(true);+ try {+ const draft = formToTest(form);+ if (draft.channel === "telegram") {+ const res = await api.testTelegramBinding(sessionId, draft.body);+ if (res.ok) {+ const ms = res.latencyMs ?? 0;+ // The success line names the bot: the one detail a user can check against @BotFather.+ toastSuccess(+ res.botUsername !== undefined+ ? S.messaging.testOkAs(res.botUsername, ms)+ : S.messaging.testOk(ms),+ );+ } else toastError(S.messaging.testFail(res.error ?? S.common.unknownError));+ } else {+ const res = await api.testFeishuBinding(sessionId, draft.body);+ if (res.ok) toastSuccess(S.messaging.testOk(res.latencyMs ?? 0));+ else toastError(S.messaging.testFail(res.error ?? S.common.unknownError));+ }+ } catch (e) {+ toastError(S.messaging.testFail(apiErrorText(e)));+ } finally {+ setTesting(false);+ }+ };++ const sendTestMessage = async () => {+ setSendingTest(true);+ try {+ await api.sendMessagingTestMessage(sessionId, selected);+ toastSuccess(S.messaging.testMessageSent);+ } catch (e) {+ toastError(apiErrorText(e));+ } finally {+ setSendingTest(false);+ }+ };++ /** Save = persist the selected channel's credentials (no connection side effect; the toggle owns that). */+ const save = async () => {+ if (!form) return;+ const built = formToPut(form, channels[form.channel].secretConfigured);+ if (!built.ok) {+ setFieldErrors(built.errors);+ return;+ }+ setBusy(true);+ try {+ const res =+ built.channel === "telegram"+ ? await api.putTelegramBinding(sessionId, built.body)+ : await api.putFeishuBinding(sessionId, built.body);+ applyChannel(built.channel, res.binding, res.status);+ toastSuccess(S.common.saved);+ } catch (e) {+ toastError(apiErrorText(e));+ } finally {+ setBusy(false);+ }+ };++ /** The Switch: connect/disconnect the SELECTED channel with its stored credentials. */+ const toggleEnabled = async (next: boolean) => {+ setToggling(true);+ try {+ const res = await api.setMessagingBindingState(sessionId, selected, next);+ applyChannel(selected, res.binding, res.status);+ onChanged?.(sessionId, next && res.binding?.enabled === true ? selected : null);+ } catch (e) {+ toastError(apiErrorText(e));+ } finally {+ setToggling(false);+ }+ };++ // Enabling needs a saved credential, no unsaved edits, and the other channel dark;+ // disabling is always allowed. The hint names the strongest reason.+ const enableBlocked = !facts.enabled && (otherEnabled || !facts.secretConfigured || dirty);+ const toggleHint =+ !facts.enabled && enabledChannel !== null && otherEnabled+ ? S.messaging.otherEnabledHint(S.messaging.channelName[enabledChannel])+ : !facts.enabled && !facts.secretConfigured+ ? S.messaging.credentialMissingHint+ : !facts.enabled && dirty+ ? S.messaging.saveBeforeEnable+ : null;++ return {+ form,+ patchForm,+ selectChannel,+ channels,+ fieldErrors,+ dirty,+ busy,+ toggling,+ testing,+ sendingTest,+ testable: form !== null && formTestable(form, facts.secretConfigured),+ toggleBlocked: enableBlocked || toggling || busy,+ toggleHint,+ save,+ toggleEnabled,+ testConnection,+ sendTestMessage,+ };+}++/** External link styled like the models dialog's "get API key" corner action. */+function ExternalLink({ href, label }: { href: string; label: string }) {+ return (+ <a+ href={href}+ target="_blank"+ rel="noreferrer noopener"+ className="shrink-0 text-xs text-brand-600 underline-offset-2 hover:underline dark:text-brand-300"+ >+ {label} ↗+ </a>+ );+}++/**+ * A field with an action link at the label's top-right corner — the models dialog's+ * "get API key" idiom. The control inside carries `aria-label` itself: this wrapper's+ * label row is layout, not a <label> element.+ */+function CornerLinkedField({+ label,+ required,+ link,+ children,+}: {+ label: string;+ required?: boolean;+ link: ReactNode;+ children: ReactNode;+}) {+ return (+ <div className="block">+ <span className="mb-1 flex items-baseline justify-between gap-2">+ <FieldLabel block={false} {...(required ? { required: true } : {})}>+ {label}+ </FieldLabel>+ {link}+ </span>+ {children}+ </div>+ );+}++/**+ * The stored secret's status row, under the secret field — the models-page configured-key+ * idiom: the site-wide mask in mono, and a "clear stored …" checkbox applied on Save+ * (typing into the field unchecks it). Clearing requires the channel's connection to be+ * disabled first, so the checkbox is gated with that hint while enabled.+ */+function StoredSecretRow({+ masked,+ clearLabel,+ checked,+ enabled,+ onChange,+}: {+ masked: string;+ clearLabel: string;+ /** The clear checkbox's state (lives in the form, applied on Save). */+ checked: boolean;+ /** The channel's connection is enabled: clearing is gated until it is turned off. */+ enabled: boolean;+ onChange: (checked: boolean) => void;+}) {+ return (+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-500 dark:text-gray-400">+ <span className="font-mono">{masked}</span>+ <label+ className={`flex items-center gap-1.5 ${enabled ? "cursor-not-allowed opacity-60" : ""}`}+ >+ <input+ type="checkbox"+ checked={checked}+ disabled={enabled}+ onChange={(e) => onChange(e.target.checked)}+ />+ {clearLabel}+ </label>+ {/* A disabled checkbox does not reliably fire hover, so the reason is on screen rather+ than in a title: a gated control that never says why is the bug this avoids. */}+ {enabled && (+ <span className="text-gray-400 dark:text-gray-500">+ {S.messaging.disableBeforeClearHint}+ </span>+ )}+ </div>+ );+}++/**+ * The editor's body, top to bottom: the channel selector, the connection controls (enable+ * toggle + live status, then the two probes, then the hint naming what gates the switch),+ * then the selected channel's credential fields (console link at the credential field's+ * corner, models-style stored-secret row). Only the selector and the controls sit above the+ * fields, and everything above the fields is channel-independent in height, so the toggle+ * and the probes hold one vertical position no matter which channel is selected. Hosts+ * place their own Save action after it and `MessagingBindingHelp` below that.+ */+export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState }) {+ const { form } = b;+ if (!form) return null;+ const channel = form.channel;+ const facts = b.channels[channel];+ const links = CHANNEL_LINKS[channel];+ return (+ <div className="space-y-3">+ {/* Channel first — each channel's config is saved independently, so the selector+ switches forms rather than locking (the mcp transport idiom). */}+ <div role="group" aria-label={S.messaging.channelLabel}>+ <Segmented+ cols={2}+ options={[+ { value: "feishu" as MessagingChannel, label: S.messaging.channelName.feishu },+ { value: "telegram" as MessagingChannel, label: S.messaging.channelName.telegram },+ ]}+ value={channel}+ onChange={(v) => b.selectChannel(v)}+ />+ </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` stays on this line by truncating inside its+ own flex track, so a long message never grows the row and pushes the probes. */}+ <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">+ <Switch+ checked={facts.enabled}+ disabled={b.toggleBlocked}+ onChange={(v) => void b.toggleEnabled(v)}+ />+ {S.messaging.enabled}+ </label>+ <span className="ml-2 text-gray-500 dark:text-gray-400">{S.messaging.statusLabel}</span>+ <span+ {...(facts.status.lastError !== undefined ? { title: facts.status.lastError } : {})}+ className={`font-medium ${toneInk[STATUS_TONE[facts.status.state]]}`}+ >+ {S.messaging.status[facts.status.state]}+ </span>+ {facts.status.state === "error" && facts.status.lastError !== undefined && (+ <span className="min-w-0 flex-1 truncate text-gray-400 dark:text-gray-500">+ {facts.status.lastError}+ </span>+ )}+ </div>+ {/* Entry-level probes — the MCP dialog idiom: standalone buttons, results as toasts. */}+ <div className="flex flex-wrap items-center gap-2">+ <Button+ size="sm"+ disabled={b.testing || b.busy || !b.testable}+ onClick={() => void b.testConnection()}+ >+ {b.testing ? S.messaging.testing : S.messaging.test}+ </Button>+ <Button+ size="sm"+ disabled={+ b.sendingTest || b.busy || facts.status.state !== "connected" || !facts.lastChatKnown+ }+ {...(!facts.lastChatKnown+ ? {+ title:+ channel === "telegram"+ ? S.telegram.testMessageNoChat+ : S.feishu.testMessageNoChat,+ }+ : {})}+ onClick={() => void b.sendTestMessage()}+ >+ {b.sendingTest ? S.messaging.sendingTestMessage : S.messaging.sendTestMessage}+ </Button>+ </div>+ {/* The gating reason closes the control block rather than sitting under the switch:+ it comes and goes with the switch's own state, so anything below it shifts by a+ line — trailing the probes leaves both of them at a fixed offset. */}+ {b.toggleHint !== null && (+ <p className="text-xs text-gray-400 dark:text-gray-500">{b.toggleHint}</p>+ )}+ {/* The credential fields trail the controls above; explanations live in the FAQ folds+ below the save area. */}+ {channel === "telegram" ? (+ <>+ <CornerLinkedField+ label={S.telegram.botToken}+ required={!facts.secretConfigured}+ link={<ExternalLink href={links.console} label={S.messaging.console} />}+ >+ <PasswordInput+ size="sm"+ aria-label={S.telegram.botToken}+ {...(facts.secretConfigured ? { placeholder: S.telegram.botTokenKeepHint } : {})}+ error={errorText(b.fieldErrors.botToken)}+ value={form.telegram.botToken}+ onChange={(e) =>+ b.patchForm({ telegram: { botToken: e.target.value, clearToken: false } })+ }+ autoComplete="off"+ />+ </CornerLinkedField>+ {facts.secretMasked !== null && form.telegram.botToken === "" && (+ <StoredSecretRow+ masked={facts.secretMasked}+ clearLabel={S.telegram.clearToken}+ checked={form.telegram.clearToken}+ enabled={facts.enabled}+ onChange={(checked) =>+ b.patchForm({ telegram: { ...form.telegram, clearToken: checked } })+ }+ />+ )}+ </>+ ) : (+ <>+ <CornerLinkedField+ label={S.feishu.appId}+ required+ link={<ExternalLink href={links.console} label={S.messaging.console} />}+ >+ <Input+ size="sm"+ aria-label={S.feishu.appId}+ error={errorText(b.fieldErrors.appId)}+ value={form.feishu.appId}+ onChange={(e) => b.patchForm({ feishu: { ...form.feishu, appId: e.target.value } })}+ className="font-mono"+ placeholder="cli_xxxxxxxxxxxxxxxx"+ autoComplete="off"+ />+ </CornerLinkedField>+ <PasswordInput+ size="sm"+ label={S.feishu.appSecret}+ {...(facts.secretConfigured+ ? { placeholder: S.feishu.appSecretKeepHint }+ : { required: true })}+ error={errorText(b.fieldErrors.appSecret)}+ value={form.feishu.appSecret}+ onChange={(e) =>+ b.patchForm({+ feishu: { ...form.feishu, appSecret: e.target.value, clearSecret: false },+ })+ }+ autoComplete="off"+ />+ {facts.secretMasked !== null && form.feishu.appSecret === "" && (+ <StoredSecretRow+ masked={facts.secretMasked}+ clearLabel={S.feishu.clearSecret}+ checked={form.feishu.clearSecret}+ enabled={facts.enabled}+ onChange={(checked) =>+ b.patchForm({ feishu: { ...form.feishu, clearSecret: checked } })+ }+ />+ )}+ <Input+ size="sm"+ label={S.feishu.baseDomain}+ hint={S.feishu.baseDomainHint}+ error={errorText(b.fieldErrors.baseDomain)}+ value={form.feishu.baseDomain}+ onChange={(e) =>+ b.patchForm({ feishu: { ...form.feishu, baseDomain: e.target.value } })+ }+ className="font-mono"+ placeholder="https://open.feishu.cn"+ autoComplete="off"+ />+ </>+ )}+ </div>+ );+}++/**+ * The collapsed-by-default FAQ under the save area — three titled `HelpFold`s: the+ * selected channel's setup steps (ending in its tutorial link), what binding does, and+ * troubleshooting. Hosts place it below their Save controls, which is what keeps the+ * form itself opening on the channel selector and the connection controls.+ */+export function MessagingBindingHelp({ channel }: { channel: MessagingChannel }) {+ const per = channel === "telegram" ? S.telegram : S.feishu;+ const links = CHANNEL_LINKS[channel];+ return (+ <div className="space-y-2 border-t border-gray-200 pt-3 dark:border-gray-800">+ <HelpFold title={S.messaging.faqSetupTitle}>+ <ol className="list-decimal space-y-1 pl-4">+ {per.setupSteps.map((step) => (+ <li key={step}>{step}</li>+ ))}+ </ol>+ <p className="mt-1.5">+ <ExternalLink href={links.tutorial} label={S.messaging.tutorial} />+ </p>+ </HelpFold>+ <HelpFold title={S.messaging.faqWhatTitle}>+ <p>{per.intro}</p>+ </HelpFold>+ <HelpFold title={S.messaging.faqTroubleTitle}>+ <ul className="list-disc space-y-1 pl-4">+ <li>{S.messaging.troubleNoChat}</li>+ <li>{S.messaging.troubleConnError}</li>+ </ul>+ </HelpFold>+ </div>+ );+}diff --git a/packages/web/src/features/messaging/messaging-binding-form.ts b/packages/web/src/features/messaging/messaging-binding-form.tsnew file mode 100644index 00000000..fce75061--- /dev/null+++ b/packages/web/src/features/messaging/messaging-binding-form.ts@@ -0,0 +1,206 @@+/**+ * Messaging binding form helpers — conversion between the channel-aware editor's editable+ * state and the per-channel PUT/test DTOs (pure logic, unit-tested without a DOM; the+ * mcp-servers-form convention). The form keeps one sub-state per channel so switching the+ * selector back and forth never loses what was typed; `channel` names the selected one,+ * and only its fields are validated or submitted.+ *+ * Secrets never round-trip: `bindingToForm` always leaves the secret field empty (the+ * server only ever returns a masked value), and `formToPut` omits a blank one so the+ * server keeps the stored value. Validation errors come back as codes; the component maps+ * them to localized messages.+ */+import type {+ FeishuBindingPutRequest,+ FeishuTestRequest,+ MessagingBindingInfo,+ MessagingChannel,+ TelegramBindingPutRequest,+ TelegramTestRequest,+} from "@prismshadow/penguin-server/api";++/** Default Feishu open-platform domain (shown prefilled; Lark tenants overwrite it). */+export const FEISHU_DEFAULT_DOMAIN = "https://open.feishu.cn";++/** The token shape @BotFather issues — mirrors the server's identity rule, for immediate feedback. */+const TELEGRAM_TOKEN_RE = /^\d+:[A-Za-z0-9_-]{5,}$/;++export interface FeishuFormFields {+ appId: string;+ /** Always starts empty; a non-empty value replaces the stored secret on save. */+ appSecret: string;+ baseDomain: string;+ /** The stored-secret clear checkbox (models idiom): applied on save, a typed secret wins over it. */+ clearSecret: boolean;+}++export interface TelegramFormFields {+ /** Always starts empty; a non-empty value replaces the stored token on save. */+ botToken: string;+ /** The stored-token clear checkbox (models idiom): applied on save, a typed token wins over it. */+ clearToken: boolean;+}++/** Editable state backing the binding editor: the selected channel plus both channels' fields. */+export interface MessagingFormState {+ channel: MessagingChannel;+ feishu: FeishuFormFields;+ telegram: TelegramFormFields;+}++export type MessagingFormField = "appId" | "appSecret" | "baseDomain" | "botToken";++export type MessagingFormErrorCode = "required" | "url_invalid" | "token_invalid";++export type MessagingFormErrors = Partial<Record<MessagingFormField, MessagingFormErrorCode>>;++/** A valid submit names its channel so the caller picks that channel's endpoint. */+export type MessagingFormResult =+ | { ok: true; channel: "feishu"; body: FeishuBindingPutRequest }+ | { ok: true; channel: "telegram"; body: TelegramBindingPutRequest }+ | { ok: false; errors: MessagingFormErrors };++export type MessagingTestRequestByChannel =+ | { channel: "feishu"; body: FeishuTestRequest }+ | { channel: "telegram"; body: TelegramTestRequest };++export function emptyMessagingForm(channel: MessagingChannel = "feishu"): MessagingFormState {+ return {+ channel,+ feishu: { appId: "", appSecret: "", baseDomain: FEISHU_DEFAULT_DOMAIN, clearSecret: false },+ telegram: { botToken: "", clearToken: false },+ };+}++/**+ * Builds the editor's form from every saved config: each channel's non-secret fields+ * load (secrets stay empty — masked values never round-trip — and clear checkboxes start+ * unchecked), and the selector starts on the enabled channel, else the first saved one,+ * else Feishu.+ */+export function bindingsToForm(bindings: MessagingBindingInfo[]): MessagingFormState {+ const enabled = bindings.find((b) => b.enabled)?.channel;+ const form = emptyMessagingForm(enabled ?? bindings[0]?.channel ?? "feishu");+ for (const info of bindings) {+ if (info.channel === "feishu") {+ form.feishu = {+ appId: info.appId,+ appSecret: "",+ baseDomain: info.baseDomain,+ clearSecret: false,+ };+ }+ // Telegram's one field is the secret itself, so its sub-state always loads empty.+ }+ return form;+}++/** A syntactically valid http(s) URL (the server normalizes to the origin). */+function isHttpUrl(raw: string): boolean {+ try {+ const url = new URL(raw);+ return url.protocol === "http:" || url.protocol === "https:";+ } catch {+ return false;+ }+}++/**+ * Validates the selected channel's fields and builds its PUT body. `hasStoredSecret`+ * relaxes the secret requirement: with a saved binding an empty field means "keep it",+ * on a first bind it is an error. A blank Feishu domain falls back to the default rather+ * than erroring — the field is prefilled, and clearing it is a "give me the default"+ * gesture.+ */+export function formToPut(form: MessagingFormState, hasStoredSecret: boolean): MessagingFormResult {+ const errors: MessagingFormErrors = {};+ if (form.channel === "telegram") {+ const botToken = form.telegram.botToken.trim();+ // A typed token wins over a stale clear checkbox (the models idiom).+ const clearing = botToken === "" && form.telegram.clearToken && hasStoredSecret;+ if (botToken === "" && !hasStoredSecret) errors.botToken = "required";+ else if (botToken !== "" && !TELEGRAM_TOKEN_RE.test(botToken)) {+ errors.botToken = "token_invalid";+ }+ if (Object.keys(errors).length > 0) return { ok: false, errors };+ return {+ ok: true,+ channel: "telegram",+ body: {+ ...(botToken !== "" ? { botToken } : {}),+ ...(clearing ? { clearBotToken: true } : {}),+ },+ };+ }+ const appId = form.feishu.appId.trim();+ if (appId === "") errors.appId = "required";+ const appSecret = form.feishu.appSecret.trim();+ const clearing = appSecret === "" && form.feishu.clearSecret && hasStoredSecret;+ if (appSecret === "" && !hasStoredSecret) errors.appSecret = "required";+ const baseDomain = form.feishu.baseDomain.trim() || FEISHU_DEFAULT_DOMAIN;+ if (!isHttpUrl(baseDomain)) errors.baseDomain = "url_invalid";+ if (Object.keys(errors).length > 0) return { ok: false, errors };+ return {+ ok: true,+ channel: "feishu",+ body: {+ appId,+ ...(appSecret !== "" ? { appSecret } : {}),+ ...(clearing ? { clearAppSecret: true } : {}),+ baseDomain,+ },+ };+}++/**+ * The credential test's request: only the fields the form actually carries — omitted ones+ * fall back to the stored binding server-side, so testing a saved binding needs no+ * re-typed secret.+ */+export function formToTest(form: MessagingFormState): MessagingTestRequestByChannel {+ if (form.channel === "telegram") {+ const botToken = form.telegram.botToken.trim();+ return { channel: "telegram", body: { ...(botToken !== "" ? { botToken } : {}) } };+ }+ const appId = form.feishu.appId.trim();+ const appSecret = form.feishu.appSecret.trim();+ const baseDomain = form.feishu.baseDomain.trim();+ return {+ channel: "feishu",+ body: {+ ...(appId !== "" ? { appId } : {}),+ ...(appSecret !== "" ? { appSecret } : {}),+ ...(baseDomain !== "" ? { baseDomain } : {}),+ },+ };+}++/**+ * Unsaved edits on the selected channel: any field differing from the loaded baseline (a+ * typed secret always counts — it always loads empty — and so does a checked clear box).+ */+export function formDirty(form: MessagingFormState, baseline: MessagingFormState): boolean {+ if (form.channel === "telegram") {+ return form.telegram.botToken.trim() !== "" || form.telegram.clearToken;+ }+ return (+ form.feishu.appId !== baseline.feishu.appId ||+ form.feishu.baseDomain !== baseline.feishu.baseDomain ||+ form.feishu.appSecret.trim() !== "" ||+ form.feishu.clearSecret+ );+}++/**+ * The credential probe needs a testable credential: the selected channel's draft, or its+ * stored secret (`secretConfigured` — a stored config whose secret was cleared has+ * nothing to probe).+ */+export function formTestable(form: MessagingFormState, secretConfigured: boolean): boolean {+ if (form.channel === "telegram") {+ return form.telegram.botToken.trim() !== "" || secretConfigured;+ }+ return (+ (form.feishu.appId.trim() !== "" && form.feishu.appSecret.trim() !== "") || secretConfigured+ );+}diff --git a/packages/web/src/features/messaging/messaging-binding-modal.tsx b/packages/web/src/features/messaging/messaging-binding-modal.tsxnew file mode 100644index 00000000..186404a8--- /dev/null+++ b/packages/web/src/features/messaging/messaging-binding-modal.tsx@@ -0,0 +1,63 @@+/**+ * Messaging binding dialog (session-row "Messaging binding…"): a Modal shell over the+ * shared channel-aware binding editor — the same hook + body the conversation's Messaging+ * dock panel renders, so the sidebar can manage bindings without opening the chat and+ * the two surfaces can never drift. This host contributes only the Modal frame, the+ * footer's Close / Save placement, and the FAQ folds' position at the body's end; every+ * behavior (channel switching, save/enable split, single-enabled gating, models-style+ * secret clearing, status poll) lives in the editor. There is no unbind action —+ * removing a credential is the secret field's clear checkbox.+ */+import type { MessagingChannel } from "@prismshadow/penguin-server/api";+import { S } from "../../lib/strings";+import { Button } from "../../components/ui/button";+import { Modal } from "../../components/ui/modal";+import {+ MessagingBindingBody,+ MessagingBindingHelp,+ useMessagingBinding,+} from "./messaging-binding-editor";++export function MessagingBindingModal({+ sessionId,+ onClose,+ onChanged,+}: {+ sessionId: string;+ onClose: () => void;+ /** Fired when the ENABLED channel changed (null = none); callers refresh their row/list indicator. */+ onChanged?: (sessionId: string, channel: MessagingChannel | null) => void;+}) {+ // The dialog polls for its whole lifetime (it unmounts on close).+ const b = useMessagingBinding(sessionId, {+ poll: true,+ ...(onChanged ? { onChanged } : {}),+ onLoadFailed: onClose,+ });++ return (+ <Modal+ open+ title={S.messaging.dialogTitle}+ onClose={onClose}+ footer={+ <>+ <Button onClick={onClose}>{S.common.close}</Button>+ <Button+ variant="primary"+ disabled={b.busy || b.form === null}+ onClick={() => void b.save()}+ >+ {b.busy ? S.common.saving : S.common.save}+ </Button>+ </>+ }+ >+ <div className="space-y-3">+ <MessagingBindingBody b={b} />+ {/* The Save action lives in the footer; the collapsed FAQ trails the body. */}+ {b.form !== null && <MessagingBindingHelp channel={b.form.channel} />}+ </div>+ </Modal>+ );+}diff --git a/packages/web/src/features/messaging/messaging-panel.tsx b/packages/web/src/features/messaging/messaging-panel.tsxnew file mode 100644index 00000000..8a00ed4f--- /dev/null+++ b/packages/web/src/features/messaging/messaging-panel.tsx@@ -0,0 +1,50 @@+/**+ * Messaging panel — the current conversation's messaging bindings as a dock tab, sitting+ * in the panel rail beside the subagents and Trace panels. It renders the SAME shared+ * channel-aware binding editor as the session-row dialog (hook + body, not a fork): the+ * channel selector switching between the two channels' forms (each independently+ * savable), then the connection controls — the enable/disable toggle (one enabled channel+ * per conversation) with the live status line, both probes, and the hint naming what gates+ * the switch — then the per-channel credential fields with the console link at the field+ * corner and the models-style stored-secret row, and the collapsed FAQ folds below the+ * Save area. There is no unbind action — removing a credential is the secret field's clear+ * checkbox.+ *+ * Status polling is gated on `active` (the dock keeps hidden tabs mounted): a hidden tab+ * neither polls nor loses the form state it accumulated.+ */+import { S } from "../../lib/strings";+import { Button } from "../../components/ui/button";+import { Skeleton } from "../../components/ui/skeleton";+import {+ MessagingBindingBody,+ MessagingBindingHelp,+ useMessagingBinding,+} from "./messaging-binding-editor";++export function MessagingPanel({ sessionId, active }: { sessionId: string; active: boolean }) {+ const b = useMessagingBinding(sessionId, { poll: active });++ return (+ <div className="h-full overflow-y-auto p-3">+ {b.form === null ? (+ <div className="space-y-2">+ <Skeleton className="h-5 w-40" />+ <Skeleton className="h-24 w-full" />+ </div>+ ) : (+ <div className="space-y-3">+ <MessagingBindingBody b={b} />+ {/* The dialog places Save in its footer; the panel keeps it under the form. */}+ <div className="flex items-center justify-end gap-2">+ <Button variant="primary" size="sm" disabled={b.busy} onClick={() => void b.save()}>+ {b.busy ? S.common.saving : S.common.save}+ </Button>+ </div>+ {/* Below the save area: the collapsed setup/what/troubleshooting folds. */}+ <MessagingBindingHelp channel={b.form.channel} />+ </div>+ )}+ </div>+ );+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 53b42d4c..6a5c9c1b 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1705,6 +1705,8 @@ Scenarios:pinSession: "Pin",unpinSession: "Unpin",pinnedSession: "Pinned",+ /** The hover ellipsis button that opens the row's full context menu. */+ moreActions: "More",/** Sidebar group "reveal/load next page" row (display cap + server paging). */loadMore: "More",/** Per-group reveal row: n = conversations THIS group still hides (one click reveals/loads one page more). */@@ -1760,6 +1762,114 @@ Scenarios:} as Record<string, string>,},+ /** Feishu-channel strings of the messaging binding editor (channel-neutral ones live under `messaging`). */+ feishu: {+ /** The what-binding-does FAQ fold's body (this channel's flavor). */+ intro:+ "Once bound, messages sent to the Feishu bot flow into this conversation, and the AI's replies are sent back to Feishu as plain text. You need a self-built Feishu app with the bot capability and the message-receive event subscribed in long-connection mode.",+ appId: "App ID",+ appSecret: "App Secret",+ /** Shown while a saved secret exists: submitting an empty field keeps it. */+ appSecretKeepHint: "Leave empty to keep the saved App Secret",+ /** The stored-secret row's clear checkbox (the models-page clear idiom). */+ clearSecret: "Clear stored App Secret",+ baseDomain: "API domain",+ baseDomainHint: "https://open.feishu.cn for Feishu, https://open.larksuite.com for Lark",+ invalidDomain: "The domain must be an http(s) URL",+ /** Why "send test message" is disabled before the bot has ever been messaged. */+ testMessageNoChat: "Message the bot once in Feishu first, so it knows which chat to send to",+ /** The setup FAQ fold's steps. */+ setupSteps: [+ "Create a self-built app in the Feishu developer console",+ "Enable the bot capability for the app",+ "Subscribe to the message-receive event, with the subscription mode set to long connection",+ "Copy the App ID and App Secret from the credentials page into the form above",+ "Publish an app version, get it approved, then message the bot once in Feishu",+ ],+ },++ /** Telegram-channel strings of the messaging binding editor (channel-neutral ones live under `messaging`). */+ telegram: {+ /** The what-binding-does FAQ fold's body (this channel's flavor). */+ intro:+ "Once bound, messages sent to the Telegram bot flow into this conversation, and the AI's replies are sent back to Telegram as plain text. Create a bot with @BotFather and paste its Bot Token — no public URL is needed.",+ botToken: "Bot Token",+ /** Shown while a saved token exists: submitting an empty field keeps it. */+ botTokenKeepHint: "Leave empty to keep the saved Bot Token",+ /** The stored-token row's clear checkbox (the models-page clear idiom). */+ clearToken: "Clear stored Bot Token",+ invalidToken: "The Bot Token looks like <digits>:<secret>, as issued by @BotFather",+ /** Why "send test message" is disabled before the bot has ever been messaged. */+ testMessageNoChat: "Message the bot once in Telegram first, so it knows which chat to send to",+ /** The setup FAQ fold's steps. */+ setupSteps: [+ "Open @BotFather in Telegram and send /newbot to create a bot",+ "Name it as prompted, then copy the Bot Token @BotFather returns into the form above",+ "Find the bot in Telegram and send it one message",+ ],+ },++ /**+ * Session ↔ messaging-bot binding: the dock panel, the row action + dialog, and the+ * channel-neutral editor strings (per-channel fields live under `feishu` / `telegram`).+ */+ messaging: {+ panelTitle: "Messaging",+ /** Session-row context-menu action (the trailing ellipsis marks that a dialog follows). */+ bindAction: "Messaging binding…",+ dialogTitle: "Messaging binding",+ /** The channel selector (always live: each channel's config is saved independently). */+ channelLabel: "Channel",+ channelName: {+ feishu: "Feishu",+ telegram: "Telegram",+ },+ /** Per-channel external links: the tutorial (in the setup FAQ fold) and the console (at the credential field's corner). */+ tutorial: "Open tutorial",+ console: "Open developer console",+ /** The connection toggle (flips immediately, using the stored credentials). */+ enabled: "Enable connection",+ /** Why the toggle is gated while the form has unsaved edits. */+ saveBeforeEnable: "Save the credentials first, then enable the connection",+ test: "Test connection",+ testing: "Testing…",+ testOk: (ms: number): string => `Connected (${ms}ms)`,+ /** Success feedback naming the account the credentials sign in as (Telegram: the bot's @username). */+ testOkAs: (account: string, ms: number): string => `Connected as ${account} (${ms}ms)`,+ testFail: (reason: string): string => `Connection failed: ${reason}`,+ sendTestMessage: "Send test message",+ sendingTestMessage: "Sending…",+ testMessageSent: "Test message sent",+ statusLabel: "Connection status",+ status: {+ disconnected: "Not connected",+ connecting: "Connecting",+ connected: "Connected",+ error: "Connection error",+ },+ /** Why the enable switch is gated while the OTHER channel holds the connection. */+ otherEnabledHint: (other: string): string =>+ `Only one channel can be enabled per conversation: turn off the ${other} connection first`,+ /** Why the enable switch is gated while the selected channel has no stored credential. */+ credentialMissingHint: "Enter and save the credential first, then enable the connection",+ /** Why the clear checkbox is gated while the channel's connection is enabled. */+ disableBeforeClearHint: "Disable the connection before clearing the credential",+ /** Enabled-row indicator's tooltip / sr text (the small per-channel glyph on the session row). */+ enabledIndicator: {+ feishu: "Feishu connection enabled",+ telegram: "Telegram connection enabled",+ },+ /** The collapsed FAQ folds below the save area. */+ faqSetupTitle: "Set up the bot",+ faqWhatTitle: "What binding does",+ faqTroubleTitle: "Troubleshooting",+ /** Troubleshooting entries (bot must be messaged once; connection errors point at credentials). */+ troubleNoChat:+ "“Send test message” disabled? The bot must have received one message first, so it knows which chat to send to.",+ troubleConnError:+ "Connection status shows an error? Check the credentials; for Feishu also confirm the API domain and the long-connection event subscription.",+ },+/** Subagents side panel: call-graph of the latest Task + the selected child conversation. */subagentPanel: {topologyLabel: "Call graph",@@ -1980,6 +2090,24 @@ 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.",+ telegram_no_chat:+ "No Telegram message received yet — message the bot once in Telegram first.",+ telegram_send_failed: "Sending the Telegram message failed.",+ another_channel_enabled:+ "Another channel's connection is enabled on this conversation: disable it 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.tsindex b7ebc8ee..b94da347 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1666,6 +1666,8 @@ Benchmark:pinSession: "置顶",unpinSession: "取消置顶",pinnedSession: "已置顶",+ /** The hover ellipsis button that opens the row's full context menu. */+ moreActions: "更多",/** Sidebar group "reveal/load next page" row (display cap + server paging). */loadMore: "更多",/** Per-group reveal row: n = conversations THIS group still hides (one click reveals/loads one page more). */@@ -1722,6 +1724,112 @@ Benchmark:} as Record<string, string>,},+ /** Feishu-channel strings of the messaging binding editor (channel-neutral ones live under `messaging`). */+ feishu: {+ /** The what-binding-does FAQ fold's body (this channel's flavor). */+ intro:+ "绑定后,发给飞书机器人的消息会进入本对话,AI 的回复会以纯文本发回飞书。需要一个开通了机器人能力、订阅了接收消息事件(长连接方式)的飞书自建应用。",+ appId: "App ID",+ appSecret: "App Secret",+ /** Shown while a saved secret exists: submitting an empty field keeps it. */+ appSecretKeepHint: "留空保持已保存的 App Secret 不变",+ /** The stored-secret row's clear checkbox (the models-page clear idiom). */+ clearSecret: "清除已存 App Secret",+ baseDomain: "API 域名",+ baseDomainHint: "飞书为 https://open.feishu.cn,Lark 为 https://open.larksuite.com",+ invalidDomain: "域名需为 http(s):// 地址",+ /** Why "send test message" is disabled before the bot has ever been messaged. */+ testMessageNoChat: "先在飞书中给机器人发一条消息,机器人才知道要发到哪个会话",+ /** The setup FAQ fold's steps. */+ setupSteps: [+ "在飞书开发者后台创建一个企业自建应用",+ "为应用开通机器人能力",+ "订阅「接收消息」事件,事件订阅方式选择「长连接」",+ "在「凭证与基础信息」页取得 App ID 与 App Secret,填入上方表单",+ "发布应用版本并通过审核,然后在飞书中给机器人发一条消息",+ ],+ },++ /** Telegram-channel strings of the messaging binding editor (channel-neutral ones live under `messaging`). */+ telegram: {+ /** The what-binding-does FAQ fold's body (this channel's flavor). */+ intro:+ "绑定后,发给 Telegram 机器人的消息会进入本对话,AI 的回复会以纯文本发回 Telegram。用 @BotFather 创建机器人并粘贴其 Bot Token 即可,无需公网地址。",+ botToken: "Bot Token",+ /** Shown while a saved token exists: submitting an empty field keeps it. */+ botTokenKeepHint: "留空保持已保存的 Bot Token 不变",+ /** The stored-token row's clear checkbox (the models-page clear idiom). */+ clearToken: "清除已存 Bot Token",+ invalidToken: "Bot Token 形如「数字:密钥」,由 @BotFather 签发",+ /** Why "send test message" is disabled before the bot has ever been messaged. */+ testMessageNoChat: "先在 Telegram 中给机器人发一条消息,机器人才知道要发到哪个会话",+ /** The setup FAQ fold's steps. */+ setupSteps: [+ "在 Telegram 中打开 @BotFather,发送 /newbot 创建机器人",+ "按提示取名后,复制 @BotFather 返回的 Bot Token,填入上方表单",+ "在 Telegram 中找到这个机器人,给它发一条消息",+ ],+ },++ /**+ * Session ↔ messaging-bot binding: the dock panel, the row action + dialog, and the+ * channel-neutral editor strings (per-channel fields live under `feishu` / `telegram`).+ */+ messaging: {+ panelTitle: "消息软件",+ /** Session-row context-menu action (the trailing ellipsis marks that a dialog follows). */+ bindAction: "消息软件绑定…",+ dialogTitle: "消息软件绑定",+ /** The channel selector (always live: each channel's config is saved independently). */+ channelLabel: "渠道",+ channelName: {+ feishu: "飞书",+ telegram: "Telegram",+ },+ /** Per-channel external links: the tutorial (in the setup FAQ fold) and the console (at the credential field's corner). */+ tutorial: "前往教程",+ console: "前往开发者后台",+ /** The connection toggle (flips immediately, using the stored credentials). */+ enabled: "启用连接",+ /** Why the toggle is gated while the form has unsaved edits. */+ saveBeforeEnable: "先保存凭证,再启用连接",+ test: "测试连接",+ testing: "测试中…",+ testOk: (ms: number): string => `连接成功(${ms}ms)`,+ /** Success feedback naming the account the credentials sign in as (Telegram: the bot's @username). */+ testOkAs: (account: string, ms: number): string => `连接成功,机器人为 ${account}(${ms}ms)`,+ testFail: (reason: string): string => `连接失败:${reason}`,+ sendTestMessage: "发送测试消息",+ sendingTestMessage: "发送中…",+ testMessageSent: "测试消息已发送",+ statusLabel: "连接状态",+ status: {+ disconnected: "未连接",+ connecting: "连接中",+ connected: "已连接",+ error: "连接错误",+ },+ /** Why the enable switch is gated while the OTHER channel holds the connection. */+ otherEnabledHint: (other: string): string => `同一会话只能启用一个渠道:先停用${other}连接`,+ /** Why the enable switch is gated while the selected channel has no stored credential. */+ credentialMissingHint: "先填写并保存凭证,再启用连接",+ /** Why the clear checkbox is gated while the channel's connection is enabled. */+ disableBeforeClearHint: "先停用连接,才能清除凭证",+ /** Enabled-row indicator's tooltip / sr text (the small per-channel glyph on the session row). */+ enabledIndicator: {+ feishu: "飞书连接已启用",+ telegram: "Telegram 连接已启用",+ },+ /** The collapsed FAQ folds below the save area. */+ faqSetupTitle: "如何创建机器人",+ faqWhatTitle: "绑定后会发生什么",+ faqTroubleTitle: "常见问题",+ /** Troubleshooting entries (bot must be messaged once; connection errors point at credentials). */+ troubleNoChat: "「发送测试消息」不可用?机器人要先收到过一条消息,才知道要发到哪个会话。",+ troubleConnError:+ "连接状态显示错误?检查凭证是否正确;飞书还需确认 API 域名与事件订阅方式(长连接)。",+ },+/** Subagents side panel: call-graph of the latest Task + the selected child conversation. */subagentPanel: {topologyLabel: "调用关系",@@ -1942,6 +2050,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: "该会话已启用另一渠道的连接:先停用它,再启用当前渠道。",+ messaging_disable_before_clear: "先停用该渠道的连接,才能清除其凭证。",},},};diff --git a/packages/web/test/help-fold.test.ts b/packages/web/test/help-fold.test.tsindex 537ad027..176dbe64 100644--- a/packages/web/test/help-fold.test.ts+++ b/packages/web/test/help-fold.test.ts@@ -49,4 +49,16 @@ describe("HelpFold", () => {expect(named).toContain(`aria-label="${accessible}"`);expect(accessible.startsWith(S.common.moreInfo)).toBe(true);});++ it("lets a fold in a stack title itself, and then carries no second name", () => {+ // A column of identical "More info" rows says nothing about which one to open, so an FAQ+ // titles each fold. The visible title IS the accessible name — an aria-label beside it+ // would be a second name for one trigger, which is what breaks "label in name".+ const titled = renderToStaticMarkup(+ createElement(HelpFold, { title: "Set up the bot", label: "Vault", children: DESC }),+ );+ expect(titled).toContain("Set up the bot");+ expect(titled).not.toContain(S.common.moreInfo);+ expect(titled).not.toContain("aria-label=");+ });});diff --git a/packages/web/test/messaging-binding-editor.test.ts b/packages/web/test/messaging-binding-editor.test.tsnew file mode 100644index 00000000..cf5143bd--- /dev/null+++ b/packages/web/test/messaging-binding-editor.test.ts@@ -0,0 +1,150 @@+/**+ * The messaging binding editor's rendered shape (src/features/messaging/messaging-binding-editor.tsx).+ *+ * Four 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 — and that+ * checkbox is gated, on screen, while the channel holds the connection.+ */+import { describe, expect, it } from "vitest";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import type { MessagingChannel } from "@prismshadow/penguin-server/api";+import {+ MessagingBindingBody,+ MessagingBindingHelp,+ type MessagingBindingEditorState,+ type MessagingChannelFacts,+} from "../src/features/messaging/messaging-binding-editor";+import { emptyMessagingForm } from "../src/features/messaging/messaging-binding-form";+import { S } from "../src/lib/strings";++const DARK: MessagingChannelFacts = {+ secretConfigured: false,+ secretMasked: null,+ enabled: false,+ status: { state: "disconnected" },+ lastChatKnown: false,+};++/** A state object shaped like the hook's, with the handlers stubbed (this renders, never acts). */+function stateOf(+ channel: MessagingChannel,+ facts: Partial<Record<MessagingChannel, MessagingChannelFacts>> = {},+ extra: Partial<MessagingBindingEditorState> = {},+): MessagingBindingEditorState {+ const noop = async () => {};+ return {+ form: emptyMessagingForm(channel),+ patchForm: () => {},+ selectChannel: () => {},+ channels: { feishu: DARK, telegram: DARK, ...facts },+ fieldErrors: {},+ dirty: false,+ busy: false,+ toggling: false,+ testing: false,+ sendingTest: false,+ testable: false,+ toggleBlocked: false,+ toggleHint: null,+ save: noop,+ toggleEnabled: noop,+ testConnection: noop,+ sendTestMessage: noop,+ ...extra,+ };+}++const render = (state: MessagingBindingEditorState) =>+ renderToStaticMarkup(createElement(MessagingBindingBody, { b: state }));++describe("MessagingBindingBody", () => {+ it("opens on the fields: no explanatory prose above the first input", () => {+ const feishu = render(stateOf("feishu"));+ expect(feishu).toContain(S.feishu.appId);+ // The intro moved into the FAQ fold; leading the form with it is what this change undid.+ expect(feishu).not.toContain(S.feishu.intro);+ expect(render(stateOf("telegram"))).not.toContain(S.telegram.intro);+ });++ it("hangs each channel's developer-console link on its credential field's corner", () => {+ // The models dialog's "get API key" idiom: the link sits where the value is pasted, so the+ // reader never has to leave the field to find out where the value comes from.+ expect(render(stateOf("feishu"))).toContain('href="https://open.feishu.cn/app"');+ expect(render(stateOf("telegram"))).toContain('href="https://core.telegram.org/bots/api"');+ });++ it("offers a stored secret's removal as the clear checkbox, gated on screen while enabled", () => {+ const saved: MessagingChannelFacts = {+ secretConfigured: true,+ secretMasked: "abcd…7890",+ enabled: false,+ status: { state: "disconnected" },+ lastChatKnown: false,+ };+ const dark = render(stateOf("feishu", { feishu: saved }));+ expect(dark).toContain("abcd…7890");+ expect(dark).toContain(S.feishu.clearSecret);+ expect(dark).toContain('type="checkbox"/>');+ expect(dark).not.toContain(S.messaging.disableBeforeClearHint);++ // Enabled: clearing would leave a live connection running on a credential the store no+ // longer has, so the box is disabled — and says why, since a disabled control does not+ // reliably fire hover.+ const live = render(+ stateOf("feishu", { feishu: { ...saved, enabled: true, status: { state: "connected" } } }),+ );+ expect(live).toContain('type="checkbox" disabled=""');+ expect(live).toContain(S.messaging.disableBeforeClearHint);+ });++ it("shows the switch's gating reason when the other channel holds the connection", () => {+ const hint = S.messaging.otherEnabledHint(S.messaging.channelName.feishu);+ const html = render(+ stateOf(+ "telegram",+ { feishu: { ...DARK, secretConfigured: true, enabled: true } },+ { toggleBlocked: true, toggleHint: hint },+ ),+ );+ expect(html).toContain(hint);+ });+});++describe("MessagingBindingHelp", () => {+ it("stacks three self-titled folds, all collapsed, carrying the relocated explanation", () => {+ const html = renderToStaticMarkup(+ createElement(MessagingBindingHelp, { channel: "feishu" as MessagingChannel }),+ );+ for (const title of [+ S.messaging.faqSetupTitle,+ S.messaging.faqWhatTitle,+ S.messaging.faqTroubleTitle,+ ]) {+ expect(html).toContain(title);+ }+ expect(html.match(/aria-expanded="false"/g)).toHaveLength(3);+ expect(html.match(/<div id="[^"]+" hidden/g)).toHaveLength(3);+ // 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);+ expect(html).toContain(S.messaging.troubleNoChat);+ expect(html).toContain(S.feishu.setupSteps[0]);+ });++ it("puts each channel's tutorial link in its setup fold", () => {+ const feishu = renderToStaticMarkup(+ createElement(MessagingBindingHelp, { channel: "feishu" as MessagingChannel }),+ );+ expect(feishu).toContain(+ 'href="https://open.feishu.cn/document/develop-an-echo-bot/introduction"',+ );+ const telegram = renderToStaticMarkup(+ createElement(MessagingBindingHelp, { channel: "telegram" as MessagingChannel }),+ );+ expect(telegram).toContain('href="https://core.telegram.org/bots/tutorial"');+ expect(telegram).toContain(S.telegram.setupSteps[0]);+ });+});diff --git a/packages/web/test/messaging-binding-form.test.ts b/packages/web/test/messaging-binding-form.test.tsnew file mode 100644index 00000000..0cd4fecc--- /dev/null+++ b/packages/web/test/messaging-binding-form.test.ts@@ -0,0 +1,267 @@+/**+ * messaging-binding-form.ts unit tests: the channel-aware form ↔ DTO conversion behind+ * the binding editor. The load-bearing rules are the secret round-trip — secret fields+ * always load empty, an empty submit keeps the stored secret (the PUT body omits it), and+ * only a first bind requires one — the models-idiom clear checkbox (applied on save, a+ * typed secret wins over it), the per-channel submit routing (only the selected channel's+ * fields are validated and sent), and the blank-domain-means-default fallback.+ */+import { describe, expect, it } from "vitest";+import type { FeishuBindingInfo, TelegramBindingInfo } from "@prismshadow/penguin-server/api";+import {+ FEISHU_DEFAULT_DOMAIN,+ bindingsToForm,+ emptyMessagingForm,+ formDirty,+ formTestable,+ formToPut,+ formToTest,+} from "../src/features/messaging/messaging-binding-form";++const STORED_FEISHU: FeishuBindingInfo = {+ channel: "feishu",+ sessionId: "session-1",+ appId: "cli_abc",+ appSecretMasked: "abcd…wxyz",+ baseDomain: "https://open.larksuite.com",+ enabled: false,+ lastChatKnown: true,+ createdAt: "2026-08-25T00:00:00.000Z",+ updatedAt: "2026-08-25T00:00:00.000Z",+};++const STORED_TELEGRAM: TelegramBindingInfo = {+ channel: "telegram",+ sessionId: "session-1",+ botId: "7000000001",+ botTokenMasked: "7000…1111",+ enabled: true,+ lastChatKnown: false,+ createdAt: "2026-08-26T00:00:00.000Z",+ updatedAt: "2026-08-26T00:00:00.000Z",+};++describe("emptyMessagingForm / bindingsToForm", () => {+ it("starts empty forms on Feishu with the default domain, both channels blank", () => {+ expect(emptyMessagingForm()).toEqual({+ channel: "feishu",+ feishu: { appId: "", appSecret: "", baseDomain: FEISHU_DEFAULT_DOMAIN, clearSecret: false },+ telegram: { botToken: "", clearToken: false },+ });+ });++ it("loads every saved config's non-secret fields, selects the enabled channel, and never loads a secret back", () => {+ // The masked value must not land in an editable field — an unedited save would+ // otherwise overwrite the real secret with its mask.+ const both = bindingsToForm([STORED_FEISHU, STORED_TELEGRAM]);+ expect(both).toEqual({+ channel: "telegram", // the enabled one wins the initial selection+ feishu: {+ appId: "cli_abc",+ appSecret: "",+ baseDomain: "https://open.larksuite.com",+ clearSecret: false,+ },+ telegram: { botToken: "", clearToken: false },+ });+ // No enabled channel: the first saved one is selected; nothing saved: Feishu.+ expect(bindingsToForm([STORED_FEISHU]).channel).toBe("feishu");+ expect(bindingsToForm([]).channel).toBe("feishu");+ });+});++describe("formToPut (feishu)", () => {+ it("omits a blank secret so the server keeps the stored one", () => {+ const res = formToPut(bindingsToForm([STORED_FEISHU]), true);+ expect(res).toEqual({+ ok: true,+ channel: "feishu",+ body: { appId: "cli_abc", baseDomain: "https://open.larksuite.com" },+ });+ });++ it("carries a typed secret, trimmed", () => {+ const form = bindingsToForm([STORED_FEISHU]);+ form.feishu.appSecret = " new-secret ";+ const res = formToPut(form, true);+ expect(res.ok && res.channel === "feishu" && res.body.appSecret).toBe("new-secret");+ });++ it("requires appId always, and a secret only on a first bind", () => {+ const blank = formToPut(emptyMessagingForm(), false);+ expect(blank).toEqual({ ok: false, errors: { appId: "required", appSecret: "required" } });+ // The same empty secret is fine once one is stored.+ const rebind = emptyMessagingForm();+ rebind.feishu.appId = "cli_x";+ expect(formToPut(rebind, true).ok).toBe(true);+ });++ it("maps the checked clear box to clearAppSecret, with a typed secret winning over it", () => {+ const clearing = bindingsToForm([STORED_FEISHU]);+ clearing.feishu.clearSecret = true;+ expect(formToPut(clearing, true)).toEqual({+ ok: true,+ channel: "feishu",+ body: { appId: "cli_abc", clearAppSecret: true, baseDomain: "https://open.larksuite.com" },+ });+ // The models idiom: a typed replacement wins over a stale checked box.+ clearing.feishu.appSecret = "replacement-secret";+ const typed = formToPut(clearing, true);+ expect(typed.ok && typed.channel === "feishu" && typed.body).toEqual({+ appId: "cli_abc",+ appSecret: "replacement-secret",+ baseDomain: "https://open.larksuite.com",+ });+ // Without a stored secret there is nothing to clear: the flag never reaches the body.+ const nothingStored = emptyMessagingForm();+ nothingStored.feishu.appId = "cli_x";+ nothingStored.feishu.clearSecret = true;+ expect(formToPut(nothingStored, false)).toEqual({+ ok: false,+ errors: { appSecret: "required" },+ });+ });++ it("defaults a blank domain and rejects a non-http(s) one", () => {+ const form = emptyMessagingForm();+ form.feishu = { appId: "cli_x", appSecret: "s", baseDomain: " ", clearSecret: false };+ const blankDomain = formToPut(form, false);+ expect(blankDomain.ok && blankDomain.channel === "feishu" && blankDomain.body.baseDomain).toBe(+ FEISHU_DEFAULT_DOMAIN,+ );+ form.feishu.baseDomain = "open.feishu.cn";+ expect(formToPut(form, false)).toEqual({ ok: false, errors: { baseDomain: "url_invalid" } });+ form.feishu.baseDomain = "ftp://open.feishu.cn";+ expect(formToPut(form, false).ok).toBe(false);+ });+});++describe("formToPut (telegram)", () => {+ it("submits only the token, trimmed; blank keeps the stored one", () => {+ const form = emptyMessagingForm("telegram");+ form.telegram.botToken = " 7000000001:secret-token-AAAA ";+ expect(formToPut(form, false)).toEqual({+ ok: true,+ channel: "telegram",+ body: { botToken: "7000000001:secret-token-AAAA" },+ });+ // With a stored token an empty field means "keep it": the body omits the token.+ form.telegram.botToken = "";+ expect(formToPut(form, true)).toEqual({ ok: true, channel: "telegram", body: {} });+ // A first bind must carry one.+ expect(formToPut(form, false)).toEqual({ ok: false, errors: { botToken: "required" } });+ });++ it("maps the checked clear box to clearBotToken, with a typed token winning over it", () => {+ const form = emptyMessagingForm("telegram");+ form.telegram.clearToken = true;+ expect(formToPut(form, true)).toEqual({+ ok: true,+ channel: "telegram",+ body: { clearBotToken: true },+ });+ form.telegram.botToken = "7000000001:replacement-token";+ const typed = formToPut(form, true);+ expect(typed.ok && typed.channel === "telegram" && typed.body).toEqual({+ botToken: "7000000001:replacement-token",+ });+ });++ it("rejects a token whose bot id cannot be read (the server's identity rule, mirrored)", () => {+ const form = emptyMessagingForm("telegram");+ form.telegram.botToken = "not-a-token";+ expect(formToPut(form, false)).toEqual({ ok: false, errors: { botToken: "token_invalid" } });+ form.telegram.botToken = "abc:def-ghi-jkl";+ expect(formToPut(form, true).ok).toBe(false);+ });++ it("never validates the unselected channel's fields", () => {+ // A blank Feishu form must not block a Telegram submit, and vice versa.+ const form = emptyMessagingForm("telegram");+ form.telegram.botToken = "7000000001:secret-token-AAAA";+ expect(formToPut(form, false).ok).toBe(true);+ const feishuSide = emptyMessagingForm("feishu");+ feishuSide.feishu = {+ appId: "cli_x",+ appSecret: "s",+ baseDomain: FEISHU_DEFAULT_DOMAIN,+ clearSecret: false,+ };+ feishuSide.telegram.botToken = "garbage";+ expect(formToPut(feishuSide, false).ok).toBe(true);+ });+});++describe("formToTest", () => {+ it("carries only the selected channel's filled-in fields, so blanks fall back to the stored binding server-side", () => {+ // The fresh form prefills the default domain, and a prefilled value is a filled value.+ expect(formToTest(emptyMessagingForm())).toEqual({+ channel: "feishu",+ body: { baseDomain: FEISHU_DEFAULT_DOMAIN },+ });+ const blanked = emptyMessagingForm();+ blanked.feishu.baseDomain = "";+ expect(formToTest(blanked)).toEqual({ channel: "feishu", body: {} });+ const feishu = emptyMessagingForm();+ feishu.feishu = {+ appId: " cli_x ",+ appSecret: "s",+ baseDomain: FEISHU_DEFAULT_DOMAIN,+ clearSecret: false,+ };+ expect(formToTest(feishu)).toEqual({+ channel: "feishu",+ body: { appId: "cli_x", appSecret: "s", baseDomain: FEISHU_DEFAULT_DOMAIN },+ });+ const telegram = emptyMessagingForm("telegram");+ expect(formToTest(telegram)).toEqual({ channel: "telegram", body: {} });+ telegram.telegram.botToken = " 7000000001:tok-en-AAAA ";+ expect(formToTest(telegram)).toEqual({+ channel: "telegram",+ body: { botToken: "7000000001:tok-en-AAAA" },+ });+ });+});++describe("formDirty / formTestable", () => {+ it("marks the selected channel dirty on any field change; a typed secret and a checked clear box count", () => {+ const baseline = bindingsToForm([STORED_FEISHU]);+ expect(formDirty(bindingsToForm([STORED_FEISHU]), baseline)).toBe(false);+ const edited = bindingsToForm([STORED_FEISHU]);+ edited.feishu.appId = "cli_other";+ expect(formDirty(edited, baseline)).toBe(true);+ const secret = bindingsToForm([STORED_FEISHU]);+ secret.feishu.appSecret = "typed";+ expect(formDirty(secret, baseline)).toBe(true);+ const clearing = bindingsToForm([STORED_FEISHU]);+ clearing.feishu.clearSecret = true;+ expect(formDirty(clearing, baseline)).toBe(true);+ // Telegram: the token field always loads empty, so typed-token / checked-clear are the dirty signals.+ const tgBaseline = bindingsToForm([STORED_TELEGRAM]);+ const tg = bindingsToForm([STORED_TELEGRAM]);+ expect(formDirty(tg, tgBaseline)).toBe(false);+ tg.telegram.botToken = "7000000001:new";+ expect(formDirty(tg, tgBaseline)).toBe(true);+ tg.telegram.botToken = "";+ tg.telegram.clearToken = true;+ expect(formDirty(tg, tgBaseline)).toBe(true);+ });++ it("allows the probe when the selected channel has a testable draft or a stored secret", () => {+ // Feishu drafts need both halves of the credential pair.+ expect(formTestable(emptyMessagingForm(), false)).toBe(false);+ const half = emptyMessagingForm();+ half.feishu.appId = "cli_x";+ expect(formTestable(half, false)).toBe(false);+ half.feishu.appSecret = "s";+ expect(formTestable(half, false)).toBe(true);+ // A stored secret makes the stored config testable without retyping anything.+ expect(formTestable(emptyMessagingForm(), true)).toBe(true);+ // Telegram: the token is the whole credential.+ expect(formTestable(emptyMessagingForm("telegram"), false)).toBe(false);+ expect(formTestable(emptyMessagingForm("telegram"), true)).toBe(true);+ const typed = emptyMessagingForm("telegram");+ typed.telegram.botToken = "7000000001:tok";+ expect(formTestable(typed, false)).toBe(true);+ });+});diff --git a/packages/web/test/session-row-menu.test.ts b/packages/web/test/session-row-menu.test.tsindex 512b6ed6..bff487ec 100644--- a/packages/web/test/session-row-menu.test.ts+++ b/packages/web/test/session-row-menu.test.ts@@ -2,12 +2,13 @@* session-row-menu.tsx unit tests: which actions each of a Session row's two surfaces* offers, and how each one labels itself.*- * The split is the point of the change and the thing most likely to be undone by- * accident, so it is pinned by value rather than by shape: **hover gives archive and- * delete and nothing else** — the affordance every release up to v0.2.2 shipped — while- * the right-click menu carries the full set. Rename in particular must stay in the- * context menu: `design/specs/06-PROTOTYPE.md` requires every Session to support- * 重命名、归档与删除, and the pared-back hover pair alone would not satisfy that.+ * The split is the point and the thing most likely to be undone by accident, so it is+ * pinned by value rather than by shape: **hover gives archive plus the ellipsis "more"+ * button and nothing else** — the ellipsis opens the context menu anchored at itself, so+ * every menu action (delete and the messaging binding included) is one visible click+ * away — while the right-click menu carries the full set. Rename in particular must stay+ * in the context menu: every Session must remain renamable, archivable and deletable, and+ * the pared-back hover affordance alone would not satisfy that.** vitest runs node-only here (`environment: "node"`, no jsdom), so these assert against* the exported manifests and label helpers rather than a rendered DOM@@ -28,6 +29,7 @@ import {sessionRowMenuItem,} from "../src/components/ui/session-row-menu";import type { SessionRowAction } from "../src/components/ui/session-row-menu";+import { MESSAGING_ICON } from "../src/components/ui/icons";import { setActiveStrings, zh } from "../src/lib/strings";import { en } from "../src/lib/strings-en";@@ -37,26 +39,33 @@ afterEach(() => setActiveStrings(zh));const RESTING = { archived: false, pinned: false };describe("HOVER_ROW_ACTIONS", () => {- it("is the released archive + delete pair, in that order, and nothing more", () => {- expect([...HOVER_ROW_ACTIONS]).toEqual(["archive", "delete"]);+ it("is archive alone — the ellipsis beside it is the menu's pointer entry, not an action", () => {+ expect([...HOVER_ROW_ACTIONS]).toEqual(["archive"]);});- it("does not carry rename or pin — those moved to the context menu", () => {- expect(HOVER_ROW_ACTIONS as readonly string[]).not.toContain("rename");- expect(HOVER_ROW_ACTIONS as readonly string[]).not.toContain("pin");+ it("does not carry rename, pin, delete or the messaging binding — those live in the menu", () => {+ for (const action of ["rename", "pin", "delete", "messaging"]) {+ expect(HOVER_ROW_ACTIONS as readonly string[]).not.toContain(action);+ }});});describe("contextMenuActions", () => {it("carries the whole set when the row can be pinned", () => {- expect([...contextMenuActions(true)]).toEqual(["pin", "rename", "archive", "delete"]);+ expect([...contextMenuActions(true)]).toEqual([+ "pin",+ "rename",+ "messaging",+ "archive",+ "delete",+ ]);});it("drops only pin on rows where pinning cannot reorder anything (folder rows)", () => {- expect([...contextMenuActions(false)]).toEqual(["rename", "archive", "delete"]);+ expect([...contextMenuActions(false)]).toEqual(["rename", "messaging", "archive", "delete"]);});- it("is a superset of the hover pair, so nothing is reachable by hover alone", () => {+ it("is a superset of the hover actions, so nothing is reachable by hover alone", () => {for (const canPin of [true, false]) {for (const action of HOVER_ROW_ACTIONS) {expect(contextMenuActions(canPin)).toContain(action);@@ -64,7 +73,7 @@ describe("contextMenuActions", () => {}});- it("keeps rename reachable in every state (design/specs/06-PROTOTYPE.md: 重命名、归档与删除)", () => {+ it("keeps rename reachable in every state", () => {expect(contextMenuActions(true)).toContain("rename");expect(contextMenuActions(false)).toContain("rename");});@@ -92,11 +101,19 @@ describe("the hover buttons' CSS contract", () => {// focus-within, and the two conditions have to agree or the slot goes blank.expect(source).not.toContain("focus-visible:opacity-100");});++ it("renders the ellipsis as a labelled menu trigger anchored at its own box", () => {+ // The menu's discoverable pointer entry: a real button that reports it opens a menu+ // and anchors the panel at its own rect (not the pointer position).+ expect(source).toContain('aria-haspopup="menu"');+ expect(source).toContain("ELLIPSIS_ICON");+ expect(source).toContain("getBoundingClientRect");+ });});describe("sessionRowMenuItem", () => {it("gives every action a label, a glyph, and only delete the destructive treatment", () => {- const all: SessionRowAction[] = ["pin", "rename", "archive", "delete"];+ const all: SessionRowAction[] = ["pin", "rename", "messaging", "archive", "delete"];for (const action of all) {const item = sessionRowMenuItem(action, RESTING);expect(item.label).toBeTruthy();@@ -106,11 +123,11 @@ describe("sessionRowMenuItem", () => {});it("gives the actions distinct glyphs, so a row is not read by its label alone", () => {- const icons = (["pin", "rename", "archive", "delete"] as SessionRowAction[]).map(+ const icons = (["pin", "rename", "messaging", "archive", "delete"] as SessionRowAction[]).map((a) => sessionRowMenuItem(a, RESTING).icon,);expect(new Set(icons).size).toBe(icons.length);- expect(icons).toEqual([PIN_ICON, PENCIL_ICON, ARCHIVE_ICON, TRASH_ICON]);+ expect(icons).toEqual([PIN_ICON, PENCIL_ICON, MESSAGING_ICON, ARCHIVE_ICON, TRASH_ICON]);});it("flips archive's label and glyph on an archived row", () => {@@ -139,6 +156,7 @@ describe("sessionRowMenuItem", () => {expect(sessionRowMenuItem("archive", RESTING).label).toBe(en.chat.archiveSession);expect(sessionRowMenuItem("delete", RESTING).label).toBe(en.chat.deleteSession);expect(sessionRowMenuItem("rename", RESTING).label).toBe(en.chat.renameSession);+ expect(sessionRowMenuItem("messaging", RESTING).label).toBe(en.messaging.bindAction);// The hover buttons are icon-only, so their label IS their accessible name: an English// row must not fall back to the zh catalog and leave a Chinese name on the button.for (const action of HOVER_ROW_ACTIONS) {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex f27b8b66..48122b08 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -145,7 +145,7 @@ importers:version: file:packages/core([email protected])([email protected])'@prismshadow/penguin-server':specifier: workspace:*- version: link:../server+ version: file:packages/server([email protected])'@types/node':specifier: ^24.0.0version: 24.13.3@@ -274,6 +274,9 @@ importers:'@hono/node-server':specifier: '>=2.0.5'version: 2.0.12([email protected])+ '@larksuiteoapi/node-sdk':+ specifier: ^1.73.0'@prismshadow/penguin-core':specifier: workspace:*version: file:packages/core([email protected])([email protected])@@ -392,7 +395,7 @@ importers:version: 1.61.1'@prismshadow/penguin-server':specifier: workspace:*- version: link:../server+ version: file:packages/server([email protected])'@tailwindcss/vite':specifier: ^4.1.0version: 4.3.2([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))@@ -891,6 +894,9 @@ packages:'@jridgewell/[email protected]':resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}+ '@larksuiteoapi/[email protected]':+ resolution: {integrity: sha512-gs4EiupJ6RdYAEJGtuYrCVsB7wSMBwtUDK+ilpmOHD6RTvbtciW6AWciQO9coOQVuBZfh7hvAi25dPfCsny/nA==}+'@malept/[email protected]':resolution: {integrity: sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==}engines: {node: '>= 12.13.0'}@@ -1575,6 +1581,10 @@ packages:engines: {node: '>=0.4.0'}hasBin: true+ resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==}+ engines: {node: '>= 6.0.0'}+resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==}engines: {node: '>= 14'}@@ -1648,6 +1658,9 @@ packages:resolution: {integrity: sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==}+ resolution: {integrity: sha512-ht/iuYZXEjFxLH/Hkezgd7m6JKlHHXEUSneaDz8uZe1Gj5QZtCnpyDsckvAiEnT89OEbCLmnte4R4sn7P0EKFw==}+resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==}@@ -2170,6 +2183,15 @@ packages:resolution: {integrity: sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==}+ resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==}+ engines: {node: '>=4.0'}+ peerDependencies:+ debug: '*'+ peerDependenciesMeta:+ debug:+ optional: true+resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==}engines: {node: '>= 6'}@@ -2361,6 +2383,10 @@ packages:resolution: {integrity: sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg==}engines: {node: '>=10.19.0'}+ resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==}+ engines: {node: '>= 6'}+resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==}engines: {node: '>= 14'}@@ -2583,10 +2609,19 @@ packages:resolution: {integrity: sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==}+ resolution: {integrity: sha512-AupTIzdLQxJS5wIYUQlgGyk2XRTfGXA+MCghDHqZk0pzUNYvd3EESS6dkChNauNYVIutcb0dfHw1ri9Q1yPV8Q==}+resolution: {integrity: sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==}deprecated: This package is deprecated. Use require('node:util').isDeepStrictEqual instead.+ resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==}++ resolution: {integrity: sha512-AZV+GsS/6ckvPOVQPXSiFFacKvKB4kOQu6ynt9wz0F3LO4R9Ij4K1ddYsIytDpSgLz88JHd9P+oaLeej5/Sl7Q==}+resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==}@@ -3065,6 +3100,10 @@ packages:resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==}engines: {node: '>= 0.10'}+ resolution: {integrity: sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==}+ engines: {node: '>=10'}+resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==}@@ -4434,6 +4473,21 @@ snapshots:'@jridgewell/resolve-uri': 3.1.2'@jridgewell/sourcemap-codec': 1.5.5+ dependencies:+ lodash.identity: 3.0.0+ lodash.merge: 4.6.2+ lodash.pickby: 4.6.0+ protobufjs: 7.6.5+ qs: 6.15.2+ ws: 8.21.0+ transitivePeerDependencies:+ - bufferutil+ - debug+ - supports-color+ - utf-8-validate+'@malept/[email protected]':dependencies:cross-spawn: 7.0.6@@ -4549,6 +4603,7 @@ snapshots:transitivePeerDependencies:- '@modelcontextprotocol/sdk'- bufferutil+ - debug- supports-color- utf-8-validate- ws@@ -4605,6 +4660,7 @@ snapshots:'@prismshadow/penguin-server@file:packages/server([email protected])':dependencies:'@hono/node-server': 2.0.12([email protected])'@prismshadow/penguin-core': file:packages/core([email protected])([email protected])'@prismshadow/penguin-skills': file:packages/skills'@xterm/headless': 5.5.0@@ -4620,6 +4676,7 @@ snapshots:transitivePeerDependencies:- '@modelcontextprotocol/sdk'- bufferutil+ - debug- supports-color- utf-8-validate- zod@@ -4627,6 +4684,7 @@ snapshots:'@prismshadow/penguin-server@file:packages/server([email protected])([email protected])':dependencies:'@hono/node-server': 2.0.12([email protected])'@prismshadow/penguin-core': file:packages/core([email protected])([email protected])([email protected])'@prismshadow/penguin-skills': file:packages/skills'@xterm/headless': 5.5.0@@ -4642,6 +4700,7 @@ snapshots:transitivePeerDependencies:- '@modelcontextprotocol/sdk'- bufferutil+ - debug- supports-color- utf-8-validate- zod@@ -5260,6 +5319,12 @@ snapshots:+ dependencies:+ debug: 4.4.3([email protected])+ transitivePeerDependencies:+ - supports-color+@@ -5363,6 +5428,16 @@ snapshots:+ dependencies:+ follow-redirects: 1.16.0([email protected]([email protected]))+ form-data: 4.0.6+ https-proxy-agent: 5.0.1([email protected])+ proxy-from-env: 2.1.0+ transitivePeerDependencies:+ - debug+ - supports-color+@@ -5965,6 +6040,10 @@ snapshots:mlly: 1.8.2rollup: 4.62.0+ optionalDependencies:+ debug: 4.4.3([email protected])+dependencies:asynckit: 0.4.0@@ -6264,6 +6343,13 @@ snapshots:quick-lru: 5.1.1resolve-alpn: 1.2.1+ dependencies:+ agent-base: 6.0.2([email protected])+ debug: 4.4.3([email protected])+ transitivePeerDependencies:+ - supports-color+dependencies:agent-base: 7.1.4@@ -6437,8 +6523,14 @@ snapshots:+ [email protected]: {}++ [email protected]: {}++ [email protected]: {}+@@ -7094,6 +7186,8 @@ snapshots:forwarded: 0.2.0ipaddr.js: 1.9.1+ [email protected]: {}+dependencies:end-of-stream: 1.4.5