Skip to content

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

A channel spec for the messaging HTTP surface (#525)

Yaowei Zheng0ec0327731c9
diff --git a/changelog/unreleased/2026-08-27-messaging-channel-spec.md b/changelog/unreleased/2026-08-27-messaging-channel-spec.md
new file mode 100644
index 00000000..6fc07694
--- /dev/null
+++ b/changelog/unreleased/2026-08-27-messaging-channel-spec.md
@@ -0,0 +1,43 @@
+# The messaging HTTP surface stops being written three times
+
+- **Date:** 2026-08-27
+- **Type:** refactor
+- **Scope:** `server`
+
+[中文版](2026-08-27-messaging-channel-spec.zh.md)
+
+`runtime/messaging/connector.ts` already gave the runtime a channel seam: a connector owns its
+wire protocol and hands the bridge a channel-neutral view. The HTTP layer had no such seam, so
+each of its six endpoints was written once per channel and each new saved field was written
+three more times — the three delivery preferences that arrived in one release cost nine
+declarations, nine reads and nine spreads between them.
+
+A `MessagingChannelSpec` now carries what a channel actually differs in, and the endpoints that
+differ in nothing else are written once.
+
+## Details
+
+- `http/routes/messaging-channels.ts` holds the spec and the pieces the routes share: the
+ common half of a binding's wire shape, the masked-secret projection, the delivery-preference
+ patch read off a PUT body, and `resolveSecret` — the credential ladder all three channels
+ climb, whose four steps (a typed credential wins, the clear flag is refused while enabled,
+ the stored one carries over, a first bind with none is a 400) were previously stated three
+ times and could have drifted.
+- Four endpoints per channel — the read, the state toggle, the delete and the test message —
+ are registered from the spec table. What varied across the twelve copies was a channel
+ literal and a `<channel>_` error-code prefix, so the spec carries a display label and the
+ codes are derived.
+- The PUT and the credential test stay hand-written per channel, deliberately. Their shape is
+ shared and now uses the ladder, but the order their inputs are validated in and how an
+ account identity falls out of a credential genuinely differ — Telegram derives its bot id
+ from the token itself — and a table would have hidden that difference rather than removed it.
+- `MessagingBindingCommon` and `MessagingDeliveryPatch` do the same for the wire types. QQ
+ re-declares the three preference fields, unchanged in type, because each costs something
+ different there and the passive-reply budget is what a reader setting one needs to know; the
+ compiler enforces that a redeclaration can only add documentation.
+- The spec is not merged with the connectors' config parsers, which run in the opposite
+ direction: a connector reads a stored document to build a client, this reads a request to
+ decide what to store. They share knowledge of a document's shape and nothing else.
+
+No endpoint, status code, error code or response body changes: the whole messaging test suite
+passes unmodified.
diff --git a/changelog/unreleased/2026-08-27-messaging-channel-spec.zh.md b/changelog/unreleased/2026-08-27-messaging-channel-spec.zh.md
new file mode 100644
index 00000000..20d3a567
--- /dev/null
+++ b/changelog/unreleased/2026-08-27-messaging-channel-spec.zh.md
@@ -0,0 +1,21 @@
+# 消息通道的 HTTP 层不再写三遍
+
+- **Date:** 2026-08-27
+- **Type:** refactor
+- **Scope:** `server`
+
+[English](2026-08-27-messaging-channel-spec.md)
+
+`runtime/messaging/connector.ts` 早已为运行时提供了渠道接缝:连接器自己拥有线路协议,交给桥接的是与渠道无关的视图。HTTP 层没有这样一层,于是它的六个端点每个渠道各写一遍,每新增一个保存字段就再多写三遍——同一个版本里到来的三个投递偏好,合起来花掉了九处声明、九处读取和九处展开。
+
+现在由 `MessagingChannelSpec` 承载渠道之间真正的差异,而除此之外别无不同的端点只写一次。
+
+## 细节
+
+- `http/routes/messaging-channels.ts` 承载该 spec 以及路由共用的部件:绑定线路形状中与渠道无关的那一半、脱敏后的密钥投影、从 PUT body 读出的投递偏好补丁,以及 `resolveSecret`——三个渠道共同攀爬的那道凭据阶梯。它的四步(键入的凭据优先、启用状态下拒绝清除、否则沿用已存、首次绑定无凭据则 400)此前被陈述了三遍,本可以各自漂移。
+- 每个渠道的四个端点——读取、状态开关、删除、测试消息——改为从 spec 表注册。这十二份副本之间的差异只有渠道字面量和 `<channel>_` 错误码前缀,因此 spec 携带一个展示名,错误码由它推导。
+- PUT 与凭据测试**刻意**保留为每渠道手写。它们的骨架是共享的,现在也走同一道阶梯,但输入的校验顺序、以及账号身份如何从凭据中得出,确实各不相同——Telegram 的 bot id 就是从 token 本身推导的——用一张表会把这个差异藏起来,而不是消除它。
+- 线路类型这一侧由 `MessagingBindingCommon` 与 `MessagingDeliveryPatch` 做同样的事。QQ 重新声明了那三个偏好字段(类型不变),因为它们在该平台上各自的代价不同,而被动回复额度正是设置它们的人需要知道的;编译器保证重新声明只能增加文档、不能改变契约。
+- 该 spec 不与连接器的配置解析合并:两者方向相反——连接器读取**已存文档**来构造客户端,而这里读取**请求**来决定存什么。它们只共享对文档形状的认知,仅此而已。
+
+端点、状态码、错误码与响应体均无变化:整套消息测试未经修改即全部通过。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 7e021d2a..53467bd8 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -1703,18 +1703,24 @@ export interface MessagingRuntimeStatus {
lastConnectionError?: { at: string; detail: string };
}
-/** The stored Feishu config, secret masked (plaintext never leaves the server). */
-export interface FeishuBindingInfo {
- channel: "feishu";
+/**
+ * What a messaging binding carries whatever channel it is: the connection intent, the three
+ * delivery preferences, whether a chat is known, and the row's identity and timestamps.
+ *
+ * Split out because this is the half that grows. Three delivery preferences arrived in one
+ * release, and each would otherwise have been written into three interfaces — the credential
+ * slice is the only thing a channel genuinely differs in, and it is what stays per-channel.
+ *
+ * `channel` is NOT here: a discriminated union discriminates on a literal the member itself
+ * declares, so each interface keeps its own.
+ *
+ * A channel may RE-DECLARE a field below when it has more to say about it — QQ does, for all
+ * three preferences, because the platform's passive-reply budget and its expiring window
+ * change what setting one costs there. The re-declared type must be identical, which the
+ * compiler enforces, so the redeclaration can only add documentation and never a contract.
+ */
+export interface MessagingBindingCommon {
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;
/**
@@ -1738,18 +1744,30 @@ export interface FeishuBindingInfo {
*/
renderMarkdown: 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.
+ * Whether an inbound 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 Feishu config, secret masked (plaintext never leaves the server). */
+export interface FeishuBindingInfo extends MessagingBindingCommon {
+ channel: "feishu";
+ 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;
+}
+
/** The stored Telegram config, token masked (plaintext never leaves the server). */
-export interface TelegramBindingInfo {
+export interface TelegramBindingInfo extends MessagingBindingCommon {
channel: "telegram";
- sessionId: string;
/** The numeric bot id (the token's half before the colon) — the channel-scoped account identity, never secret. */
botId: string;
/**
@@ -1758,41 +1776,16 @@ export interface TelegramBindingInfo {
* 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;
- /**
- * Send each non-blank line of a relayed assistant reply as its own message instead of one
- * message per reply. Off by default; off is the original one-message-per-reply behaviour.
- */
- linePerMessage: boolean;
- /**
- * Relay only the LAST completed assistant message of a run, delivered when the run ends,
- * instead of mirroring each completed message as it completes. Off by default; off is the
- * original every-message behaviour. Independent of `linePerMessage`, which then applies to
- * that one final message. The approval notice is not a reply and is unaffected.
- */
- finalReplyOnly: boolean;
- /**
- * Render a relayed reply's Markdown in this channel's own markup instead of sending its
- * characters as written. ON by default. Each channel shows what it can — Telegram has no
- * headings, lists or tables, QQ has no code or tables, Feishu has all of them — and a
- * rendering the channel refuses falls back to the plain source, so this can cost
- * formatting and never a message.
- */
- renderMarkdown: 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;
}
-/** The stored QQ config, secret masked (plaintext never leaves the server). */
-export interface QQBindingInfo {
+/**
+ * The stored QQ config, secret masked (plaintext never leaves the server).
+ *
+ * The three preference fields are re-declared unchanged: every one of them costs something
+ * different here, and the platform's reply budget is what a reader setting one needs to know.
+ */
+export interface QQBindingInfo extends MessagingBindingCommon {
channel: "qq";
- sessionId: string;
/** The bot's App ID — the channel-scoped account identity, never secret. */
appId: string;
/**
@@ -1801,8 +1794,6 @@ export interface QQBindingInfo {
* enabled until one is saved.
*/
appSecretMasked?: 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;
/**
* Send each non-blank line of a relayed assistant reply as its own message instead of one
* message per reply. Off by default. On QQ the split is additionally capped at the
@@ -1811,10 +1802,8 @@ export interface QQBindingInfo {
*/
linePerMessage: boolean;
/**
- * Relay only the LAST completed assistant message of a run, delivered when the run ends,
- * instead of mirroring each completed message as it completes. Off by default; off is the
- * original every-message behaviour. Independent of `linePerMessage`, which then applies to
- * that one final message. The approval notice is not a reply and is unaffected.
+ * Relay only the LAST completed assistant message of a run, delivered when the run ends.
+ * Off by default.
*
* On QQ it cuts both ways, which is worth knowing before setting it here. It spends the
* least of the platform's passive-reply budget a run can spend — one message, where an
@@ -1825,22 +1814,19 @@ export interface QQBindingInfo {
*/
finalReplyOnly: boolean;
/**
- * Render a relayed reply's Markdown in this channel's own markup instead of sending its
- * characters as written. ON by default. QQ's own subset is the widest for prose and the
- * narrowest for code: headings, lists, blockquotes and rules render, while inline code,
- * fenced code and tables have no syntax at all here — a code block arrives as plain
- * escaped lines. A rendering the platform refuses falls back to the plain source, at the
- * cost of one more slot from the passive-reply budget.
+ * Render a relayed reply's Markdown in this channel's own markup. ON by default. QQ's own
+ * subset is the widest for prose and the narrowest for code: headings, lists, blockquotes
+ * and rules render, while inline code, fenced code and tables have no syntax at all here —
+ * a code block arrives as plain escaped lines. A rendering the platform refuses falls back
+ * to the plain source, at the cost of one more slot from the passive-reply budget.
*/
renderMarkdown: boolean;
/**
- * Whether an inbound QQ chat is known (the bot has been messaged at least once).
- * Weaker than it looks on this channel: QQ accepts only replies to a recent message, so a
- * known chat is necessary but not sufficient for anything to be deliverable right now.
+ * Whether an inbound QQ chat is known (the bot has been messaged at least once). Weaker
+ * than it looks on this channel: QQ accepts only replies to a recent message, so a known
+ * chat is necessary but not sufficient for anything to be deliverable right now.
*/
lastChatKnown: boolean;
- createdAt: string;
- updatedAt: string;
}
/** A Session's saved config for one messaging channel (`channel` is the discriminant). */
@@ -1885,7 +1871,23 @@ export interface QQBindingResponse {
* (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 {
+/**
+ * The delivery preferences any channel's PUT may set. Each is optional and each behaves the
+ * same way on every channel: an omitted field keeps the stored value, so a client that knows
+ * about one preference can save it without having to send the others back. Their meanings are
+ * on {@link MessagingBindingCommon}, and where a channel charges differently for one, on that
+ * channel's own `*BindingInfo`.
+ *
+ * The defaults a binding created without them starts from: `linePerMessage` off,
+ * `finalReplyOnly` off, `renderMarkdown` ON.
+ */
+export interface MessagingDeliveryPatch {
+ linePerMessage?: boolean;
+ finalReplyOnly?: boolean;
+ renderMarkdown?: boolean;
+}
+
+export interface FeishuBindingPutRequest extends MessagingDeliveryPatch {
appId: string;
/** Omitted or blank keeps the stored secret (the masked value never round-trips). */
appSecret?: string;
@@ -1896,21 +1898,6 @@ export interface FeishuBindingPutRequest {
* it). Refused with 409 `messaging_disable_before_clear` while the binding is enabled.
*/
clearAppSecret?: boolean;
- /**
- * Delivery preference (see `FeishuBindingInfo.linePerMessage`). Omitted keeps the stored
- * value; a binding created without it starts with it off.
- */
- linePerMessage?: boolean;
- /**
- * Delivery preference (see `FeishuBindingInfo.finalReplyOnly`). Omitted keeps the stored
- * value; a binding created without it starts with it off.
- */
- finalReplyOnly?: boolean;
- /**
- * Delivery preference (see `FeishuBindingInfo.renderMarkdown`). Omitted keeps the stored
- * value; a binding created without it starts with it ON.
- */
- renderMarkdown?: boolean;
}
/**
@@ -1919,7 +1906,7 @@ export interface FeishuBindingPutRequest {
* POST …/state). Saving never conflicts across Sessions: the same bot may sit saved on
* several, and only enabling it is exclusive.
*/
-export interface TelegramBindingPutRequest {
+export interface TelegramBindingPutRequest extends MessagingDeliveryPatch {
/** Omitted or blank keeps the stored token (the masked value never round-trips). */
botToken?: string;
/**
@@ -1928,21 +1915,6 @@ export interface TelegramBindingPutRequest {
* `messaging_disable_before_clear` while the binding is enabled.
*/
clearBotToken?: boolean;
- /**
- * Delivery preference (see `TelegramBindingInfo.linePerMessage`). Omitted keeps the stored
- * value; a binding created without it starts with it off.
- */
- linePerMessage?: boolean;
- /**
- * Delivery preference (see `TelegramBindingInfo.finalReplyOnly`). Omitted keeps the stored
- * value; a binding created without it starts with it off.
- */
- finalReplyOnly?: boolean;
- /**
- * Delivery preference (see `TelegramBindingInfo.renderMarkdown`). Omitted keeps the stored
- * value; a binding created without it starts with it ON.
- */
- renderMarkdown?: boolean;
}
/**
@@ -1951,7 +1923,7 @@ export interface TelegramBindingPutRequest {
* is POST …/state). The App ID is the account identity, so changing it rebinds the row to
* a different bot and drops the remembered chat.
*/
-export interface QQBindingPutRequest {
+export interface QQBindingPutRequest extends MessagingDeliveryPatch {
appId: string;
/** Omitted or blank keeps the stored secret (the masked value never round-trips). */
appSecret?: string;
@@ -1960,21 +1932,6 @@ export interface QQBindingPutRequest {
* it). Refused with 409 `messaging_disable_before_clear` while the binding is enabled.
*/
clearAppSecret?: boolean;
- /**
- * Delivery preference (see `QQBindingInfo.linePerMessage`). Omitted keeps the stored
- * value; a binding created without it starts with it off.
- */
- linePerMessage?: boolean;
- /**
- * Delivery preference (see `QQBindingInfo.finalReplyOnly`). Omitted keeps the stored
- * value; a binding created without it starts with it off.
- */
- finalReplyOnly?: boolean;
- /**
- * Delivery preference (see `QQBindingInfo.renderMarkdown`). Omitted keeps the stored
- * value; a binding created without it starts with it ON.
- */
- renderMarkdown?: boolean;
}
/**
diff --git a/packages/server/src/http/routes/messaging-channels.ts b/packages/server/src/http/routes/messaging-channels.ts
new file mode 100644
index 00000000..b012a705
--- /dev/null
+++ b/packages/server/src/http/routes/messaging-channels.ts
@@ -0,0 +1,165 @@
+/**
+ * The channel-shaped half of the messaging HTTP surface, so the routes beside it can stop
+ * asking which channel they are serving.
+ *
+ * `runtime/messaging/connector.ts` already does this for the RUNTIME: a connector owns its
+ * wire protocol and hands the bridge a channel-neutral view. The HTTP layer had no such seam,
+ * so every one of its six endpoints was written three times and each new saved field was
+ * written three more. What differs between channels here is small and enumerable — which
+ * credential field a PUT reads, how an account identity is derived from it, and how a stored
+ * row masks into its wire shape — and that is what a {@link MessagingChannelSpec} carries.
+ *
+ * **This is not the connector's config parser, and must not be merged with it.** The two run
+ * in opposite directions: a connector reads a STORED document to build a client, while this
+ * reads a REQUEST to decide what to store, and rejects what the connector would only find
+ * malformed later. They share knowledge of a document's shape and nothing else, and collapsing
+ * them would put request validation inside the runtime.
+ *
+ * What deliberately stays hand-written in `messaging.ts`: each channel's PUT and its
+ * credential test. Their SHAPE is shared — `resolveSecret` below is the ladder all three climb
+ * — but the order their inputs are validated in, and how an account id falls out of a
+ * credential, genuinely differ, and a table that hid that would only move the difference
+ * somewhere harder to read.
+ */
+import { HttpError } from "../errors.js";
+import { optionalBoolean } from "../validate.js";
+import { maskApiKey } from "../../services/project-config-service.js";
+import type { MessagingBindingRow } from "../../db/repos/messaging-bindings.js";
+import type { MessagingChannel } from "../../runtime/messaging/connector.js";
+import type {
+ MessagingBindingCommon,
+ MessagingBindingInfo,
+ MessagingDeliveryPatch,
+} from "../../api/types.js";
+
+/**
+ * One channel's contribution to the shared HTTP surface.
+ *
+ * Everything a channel does NOT appear in is the point: the read, the state toggle, the
+ * delete and the test message are written once against this interface.
+ */
+export interface MessagingChannelSpec {
+ readonly channel: MessagingChannel;
+ /**
+ * The channel's name as a person writes it — "Feishu", "Telegram", "QQ". It appears in the
+ * shared endpoints' error messages, which name the channel a caller is asking about; the
+ * `channel` discriminant above is the machine-facing half and is not capitalised.
+ */
+ readonly label: string;
+ /**
+ * The stored credential, read tolerantly — `""` when none is stored, which is what the
+ * enable gate and the masking below both key on. A malformed document reads as absent
+ * rather than throwing: the row still has an identity and a state worth reporting, and the
+ * connector is where an unusable document is diagnosed.
+ */
+ storedSecret(row: MessagingBindingRow): string;
+ /**
+ * The 400 code for "this binding has no credential". Channel-specific because the word is:
+ * a Feishu or QQ binding is missing a *secret*, a Telegram one a *token*, and the code is
+ * what a client branches on.
+ */
+ readonly secretRequiredCode: string;
+ /** One stored row as its wire shape, secret masked. */
+ toInfo(row: MessagingBindingRow): MessagingBindingInfo;
+}
+
+/**
+ * The half of a binding's wire shape that has nothing to do with which channel it is.
+ *
+ * Written once here rather than spelled into each channel's projection, for the reason
+ * {@link MessagingBindingCommon} exists: this is the half that grows, and it grew by three
+ * fields in one release.
+ */
+export function commonBindingFields(row: MessagingBindingRow): MessagingBindingCommon {
+ return {
+ sessionId: row.sessionId,
+ enabled: row.enabled,
+ linePerMessage: row.linePerMessage,
+ finalReplyOnly: row.finalReplyOnly,
+ renderMarkdown: row.renderMarkdown,
+ lastChatKnown: row.lastChatId !== null,
+ createdAt: row.createdAt,
+ updatedAt: row.updatedAt,
+ };
+}
+
+/**
+ * A stored secret as it may leave the server: masked, or absent entirely.
+ *
+ * The absence is load-bearing rather than tidiness — the editor renders "not configured" from
+ * the field being missing, so a cleared secret must not come back as a mask of the empty
+ * string.
+ */
+export function maskedSecretField<K extends string>(
+ key: K,
+ secret: string,
+): Partial<Record<K, string>> {
+ return secret === "" ? {} : ({ [key]: maskApiKey(secret) } as Record<K, string>);
+}
+
+/**
+ * The delivery preferences a PUT carries, read off its body in the shape the repo's update
+ * takes: a field the request omitted is absent here, and absent means "keep what is stored".
+ *
+ * Read once for every channel, because these are the fields that are the same on all of them.
+ * A fourth preference is one line here and nowhere else — the three-per-channel spread this
+ * replaces is what made the last two cost nine.
+ */
+export function deliveryPatchOf(body: Record<string, unknown>): MessagingDeliveryPatch {
+ const linePerMessage = optionalBoolean(body, "linePerMessage");
+ const finalReplyOnly = optionalBoolean(body, "finalReplyOnly");
+ const renderMarkdown = optionalBoolean(body, "renderMarkdown");
+ return {
+ ...(linePerMessage !== undefined ? { linePerMessage } : {}),
+ ...(finalReplyOnly !== undefined ? { finalReplyOnly } : {}),
+ ...(renderMarkdown !== undefined ? { renderMarkdown } : {}),
+ };
+}
+
+/** What {@link resolveSecret} decided, and where it came from. */
+export interface ResolvedSecret {
+ secret: string;
+ /**
+ * Whether the secret arrived in THIS request. The channels that derive an account identity
+ * from the credential itself (Telegram, from the token's numeric half) re-derive it only
+ * then; the other branches keep the identity the row already had.
+ */
+ fromRequest: boolean;
+}
+
+/**
+ * The credential ladder every channel's PUT climbs, in the one order they all agree on:
+ *
+ * 1. a typed credential wins — including over the clear flag, which is the models-page idiom;
+ * 2. otherwise the clear flag drops the stored one, **refused while the binding is enabled**:
+ * a live connection must never keep running on a credential the store no longer has;
+ * 3. otherwise the stored credential carries over, so a save that only changes a preference
+ * never has to round-trip the secret — which is what lets the masked value stay masked;
+ * 4. and a first bind with nothing at any step is a 400 naming the channel's own code.
+ *
+ * A blank typed value is not a credential: it is what an untouched field submits, and treating
+ * it as one would let a save with an empty box wipe a working binding.
+ */
+export function resolveSecret(args: {
+ typed: string | undefined;
+ clear: boolean;
+ existing: MessagingBindingRow | null;
+ stored: string;
+ requiredCode: string;
+ requiredMessage: string;
+}): ResolvedSecret {
+ const typed = args.typed !== undefined && args.typed !== "" ? args.typed : undefined;
+ if (typed !== undefined) return { secret: typed, fromRequest: true };
+ if (args.clear && args.existing !== null) {
+ if (args.existing.enabled) {
+ throw new HttpError(
+ 409,
+ "messaging_disable_before_clear",
+ "Disable the connection before clearing its credential.",
+ );
+ }
+ return { secret: "", fromRequest: false };
+ }
+ if (args.stored === "") throw new HttpError(400, args.requiredCode, args.requiredMessage);
+ return { secret: args.stored, fromRequest: false };
+}
diff --git a/packages/server/src/http/routes/messaging.ts b/packages/server/src/http/routes/messaging.ts
index 7ffd5c99..d9f3d1c4 100644
--- a/packages/server/src/http/routes/messaging.ts
+++ b/packages/server/src/http/routes/messaging.ts
@@ -76,6 +76,14 @@ import {
requireString,
} from "../validate.js";
import type { AppDeps } from "../../app.js";
+import {
+ commonBindingFields,
+ deliveryPatchOf,
+ maskedSecretField,
+ resolveSecret,
+} from "./messaging-channels.js";
+import type { MessagingChannelSpec } from "./messaging-channels.js";
+import type { MessagingChannel } from "../../runtime/messaging/connector.js";
/** The stored feishu config, tolerated loosely (a malformed document reads as blanks). */
function feishuFieldsOf(row: MessagingBindingRow): {
@@ -106,66 +114,71 @@ function qqFieldsOf(row: MessagingBindingRow): { appId: string; appSecret: strin
};
}
-function toFeishuInfo(row: MessagingBindingRow): FeishuBindingInfo {
- const fields = feishuFieldsOf(row);
- return {
+/**
+ * The three channels, each saying only what it does not share (see messaging-channels.ts).
+ * Everything written against this table — the read, the state toggle, the delete, the test
+ * message, the enable gate's credential check — is written once.
+ *
+ * A `Record` keyed by the discriminant rather than an array: every lookup here starts from a
+ * channel already in hand, and a stored row's channel is untrusted text, so `?? null` on a
+ * miss is the shape both callers want.
+ */
+const CHANNEL_SPECS: Readonly<Record<MessagingChannel, MessagingChannelSpec>> = {
+ feishu: {
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,
- linePerMessage: row.linePerMessage,
- finalReplyOnly: row.finalReplyOnly,
- renderMarkdown: row.renderMarkdown,
- lastChatKnown: row.lastChatId !== null,
- createdAt: row.createdAt,
- updatedAt: row.updatedAt,
- };
-}
-
-function toTelegramInfo(row: MessagingBindingRow): TelegramBindingInfo {
- const { botToken } = telegramFieldsOf(row);
- return {
+ label: "Feishu",
+ storedSecret: (row) => feishuFieldsOf(row).appSecret,
+ secretRequiredCode: "feishu_secret_required",
+ toInfo: (row) => {
+ const fields = feishuFieldsOf(row);
+ return {
+ channel: "feishu",
+ ...commonBindingFields(row),
+ appId: fields.appId,
+ ...maskedSecretField("appSecretMasked", fields.appSecret),
+ baseDomain: fields.baseDomain,
+ };
+ },
+ },
+ telegram: {
channel: "telegram",
- sessionId: row.sessionId,
- botId: row.accountId,
- ...(botToken !== "" ? { botTokenMasked: maskApiKey(botToken) } : {}),
- enabled: row.enabled,
- linePerMessage: row.linePerMessage,
- finalReplyOnly: row.finalReplyOnly,
- renderMarkdown: row.renderMarkdown,
- lastChatKnown: row.lastChatId !== null,
- createdAt: row.createdAt,
- updatedAt: row.updatedAt,
- };
-}
-
-function toQQInfo(row: MessagingBindingRow): QQBindingInfo {
- const fields = qqFieldsOf(row);
- return {
+ label: "Telegram",
+ storedSecret: (row) => telegramFieldsOf(row).botToken,
+ secretRequiredCode: "telegram_token_required",
+ toInfo: (row) => ({
+ channel: "telegram",
+ ...commonBindingFields(row),
+ // The bot id is the row's account identity rather than a config field: it survives a
+ // cleared token, because the half in front of a token's colon never changes for a bot.
+ botId: row.accountId,
+ ...maskedSecretField("botTokenMasked", telegramFieldsOf(row).botToken),
+ }),
+ },
+ qq: {
channel: "qq",
- sessionId: row.sessionId,
- appId: fields.appId,
- ...(fields.appSecret !== "" ? { appSecretMasked: maskApiKey(fields.appSecret) } : {}),
- enabled: row.enabled,
- linePerMessage: row.linePerMessage,
- finalReplyOnly: row.finalReplyOnly,
- renderMarkdown: row.renderMarkdown,
- lastChatKnown: row.lastChatId !== null,
- createdAt: row.createdAt,
- updatedAt: row.updatedAt,
- };
+ label: "QQ",
+ storedSecret: (row) => qqFieldsOf(row).appSecret,
+ secretRequiredCode: "qq_secret_required",
+ toInfo: (row) => {
+ const fields = qqFieldsOf(row);
+ return {
+ channel: "qq",
+ ...commonBindingFields(row),
+ appId: fields.appId,
+ ...maskedSecretField("appSecretMasked", fields.appSecret),
+ };
+ },
+ },
+};
+
+/** The spec for a stored row's channel, or null on an unknown discriminator (skipped defensively, like the bridge does). */
+function specOf(channel: string): MessagingChannelSpec | null {
+ return CHANNEL_SPECS[channel as MessagingChannel] ?? null;
}
-/** Whatever channel the row is: its masked view, or null on an unknown discriminator (skipped defensively, like the bridge does). */
+/** Whatever channel the row is: its masked view, or null on an unknown discriminator. */
function toBindingInfo(row: MessagingBindingRow): MessagingBindingInfo | null {
- if (row.channel === "feishu") return toFeishuInfo(row);
- if (row.channel === "telegram") return toTelegramInfo(row);
- if (row.channel === "qq") return toQQInfo(row);
- return null;
+ return specOf(row.channel)?.toInfo(row) ?? null;
}
/** Normalizes a domain input: blank → the default; anything else must be an http(s) origin. */
@@ -212,29 +225,25 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
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");
+ /**
+ * One channel's saved config plus its live connection status — the body every endpoint on
+ * this router answers with, so a caller never has to ask twice to see the effect of what it
+ * just did. Typed by the channel's own response so each route keeps its exact wire contract.
+ */
+ const bindingResponse = (sessionId: string, spec: MessagingChannelSpec) => {
+ const row = deps.messagingRepo.find(sessionId, spec.channel);
return {
- binding: row ? toTelegramInfo(row) : null,
- status: deps.messaging.statusOf(sessionId, "telegram"),
+ binding: row ? spec.toInfo(row) : null,
+ status: deps.messaging.statusOf(sessionId, spec.channel),
};
};
- const qqResponse = (sessionId: string): QQBindingResponse => {
- const row = deps.messagingRepo.find(sessionId, "qq");
- return {
- binding: row ? toQQInfo(row) : null,
- status: deps.messaging.statusOf(sessionId, "qq"),
- };
- };
+ const feishuResponse = (sessionId: string): FeishuBindingResponse =>
+ bindingResponse(sessionId, CHANNEL_SPECS.feishu) as FeishuBindingResponse;
+ const telegramResponse = (sessionId: string): TelegramBindingResponse =>
+ bindingResponse(sessionId, CHANNEL_SPECS.telegram) as TelegramBindingResponse;
+ const qqResponse = (sessionId: string): QQBindingResponse =>
+ bindingResponse(sessionId, CHANNEL_SPECS.qq) as QQBindingResponse;
/**
* The one-connection-per-account rule, on its own because two paths need it: the enable,
@@ -279,20 +288,16 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
);
}
guardAccountFree(sessionId, channel, row.accountId);
- const secret =
- channel === "feishu"
- ? feishuFieldsOf(row).appSecret
- : channel === "qq"
- ? qqFieldsOf(row).appSecret
- : telegramFieldsOf(row).botToken;
- if (secret === "") {
- const code =
- channel === "feishu"
- ? "feishu_secret_required"
- : channel === "qq"
- ? "qq_secret_required"
- : "telegram_token_required";
- throw new HttpError(400, code, "The stored config has no credential: save one first.");
+ // An unknown discriminator cannot be enabled: nothing can connect it, and the spec table
+ // is what says so. It is reachable only from a row written by a build that had a channel
+ // this one does not.
+ const spec = specOf(channel);
+ if (spec === null || spec.storedSecret(row) === "") {
+ throw new HttpError(
+ 400,
+ spec?.secretRequiredCode ?? "messaging_channel_unknown",
+ "The stored config has no credential: save one first.",
+ );
}
};
@@ -311,11 +316,79 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
});
// —— Feishu ————————————————————————————————————————————————————————————————
+ /**
+ * The four endpoints every channel serves the same way, registered from the spec table so a
+ * channel contributes a name to them and nothing else.
+ *
+ * They were written three times each, and what varied across the copies was the channel
+ * literal and a `<channel>_` error-code prefix — which is to say nothing. What is NOT here
+ * is as deliberate: the PUT and the credential test stay hand-written below, because their
+ * inputs differ in more than a name and a table would only hide that.
+ */
+ const registerChannelRoutes = (spec: MessagingChannelSpec): void => {
+ const base = `/:sessionId/messaging/${spec.channel}`;
+ const notBound = (): never => {
+ throw new HttpError(
+ 404,
+ `${spec.channel}_not_bound`,
+ `This Session has no ${spec.label} binding.`,
+ );
+ };
+ const boundOr404 = (sessionId: string): MessagingBindingRow =>
+ deps.messagingRepo.find(sessionId, spec.channel) ?? notBound();
+
+ app.get(base, (c) => c.json(bindingResponse(resolveSession(c).sessionId, spec)));
+
+ // 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(`${base}/state`, async (c) => {
+ const row = resolveSession(c);
+ deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ const enabled = await readStateBody(c);
+ const binding = boundOr404(row.sessionId);
+ if (enabled) guardEnable(row.sessionId, spec.channel, binding);
+ deps.messagingRepo.setEnabled(row.sessionId, spec.channel, enabled);
+ await deps.messaging.sync(row.sessionId);
+ return c.json(bindingResponse(row.sessionId, spec));
+ });
- app.get("/:sessionId/messaging/feishu", (c) => {
- const row = resolveSession(c);
- 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(base, (c) => {
+ const row = resolveSession(c);
+ deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ deps.messaging.unbind(row.sessionId, spec.channel);
+ return c.body(null, 204);
+ });
+
+ // 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 the channel first.
+ app.post(`${base}/test-message`, async (c) => {
+ const row = resolveSession(c);
+ const binding = boundOr404(row.sessionId);
+ if (binding.lastChatId === null) {
+ throw new HttpError(
+ 409,
+ `${spec.channel}_no_chat`,
+ `No ${spec.label} chat is known yet: message the bot once in ${spec.label} first.`,
+ );
+ }
+ try {
+ await deps.messaging.sendTestMessage(binding);
+ } catch (err) {
+ throw new HttpError(
+ 502,
+ `${spec.channel}_send_failed`,
+ err instanceof Error ? err.message : String(err),
+ );
+ }
+ return c.json({ ok: true } satisfies MessagingTestMessageResponse);
+ });
+ };
+
+ for (const spec of Object.values(CHANNEL_SPECS)) registerChannelRoutes(spec);
app.put("/:sessionId/messaging/feishu", async (c) => {
const row = resolveSession(c);
@@ -323,35 +396,16 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
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 linePerMessage = optionalBoolean(body, "linePerMessage");
- const finalReplyOnly = optionalBoolean(body, "finalReplyOnly");
- const renderMarkdown = optionalBoolean(body, "renderMarkdown");
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 { secret: appSecret } = resolveSecret({
+ typed: optionalString(body, "appSecret", { maxLen: 500 })?.trim(),
+ clear: (body as { clearAppSecret?: unknown }).clearAppSecret === true,
+ existing,
+ stored: existing !== null ? feishuFieldsOf(existing).appSecret : "",
+ requiredCode: "feishu_secret_required",
+ requiredMessage: "appSecret is required to bind.",
+ });
// A save never enables — but an ENABLED binding re-pointed at another app keeps its
// connection and restarts it below, which would stand two Sessions on one app without
// ever passing the enable gate. Exclusivity is therefore asked here too, of the app
@@ -363,9 +417,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
channel: "feishu",
accountId: appId,
config: { appId, appSecret, baseDomain },
- ...(linePerMessage !== undefined ? { linePerMessage } : {}),
- ...(finalReplyOnly !== undefined ? { finalReplyOnly } : {}),
- ...(renderMarkdown !== undefined ? { renderMarkdown } : {}),
+ ...deliveryPatchOf(body),
});
// 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
@@ -375,32 +427,6 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
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) => {
@@ -429,59 +455,26 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
} 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 linePerMessage = optionalBoolean(body, "linePerMessage");
- const finalReplyOnly = optionalBoolean(body, "finalReplyOnly");
- const renderMarkdown = optionalBoolean(body, "renderMarkdown");
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;
+ const { secret: botToken, fromRequest } = resolveSecret({
+ typed: optionalString(body, "botToken", { maxLen: 200 })?.trim(),
+ clear: (body as { clearBotToken?: unknown }).clearBotToken === true,
+ existing,
+ stored: existing !== null ? telegramFieldsOf(existing).botToken : "",
+ requiredCode: "telegram_token_required",
+ requiredMessage: "botToken is required to bind.",
+ });
+ // The one channel whose account identity comes out of the credential rather than out of a
+ // field of its own, so it is re-derived exactly when a new token arrives. Every other
+ // branch keeps the row's identity: the half in front of a token's colon never changes for
+ // a bot, so a cleared config still knows which bot it was.
let botId: string;
- if (typed !== undefined) {
- const id = telegramBotIdOf(typed);
+ if (fromRequest) {
+ const id = telegramBotIdOf(botToken);
if (id === null) {
throw new HttpError(
400,
@@ -489,25 +482,9 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
"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;
+ botId = existing!.accountId;
}
// Same reason as the Feishu PUT: a token swap on an enabled binding would carry the
// live connection onto another bot without passing the enable gate.
@@ -517,36 +494,13 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
channel: "telegram",
accountId: botId,
config: { botToken },
- ...(linePerMessage !== undefined ? { linePerMessage } : {}),
- ...(finalReplyOnly !== undefined ? { finalReplyOnly } : {}),
- ...(renderMarkdown !== undefined ? { renderMarkdown } : {}),
+ ...deliveryPatchOf(body),
});
// Same save/enable split as Feishu: only an enabled binding restarts its connector.
if (saved.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.
@@ -574,76 +528,21 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
} 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);
- });
-
- // —— QQ ————————————————————————————————————————————————————————————————————
- //
- // Same verb set and the same save/enable split as the two channels above; the config is
- // the App ID / App Secret pair from the QQ developer console, and the App ID is the
- // account identity (the QQ analogue of the Feishu app id: stable, non-secret, and
- // unchanged by rotating the secret).
-
- app.get("/:sessionId/messaging/qq", (c) => {
- const row = resolveSession(c);
- return c.json(qqResponse(row.sessionId));
- });
-
app.put("/:sessionId/messaging/qq", 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 linePerMessage = optionalBoolean(body, "linePerMessage");
- const finalReplyOnly = optionalBoolean(body, "finalReplyOnly");
- const renderMarkdown = optionalBoolean(body, "renderMarkdown");
const existing = deps.messagingRepo.find(row.sessionId, "qq");
- const typed = secretInput !== undefined && secretInput !== "" ? secretInput : undefined;
- // The same ladder as the other two channels: typed wins, then the clear flag (disable
- // first), then the stored secret; a first bind must carry one.
- 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 ? qqFieldsOf(existing).appSecret : "";
- if (stored === "") {
- throw new HttpError(400, "qq_secret_required", "appSecret is required to bind.");
- }
- appSecret = stored;
- }
+ const { secret: appSecret } = resolveSecret({
+ typed: optionalString(body, "appSecret", { maxLen: 500 })?.trim(),
+ clear: (body as { clearAppSecret?: unknown }).clearAppSecret === true,
+ existing,
+ stored: existing !== null ? qqFieldsOf(existing).appSecret : "",
+ requiredCode: "qq_secret_required",
+ requiredMessage: "appSecret is required to bind.",
+ });
// Same reason as the Feishu and Telegram PUTs: an enabled binding re-pointed at another
// App ID keeps its connection and restarts it below, which would stand two Sessions on
// one bot's single gateway without either passing the enable gate.
@@ -653,37 +552,12 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
channel: "qq",
accountId: appId,
config: { appId, appSecret },
- ...(linePerMessage !== undefined ? { linePerMessage } : {}),
- ...(finalReplyOnly !== undefined ? { finalReplyOnly } : {}),
- ...(renderMarkdown !== undefined ? { renderMarkdown } : {}),
+ ...deliveryPatchOf(body),
});
if (saved.enabled) await deps.messaging.sync(row.sessionId);
return c.json(qqResponse(row.sessionId));
});
- app.post("/:sessionId/messaging/qq/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, "qq");
- if (binding === null) {
- throw new HttpError(404, "qq_not_bound", "This Session has no QQ binding.");
- }
- if (enabled) guardEnable(row.sessionId, "qq", binding);
- deps.messagingRepo.setEnabled(row.sessionId, "qq", enabled);
- await deps.messaging.sync(row.sessionId);
- return c.json(qqResponse(row.sessionId));
- });
-
- app.delete("/:sessionId/messaging/qq", (c) => {
- const row = resolveSession(c);
- deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
- deps.messaging.unbind(row.sessionId, "qq");
- // A scan still in flight would land on a config that has just been removed.
- deps.qqScan.cancelSession(row.sessionId);
- return c.body(null, 204);
- });
-
// —— QQ scan-to-connect ————————————————————————————————————————————————————
//
// The alternative to typing an App ID and an App Secret: the server registers a bind task
@@ -761,7 +635,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
return c.json({
status: "completed",
appId: result.bot.appId,
- binding: toQQInfo(saved),
+ binding: CHANNEL_SPECS.qq.toInfo(saved) as QQBindingInfo,
} satisfies QQScanPollResponse);
});
@@ -796,32 +670,6 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
...(result.error !== undefined ? { error: result.error } : {}),
} satisfies QQTestResponse);
});
-
- // The one test endpoint that means something different here. On Feishu and Telegram a
- // known chat is enough to send into; on QQ a message may only be sent as a reply to one
- // the user sent minutes ago, so the 409 below is the weaker of two gates and the send can
- // still fail with 502 `qq_send_failed` naming the window. The message text says so.
- app.post("/:sessionId/messaging/qq/test-message", async (c) => {
- const row = resolveSession(c);
- const binding = deps.messagingRepo.find(row.sessionId, "qq");
- if (!binding) {
- throw new HttpError(404, "qq_not_bound", "This Session has no QQ binding.");
- }
- if (binding.lastChatId === null) {
- throw new HttpError(
- 409,
- "qq_no_chat",
- "No QQ chat is known yet: message the bot once in QQ first.",
- );
- }
- try {
- await deps.messaging.sendTestMessage(binding);
- } catch (err) {
- throw new HttpError(502, "qq_send_failed", err instanceof Error ? err.message : String(err));
- }
- return c.json({ ok: true } satisfies MessagingTestMessageResponse);
- });
-
return app;
}