A local-first multi-agent app development platform, built on PenguinHarness
fix(server): group messages reach the model as what the user wrote, not as mention placeholders (#497)
Yaowei Zhengdb3bbd52f57d
diff --git a/changelog/unreleased/2026-08-26-messaging-inbound-mentions.md b/changelog/unreleased/2026-08-26-messaging-inbound-mentions.mdnew file mode 100644index 00000000..4fa2f175--- /dev/null+++ b/changelog/unreleased/2026-08-26-messaging-inbound-mentions.md@@ -0,0 +1,60 @@+# Group messages reach the model as what the user wrote, not as mention placeholders++- **Date:** 2026-08-26+- **Type:** fix+- **Scope:** `server`+- **PR:** [#497](https://github.com/Prism-Shadow/penguin-harness/pull/497)++[中文版](2026-08-26-messaging-inbound-mentions.zh.md)++Addressing a bot in a group means mentioning it, so nearly every group message a binding+receives carries an `@`. Neither channel handed that to the model in a usable form: Feishu writes+a placeholder the model cannot resolve, and Telegram leaves the bot's own handle in front of the+sentence. A Session driven from a Feishu group answered `我看到你发的是 @_user_1 你好,但我不太确定+_user_1 指的是谁或什么` — a whole turn spent on a token that was never part of the message.++## Feishu: placeholders become names++Feishu's `im.message.receive_v1` puts `@_user_1` in the content JSON's `text` and carries the real+identity in a parallel `mentions` array the connector did not read. That array now rides+`FeishuInboundEvent`, and every placeholder is replaced with the mentioned party's name before the+text reaches the Session.++Substitution is one left-to-right pass over the original text, its keys ordered longest first. Two+problems called for that. Feishu numbers placeholders from 1 upward, so `@_user_1` is a literal+prefix of `@_user_10`. And a pass per key re-scans what the earlier passes wrote, which let a+display name that reads like a placeholder be replaced a second time. Each key is substituted at+its first occurrence only — Feishu emits exactly one placeholder per key, so anything further along+that spells the same key is a token the user typed by hand, and it reaches the model as typed.++The bot's identity comes from one `/open-apis/bot/v3/info` lookup per connection, and that lookup+was moved off the connect path onto a background promise. Every enabled binding connects while the+server boots, before the HTTP listener binds; a Feishu endpoint that accepts TCP and then never+answers — a stalled proxy, a blackholing firewall — would otherwise have held the whole server down+on a best-effort display-name lookup. Until the answer lands, and when the app cannot report an+identity at all, this bot's mention is named like everyone else's.++## Telegram: the bot's own handle is stripped++The bot's `@username` is already known from the `getMe` the poll loop makes before every up-streak.+An opening `mention` entity of its own (matched case-insensitively) or `text_mention` entity+(matched by user id) is cut off the front of the text, and what remains is trimmed — the same+whitespace policy the Feishu side applies to its own placeholder. Entity offsets are UTF-16 code+units, which is what a JavaScript string index already is, so an emoji ahead of the handle or inside+a linked display name does not shift the cut.++## Only the addressing prefix is dropped++A mention counts as addressing only when the message opens with it. This bot named further in —+"what is @thisbot's status?", "summarize what @thisbot said yesterday", a Feishu placeholder for it+standing mid-sentence — is a word the user chose, and it stays: on Telegram as the handle the user+typed, on Feishu as this bot's name, exactly like anyone else's mention. Cutting those left the+model a sentence with a hole in it ("what is 's status?"), which is worse than naming the channel+the message came through.++## A message with no words starts no Task++A message left with nothing but mentions — someone `@`-ed the bot and typed nothing else — now+takes the same branch a sticker does, answering with the text-only notice instead of starting a+run on a bare placeholder. On Feishu the emptiness is judged with every placeholder removed, not+only this bot's, so it holds whether or not the bot's identity resolved.diff --git a/changelog/unreleased/2026-08-26-messaging-inbound-mentions.zh.md b/changelog/unreleased/2026-08-26-messaging-inbound-mentions.zh.mdnew file mode 100644index 00000000..81f73219--- /dev/null+++ b/changelog/unreleased/2026-08-26-messaging-inbound-mentions.zh.md@@ -0,0 +1,49 @@+# 群消息以用户实际写下的内容抵达模型,而不是提及占位符++- **Date:** 2026-08-26+- **Type:** fix+- **Scope:** `server`+- **PR:** [#497](https://github.com/Prism-Shadow/penguin-harness/pull/497)++[English](2026-08-26-messaging-inbound-mentions.md)++在群里对机器人说话就意味着要提及它,因此绑定收到的群消息几乎每一条都带着一个 `@`。两个渠道此前都+没有把它交成模型可用的形式:飞书写入的是模型无法解析的占位符,Telegram 则把机器人自己的 handle 留+在句首。一个由飞书群驱动的 Session 因此答道「我看到你发的是 `@_user_1 你好`,但我不太确定+`_user_1` 指的是谁或什么」——整整一轮花在一个从来不属于该消息的 token 上。++## 飞书:占位符变成名字++飞书的 `im.message.receive_v1` 在 content JSON 的 `text` 里放的是 `@_user_1`,真实身份放在连接器+未曾读取的并列 `mentions` 数组中。该数组现在随 `FeishuInboundEvent` 一同传递,每个占位符在文本抵达+Session 之前都会被替换为被提及者的名字。++替换是对原文的一次从左到右扫描,键名按从长到短排列。这是两个问题共同要求的。飞书的占位符从 1 开始+编号,因此 `@_user_1` 是 `@_user_10` 的字面前缀。而逐个键各扫一遍,后面的扫描会重新扫到前几遍刚写+下的内容,于是一个读起来像占位符的显示名会被替换第二次。每个键只在**首次**出现处被替换——飞书对每+个键只发出一个占位符,因此再往后出现的同名 token 是用户亲手敲出来的文字,会原样抵达模型。++机器人身份来自每次连接一次的 `/open-apis/bot/v3/info` 查询,而这次查询已被移出连接路径,交给一个后+台 promise。每个已启用的绑定都在服务器启动、HTTP 监听尚未绑定之前建立连接;一个接受了 TCP 却永远不+作答的飞书端点——卡住的代理、黑洞防火墙——原本会让整台服务器被一次尽力而为的显示名查询拖住。在答案+落地之前,以及应用根本无法给出身份时,本机器人的提及与其他人一样被命名。++## Telegram:剥掉机器人自己的 handle++机器人的 `@username` 本就来自轮询循环在每段连通期之前所做的 `getMe`。属于它自己的开头 `mention` 实+体(大小写不敏感匹配)或 `text_mention` 实体(按用户 id 匹配)会从文本开头剪除,剩下的部分做一次+trim——与飞书侧对自己占位符所用的空白处理策略相同。实体偏移以 UTF-16 码元计数,而这正是 JavaScript+字符串下标本身的单位,因此 handle 之前的 emoji、或被链接的显示名内部的 emoji,都不会让剪除位置错位。++## 只有开头的称呼会被丢掉++只有当消息以某个提及开头时,它才算称呼。本机器人出现在句子中间时——「@thisbot 的状态是什么?」「总+结一下 @thisbot 昨天说了什么」,以及飞书中位于句中的占位符——那是用户自己选择的文字,于是它被保留下+来:在 Telegram 上保留为用户敲出的 handle,在飞书上则显示为本机器人的名字,与其他任何人的提及一样。+剪掉它们会给模型留下一个带窟窿的句子(「 的状态是什么?」),那比让它看出消息来自哪个渠道更糟。++## 没有实际内容的消息不再发起 Task++只剩提及的消息——有人 `@` 了机器人却没有写别的——现在走与表情包相同的分支,以「仅支持文本消息」的+提示作答,而不是拿一个裸占位符发起一轮运行。在飞书侧,这一「是否为空」的判断是在移除**全部**占位符+(而不只是本机器人的)之后做出的,因此无论机器人身份是否解析成功都成立。diff --git a/packages/server/src/runtime/messaging/feishu-connector.ts b/packages/server/src/runtime/messaging/feishu-connector.tsindex 724b9bb3..6f2453ed 100644--- a/packages/server/src/runtime/messaging/feishu-connector.ts+++ b/packages/server/src/runtime/messaging/feishu-connector.ts@@ -4,7 +4,8 @@* 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`).+ * from the content JSON and its mention placeholders resolved — see resolveFeishuMentions;+ * anything non-text reads as `text: null`).*/import type {MessagingChannelConnector,@@ -12,7 +13,7 @@ import type {MessagingConnection,MessagingConnectorHandlers,} from "./connector.js";-import type { FeishuCredentials, FeishuSdk } from "./feishu-sdk.js";+import type { FeishuCredentials, FeishuMention, 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";@@ -50,6 +51,77 @@ function textOfContent(content: string): string | null {}}+/** Escapes a mention key for embedding in a RegExp (keys are `@_user_N`, but keep this honest). */+function escapeKey(key: string): string {+ return key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++/**+ * One alternation over every mention key, longest key first.+ *+ * Two things make it a single regex rather than a substitution per key. Feishu numbers its+ * placeholders `@_user_1`, `@_user_2`, … — so once a message mentions ten people, `@_user_1`+ * is a prefix of `@_user_10`, and an ordered alternation lets the longer key win wherever+ * both could match. And one regex means ONE left-to-right pass over the original text: key+ * by key, every later key re-scans what the earlier ones already wrote, so a mentioned+ * party whose display name reads like a placeholder gets replaced a second time.+ */+function mentionKeyRegex(mentions: readonly FeishuMention[]): RegExp {+ const keys = [...mentions]+ .sort((a, b) => b.key.length - a.key.length)+ .map((m) => escapeKey(m.key));+ return new RegExp(keys.join("|"), "g");+}++/**+ * Rewrites a message's text into what the user actually wrote.+ *+ * Feishu never puts a mention in the text: it writes a placeholder (`@_user_1`) and carries+ * who it refers to in a parallel `mentions` array. Handed to the model raw, that is a token+ * nothing in the conversation can resolve — a group message reads as `@_user_1 你好` and the+ * model spends its turn asking who `_user_1` is. Every placeholder therefore becomes the+ * mentioned party's name.+ *+ * A LEADING mention of this bot is dropped instead of named, when its open id is known: the+ * bridge feeds inbound text to the model exactly as if it had been typed into the web+ * composer, and a `@PenguinHarness` in front of the sentence would announce the channel the+ * message came through. Only that addressing prefix goes — this bot named further in ("why+ * did @PenguinHarness stop replying?") is a word the user chose, and it reads as itself like+ * anyone else's. An unknown id (see FeishuApiClient.botOpenId) only means the prefix is named+ * too — the confusion the placeholder caused is gone either way.+ *+ * Each key is substituted at its FIRST occurrence only: Feishu emits one placeholder per key,+ * so anything further along that spells the same key is a token the user typed by hand, and+ * it stays as typed.+ *+ * Returns `""` when the message carries nothing but mentions — someone `@`-ed the bot and+ * typed no words — because there is no message there to run a Task on. The emptiness is+ * judged with EVERY placeholder removed, not just this bot's, so it holds whether or not+ * the bot's own id was resolved.+ */+export function resolveFeishuMentions(+ text: string,+ mentions: readonly FeishuMention[] | undefined,+ botOpenId: string | null,+): string {+ // An empty key would match at every position: a malformed event does not get to shred the text.+ const keyed = (mentions ?? []).filter((m) => m.key !== "");+ if (keyed.length === 0) return text;+ const re = mentionKeyRegex(keyed);+ if (text.replace(re, "").trim() === "") return "";+ const byKey = new Map(keyed.map((m) => [m.key, m]));+ const substituted = new Set<string>();+ const out = text.replace(re, (key: string, offset: number) => {+ if (substituted.has(key)) return key;+ substituted.add(key);+ const mention = byKey.get(key)!;+ const isThisBot = botOpenId !== null && mention.openId === botOpenId;+ const isLeading = text.slice(0, offset).trim() === "";+ return isThisBot && isLeading ? "" : `@${mention.name}`;+ });+ return out.trim();+}+export class FeishuConnector implements MessagingChannelConnector {readonly channel = "feishu" as const;@@ -64,21 +136,47 @@ export class FeishuConnector implements MessagingChannelConnector {return this.sdk.createClient(this.credsOf(config));}- connect(+ async connect(config: Record<string, unknown>,handlers: MessagingConnectorHandlers,): Promise<MessagingConnection> {- return this.sdk.connect(this.credsOf(config), {- onMessage: (evt) =>- handlers.onMessage({+ const creds = this.credsOf(config);+ /**+ * This bot's own open id: which mention in a group message is its own never changes while+ * the credentials do not, so one lookup per connection serves every inbound message.+ */+ let botOpenId: string | null = null;+ // Deliberately not awaited. connect() must resolve as soon as the connection is+ // constructed (see MessagingChannelConnector.connect): the bridge walks every enabled+ // binding on the server's boot path, so a lookup against an endpoint that accepts TCP and+ // never answers would keep the HTTP listener from ever binding. Telegram learns its own+ // identity the same way, from inside its poll loop. Until the answer lands, a mention of+ // this bot is named rather than dropped — the same degraded mode an app that cannot report+ // an identity at all already lives in.+ void this.sdk+ .createClient(creds)+ .then((client) => client.botOpenId())+ .then((id) => {+ botOpenId = id;+ })+ .catch(() => {+ // `botOpenId` resolves null rather than throwing (see its doc); building the client+ // around it still can, and an unavailable identity is never a reason to refuse a+ // connection.+ });+ return this.sdk.connect(creds, {+ onMessage: (evt) => {+ // Only `text` messages carry text; every other message type normalizes to null+ // (the bridge answers those with the text-only notice).+ const raw = evt.messageType === "text" ? textOfContent(evt.content) : null;+ return 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,+ text: raw === null ? null : resolveFeishuMentions(raw, evt.mentions, botOpenId),...(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.tsindex 14046f25..131ad286 100644--- a/packages/server/src/runtime/messaging/feishu-sdk.ts+++ b/packages/server/src/runtime/messaging/feishu-sdk.ts@@ -18,6 +18,21 @@ export interface FeishuCredentials {baseDomain: string;}+/**+ * One `@` in a message, as Feishu reports it: the event's `content` JSON carries only a+ * placeholder (`@_user_1`) where the mention stands, and this array says what each+ * placeholder refers to. Without it the text is unreadable — see the connector's+ * resolveFeishuMentions.+ */+export interface FeishuMention {+ /** The literal placeholder inside the content JSON's `text`, e.g. `@_user_1`. */+ key: string;+ /** Display name of whoever was mentioned (a bot's is its own name). */+ name: string;+ /** Open id of whoever was mentioned; absent when the event carries no id for them. */+ openId?: string;+}+/** One inbound `im.message.receive_v1` event, reduced to what the connector consumes. */export interface FeishuInboundEvent {chatId: string;@@ -30,6 +45,8 @@ export interface FeishuInboundEvent {content: string;/** Sender display name when the event carries one (the standard event does not). */senderName?: string;+ /** Everyone `@`-ed in this message, in the order Feishu lists them; absent when nobody was. */+ mentions?: FeishuMention[];}/** OpenAPI half of the seam: credential probe + text sends. Every method throws on failure. */@@ -44,6 +61,16 @@ export interface FeishuApiClient {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>;+ /**+ * This app's own bot open id, so a group message's mention of THIS bot can be told apart+ * from a mention of anyone else (the ids are the only thing that distinguishes them —+ * two accounts may share a display name).+ *+ * Resolves null rather than throwing when the app cannot report one: the bot capability+ * may be off, or the call may simply fail, and neither is a reason to refuse a+ * connection. A null answer degrades mention handling, it does not break it.+ */+ botOpenId(): Promise<string | null>;}export interface FeishuEventHandlers {@@ -103,6 +130,15 @@ interface LarkResponse {}interface LarkClient {+ /**+ * The SDK's generic call, for endpoints its typed surface does not cover. Used for+ * `/open-apis/bot/v3/info`, which has no typed member here (the SDK's own internals reach+ * it the same way).+ */+ request(args: {+ url: string;+ method: string;+ }): Promise<LarkResponse & { bot?: { open_id?: string } }>;auth: {v3: {tenantAccessToken: {@@ -140,6 +176,11 @@ interface LarkEventDispatcher {chat_type: string;message_type: string;content: string;+ mentions?: {+ key: string;+ name: string;+ id?: { open_id?: string };+ }[];};}) => Promise<void>;}): LarkEventDispatcher;@@ -217,6 +258,18 @@ export function createLarkSdk(): FeishuSdk {}ensureOk(res, "Message reply");},+ async botOpenId(): Promise<string | null> {+ // Best effort by contract (see FeishuApiClient.botOpenId): every failure shape —+ // a thrown request, a non-zero envelope, a body without the field — answers+ // "unknown" so a connection is never refused over it.+ try {+ const res = await client.request({ url: "/open-apis/bot/v3/info", method: "GET" });+ if (res.code !== undefined && res.code !== 0) return null;+ return res.bot?.open_id ?? null;+ } catch {+ return null;+ }+ },};},@@ -227,12 +280,18 @@ export function createLarkSdk(): FeishuSdk {const lark = await load();const dispatcher = new lark.EventDispatcher({}).register({"im.message.receive_v1": async (data) => {+ const mentions = data.message.mentions?.map((m) => ({+ key: m.key,+ name: m.name,+ ...(m.id?.open_id !== undefined ? { openId: m.id.open_id } : {}),+ }));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,+ ...(mentions !== undefined ? { mentions } : {}),});},});diff --git a/packages/server/src/runtime/messaging/telegram-api.ts b/packages/server/src/runtime/messaging/telegram-api.tsindex ed2eadf2..aa2791df 100644--- a/packages/server/src/runtime/messaging/telegram-api.ts+++ b/packages/server/src/runtime/messaging/telegram-api.ts@@ -25,6 +25,22 @@ export interface TelegramBotUser {username?: string;}+/**+ * One entry of a message's `entities` array: a span over the text with a meaning attached.+ *+ * `offset` and `length` are counted in UTF-16 code units — which is exactly what a+ * JavaScript string index is, so a span applies with `slice(offset, offset + length)` and+ * nothing has to be converted anywhere in this codebase.+ */+export interface TelegramMessageEntity {+ /** `mention` (the span is a literal `@username`), `text_mention` (a user with no username, carried in `user`), `bold`, `code`, … */+ type: string;+ offset: number;+ length: number;+ /** Present on `text_mention` only: the user the span refers to, there being no `@username` in the text to match on. */+ user?: { id: number };+}+/** The slice of a Bot API `Message` the connector consumes. */export interface TelegramMessage {message_id: number;@@ -35,6 +51,12 @@ export interface TelegramMessage {};/** Present only for text messages; anything else (photo, sticker, voice, …) omits it. */text?: string;+ /**+ * Spans over `text` (mentions, formatting, …); absent when the message has none. A+ * captioned media message carries the same shapes over its caption under+ * `caption_entities` instead — the day this connector reads captions, it reads that.+ */+ entities?: TelegramMessageEntity[];from?: {first_name?: string;username?: string;diff --git a/packages/server/src/runtime/messaging/telegram-connector.ts b/packages/server/src/runtime/messaging/telegram-connector.tsindex 50a1f7c5..fb87410d 100644--- a/packages/server/src/runtime/messaging/telegram-connector.ts+++ b/packages/server/src/runtime/messaging/telegram-connector.ts@@ -9,7 +9,9 @@** The poll loop's lifecycle: a `getMe` probe (a bad token surfaces immediately as the* connection error instead of an eternally failing poll — it runs again ahead of every- * recovery attempt, so a token revoked mid-outage stops reading as a stale conflict), a+ * recovery attempt, so a token revoked mid-outage stops reading as a stale conflict, and+ * its answer is what lets a group message's opening mention of THIS bot be stripped — see+ * stripBotMention), a* `getWebhookInfo` probe (a webhook and `getUpdates` are mutually exclusive on the Bot API,* so a bot pointed at one cannot be polled until the webhook goes — the probe names it and* stops there, because removing it is the user's call: see below), then a one-time backlog@@ -42,7 +44,9 @@ import type {} from "./connector.js";import type {TelegramBotClient,+ TelegramBotUser,TelegramCredentials,+ TelegramMessageEntity,TelegramTransport,TelegramUpdate,} from "./telegram-api.js";@@ -118,8 +122,53 @@ function sleep(ms: number, signal: AbortSignal): Promise<void> {});}-/** One update reduced to the bridge's normalized shape; null for updates that are not chat messages. */-function normalizeUpdate(update: TelegramUpdate): MessagingInboundMessage | null {+/** Whether this entity is a mention OF the bot itself, by either of the two shapes Telegram uses. */+function mentionsBot(text: string, entity: TelegramMessageEntity, me: TelegramBotUser): boolean {+ if (entity.type === "text_mention") return entity.user?.id === me.id;+ if (entity.type !== "mention" || me.username === undefined) return false;+ // Telegram matches @usernames case-insensitively, and a user typing the bot's handle by+ // hand rarely matches its capitalization.+ const span = text.slice(entity.offset, entity.offset + entity.length);+ return span.toLowerCase() === `@${me.username.toLowerCase()}`;+}++/**+ * Strips the bot's own `@mention` off the FRONT of a group message.+ *+ * Addressing a bot in a group means naming it, so nearly every message this connector sees+ * from a group opens with `@thisbot `. The bridge feeds inbound text to the model exactly as+ * if it had been typed into the web composer, and that prefix announces the channel the+ * message came through — a detail the model is deliberately not told.+ *+ * Only that addressing prefix goes. This bot named further in ("what is @thisbot's status?",+ * "summarize what @thisbot said yesterday") is a word the user chose exactly like everyone+ * else's mention, and cutting it would hand the model a sentence with a hole in it.+ *+ * Leading means nothing but whitespace ahead of the span, and the cut is followed by a trim,+ * which is the same whitespace policy the Feishu side applies to its own placeholder.+ */+function stripBotMention(+ text: string,+ entities: readonly TelegramMessageEntity[] | undefined,+ me: TelegramBotUser | null,+): string {+ if (entities === undefined || me === null) return text;+ const lead = entities.find(+ (e) => text.slice(0, e.offset).trim() === "" && mentionsBot(text, e, me),+ );+ if (lead === undefined) return text;+ return (text.slice(0, lead.offset) + text.slice(lead.offset + lead.length)).trim();+}++/**+ * One update reduced to the bridge's normalized shape; null for updates that are not chat+ * messages. `me` is this bot's own account (null before the first `getMe` of a connection+ * has answered), used only to recognize its own mention.+ */+function normalizeUpdate(+ update: TelegramUpdate,+ me: TelegramBotUser | null,+): MessagingInboundMessage | null {const msg = update.message;if (msg === undefined) return null;const senderName = msg.from?.first_name ?? msg.from?.username;@@ -129,7 +178,7 @@ function normalizeUpdate(update: TelegramUpdate): MessagingInboundMessage | nullmessageId: 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,+ text: typeof msg.text === "string" ? stripBotMention(msg.text, msg.entities, me) : null,...(senderName !== undefined ? { senderName } : {}),};}@@ -194,12 +243,14 @@ export class TelegramConnector implements MessagingChannelConnector {let webhookChecked = false;/** The backlog drain runs once per connection, never again after an outage: messages sent during a mere blip still deliver. */let drained = false;+ /** This bot's own account, from the `getMe` the loop already makes; only its own mention needs it. */+ let me: TelegramBotUser | null = null;let failures = 0;let offset: number | undefined;while (!isClosed()) {try {if (!ready) {- await bot.getMe();+ me = await bot.getMe();if (isClosed()) return;if (!webhookChecked) {const { url } = await bot.getWebhookInfo();@@ -238,7 +289,7 @@ export class TelegramConnector implements MessagingChannelConnector {}for (const update of updates) {offset = update.update_id + 1;- const msg = normalizeUpdate(update);+ const msg = normalizeUpdate(update, me);if (msg !== null) await handlers.onMessage(msg);}} catch (err) {diff --git a/packages/server/test/messaging-telegram.test.ts b/packages/server/test/messaging-telegram.test.tsindex 8ea56d7a..a8767778 100644--- a/packages/server/test/messaging-telegram.test.ts+++ b/packages/server/test/messaging-telegram.test.ts@@ -209,6 +209,9 @@ class FakeFeishuSdk implements FeishuSdk {},async sendText() {},async replyText() {},+ async botOpenId() {+ return null;+ },};}async connect(_creds: FeishuCredentials, handlers: FeishuEventHandlers) {@@ -636,6 +639,125 @@ describe("telegram binding routes and connector loop", () => {});});+ it("strips this bot's own @mention out of a group message, keeping everyone else's", async () => {+ await bindEnabled(SID);+ // What addressing a bot in a group looks like on the wire: the handle is part of the+ // text, and Telegram marks it with a `mention` entity. Offsets are UTF-16 code units,+ // which is what a JS string index already is.+ fake.push({+ message_id: 88,+ chat: { id: -1002233445566, type: "supergroup" },+ text: "@penguin_test_bot ask @alice about the build",+ entities: [+ { type: "mention", offset: 0, length: 17 },+ { type: "mention", offset: 22, length: 6 },+ ],+ from: { first_name: "Ada" },+ });+ await waitFor(() => runs.length === 1);+ // Only the bot's own handle goes: the model is deliberately not told the message came+ // through a chat channel. @alice is a word the user chose and reads as itself.+ expect(runs[0]![0]!.text).toBe("ask @alice about the build");+ });++ it("matches the bot's handle case-insensitively and recognizes a text_mention by user id", async () => {+ await bindEnabled(SID);+ fake.push({+ message_id: 89,+ chat: { id: -1002233445566, type: "supergroup" },+ text: "@Penguin_Test_Bot deploy",+ entities: [{ type: "mention", offset: 0, length: 17 }],+ from: { first_name: "Ada" },+ });+ await waitFor(() => runs.length === 1);+ expect(runs[0]![0]!.text).toBe("deploy");++ // A bot with no username, or a client that linked the mention rather than typing it:+ // Telegram sends a `text_mention` carrying the user object instead of an @handle.+ fake.push({+ message_id: 90,+ chat: { id: -1002233445566, type: "supergroup" },+ text: "Penguin Test roll it back",+ entities: [{ type: "text_mention", offset: 0, length: 12, user: { id: 7000000001 } }],+ from: { first_name: "Ada" },+ });+ await waitFor(() => runs.length === 2);+ expect(runs[1]![0]!.text).toBe("roll it back");+ });++ it("keeps a mention of this bot that is not the addressing prefix", async () => {+ await bindEnabled(SID);+ fake.push({+ message_id: 92,+ chat: { id: -1002233445566, type: "supergroup" },+ text: "@penguin_test_bot summarize what @penguin_test_bot said yesterday",+ entities: [+ { type: "mention", offset: 0, length: 17 },+ { type: "mention", offset: 33, length: 17 },+ ],+ from: { first_name: "Ada" },+ });+ await waitFor(() => runs.length === 1);+ // The opening handle is how a group addresses the bot; the second one is a word inside+ // the user's sentence, and cutting it would leave the model a hole to guess at.+ expect(runs[0]![0]!.text).toBe("summarize what @penguin_test_bot said yesterday");++ // Nothing to cut here either: the sentence starts before the handle.+ fake.push({+ message_id: 93,+ chat: { id: -1002233445566, type: "supergroup" },+ text: "what is @penguin_test_bot's status?",+ entities: [{ type: "mention", offset: 8, length: 17 }],+ from: { first_name: "Ada" },+ });+ await waitFor(() => runs.length === 2);+ expect(runs[1]![0]!.text).toBe("what is @penguin_test_bot's status?");++ // What comes first need not be words. Only whitespace ahead of the handle makes it the+ // addressing prefix — and the offset that says so is in UTF-16 code units, which is what+ // a JS string index already is (the family emoji is 8 of them).+ fake.push({+ message_id: 94,+ chat: { id: -1002233445566, type: "supergroup" },+ text: "👨👩👧 @penguin_test_bot deploy",+ entities: [{ type: "mention", offset: 9, length: 17 }],+ from: { first_name: "Ada" },+ });+ await waitFor(() => runs.length === 3);+ expect(runs[2]![0]!.text).toBe("👨👩👧 @penguin_test_bot deploy");+ });++ it("cuts the addressing prefix by UTF-16 code units, not code points", async () => {+ await bindEnabled(SID);+ // A display name carrying an emoji, linked as a `text_mention` (matched by user id, so+ // the offsets are the only thing under test). The family emoji is 8 UTF-16 code units+ // but 5 code points: an implementation that indexed by code point would cut 21 of the+ // latter and hand the model "ploy".+ fake.push({+ message_id: 95,+ chat: { id: -1002233445566, type: "supergroup" },+ text: "👨👩👧 Penguin Test deploy",+ entities: [{ type: "text_mention", offset: 0, length: 21, user: { id: 7000000001 } }],+ from: { first_name: "Ada" },+ });+ await waitFor(() => runs.length === 1);+ expect(runs[0]![0]!.text).toBe("deploy");+ });++ it("a group message that is nothing but the bot's mention starts no task", async () => {+ await bindEnabled(SID);+ fake.push({+ message_id: 91,+ chat: { id: -1002233445566, type: "supergroup" },+ text: "@penguin_test_bot",+ entities: [{ type: "mention", offset: 0, length: 17 }],+ from: { first_name: "Ada" },+ });+ await waitFor(() => fake.allSends().length > 0);+ expect(fake.allSends()[0]!.text).toBe(MESSAGING_TEXT_ONLY_NOTICE);+ expect(runs).toHaveLength(0);+ });+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.diff --git a/packages/server/test/messaging.test.ts b/packages/server/test/messaging.test.tsindex 9bac6d01..084efa5f 100644--- a/packages/server/test/messaging.test.ts+++ b/packages/server/test/messaging.test.ts@@ -72,6 +72,12 @@ class FakeClient implements FeishuApiClient {async replyText(messageId: string, text: string): Promise<void> {this.sends.push({ kind: "reply", target: messageId, text });}+ async botOpenId(): Promise<string | null> {+ this.sdk.botIdentityLookups++;+ // A stalled endpoint: the TCP connection is accepted and the answer never comes.+ if (this.sdk.stallBotOpenId) return new Promise<never>(() => {});+ return this.sdk.botOpenId;+ }}class FakeConnection {@@ -93,6 +99,12 @@ class FakeSdk implements FeishuSdk {readonly connections: FakeConnection[] = [];/** Non-null makes checkCredentials throw with this message. */failCheck: string | null = null;+ /** What `/open-apis/bot/v3/info` reports for this app; null = the identity is unavailable. */+ botOpenId: string | null = null;+ /** Makes that lookup never answer, so a test can prove connect() does not wait on it. */+ stallBotOpenId = false;+ /** Lookups the connector has started (one per connection, off the connect path). */+ botIdentityLookups = 0;async createClient(creds: FeishuCredentials): Promise<FeishuApiClient> {const client = new FakeClient(creds, this);this.clients.push(client);@@ -779,6 +791,174 @@ describe("messaging binding routes and bridge", () => {expect(fake.connections[0]!.closed).toBe(true);});+ // —— Group mentions ————————————————————————————————————————————————————————+ // Feishu never puts a mention in the message text: it writes a placeholder (`@_user_1`)+ // and carries who it refers to alongside. Handed over raw, the model gets a token nothing+ // in the conversation can resolve — and every group message carries one, because+ // addressing a bot in a group means mentioning it.++ const groupMention = (+ text: string,+ mentions: { key: string; name: string; id?: { open_id?: string } }[],+ messageId = "om_mention",+ ) => ({+ chatId: "oc_group_1",+ chatType: "group",+ messageId,+ messageType: "text",+ content: JSON.stringify({ text }),+ mentions: mentions.map((m) => ({+ key: m.key,+ name: m.name,+ ...(m.id?.open_id !== undefined ? { openId: m.id.open_id } : {}),+ })),+ });++ /** The identity lookup rides a background promise, so a test that needs its answer waits for it. */+ const bindWithIdentity = async (sid: string) => {+ fake.botOpenId = "ou_this_bot";+ await bindEnabled(sid);+ await waitFor(() => fake.botIdentityLookups === 1);+ };++ it("resolves mention placeholders to names and drops this bot's own", async () => {+ await bindWithIdentity(SID);+ await fake.lastConnection().fire(+ groupMention("@_user_1 @_user_2 check the build", [+ { key: "@_user_1", name: "PenguinHarness", id: { open_id: "ou_this_bot" } },+ { key: "@_user_2", name: "Alice", id: { open_id: "ou_alice" } },+ ]),+ );+ await waitFor(() => runs.length === 1);+ // The bot's own mention is gone (the model is deliberately not told the message arrived+ // through a chat channel); Alice's is a name the model can actually use.+ expect(runs[0]![0]!.text).toBe("@Alice check the build");+ });++ it("names this bot's mention like any other when its identity is unavailable", async () => {+ // botOpenId stays null: the app cannot report one (bot capability off, or the call+ // failed). Naming beats a raw placeholder, and the connection is never refused over it.+ await bindEnabled(SID);+ await fake+ .lastConnection()+ .fire(+ groupMention("@_user_1 status?", [+ { key: "@_user_1", name: "PenguinHarness", id: { open_id: "ou_this_bot" } },+ ]),+ );+ await waitFor(() => runs.length === 1);+ expect(runs[0]![0]!.text).toBe("@PenguinHarness status?");+ });++ it("replaces the longest placeholder first, so a tenth mention is not corrupted by the first", async () => {+ await bindWithIdentity(SID);+ // Feishu numbers placeholders from 1 up, so @_user_1 is a literal prefix of @_user_10.+ await fake.lastConnection().fire(+ groupMention("@_user_10 and @_user_1 ship it", [+ { key: "@_user_1", name: "Alice", id: { open_id: "ou_alice" } },+ { key: "@_user_10", name: "Jules", id: { open_id: "ou_jules" } },+ ]),+ );+ await waitFor(() => runs.length === 1);+ expect(runs[0]![0]!.text).toBe("@Jules and @Alice ship it");+ });++ it("a message that is nothing but a mention starts no Task", async () => {+ await bindWithIdentity(SID);+ await fake+ .lastConnection()+ .fire(+ groupMention("@_user_1 ", [+ { key: "@_user_1", name: "PenguinHarness", id: { open_id: "ou_this_bot" } },+ ]),+ );+ // Nothing but the mention: no words to run a Task on, so it takes the same branch a+ // sticker does rather than spending a turn on a bare placeholder.+ await waitFor(() => fake.allSends().length === 1);+ expect(fake.allSends()[0]!.text).toBe(MESSAGING_TEXT_ONLY_NOTICE);+ expect(runs).toHaveLength(0);+ });++ it("a direct chat with no mentions is untouched", async () => {+ await bindEnabled(SID);+ await fake.lastConnection().fire({+ chatId: "oc_chat_1",+ chatType: "p2p",+ messageId: "om_plain",+ messageType: "text",+ content: JSON.stringify({ text: "@_user_1 is not a placeholder here" }),+ });+ await waitFor(() => runs.length === 1);+ // No mentions array means nothing to resolve: the text is whatever the user typed,+ // even when it happens to look like a placeholder.+ expect(runs[0]![0]!.text).toBe("@_user_1 is not a placeholder here");+ });++ it("names this bot's mention when it is not the addressing prefix", async () => {+ await bindWithIdentity(SID);+ await fake+ .lastConnection()+ .fire(+ groupMention("why did @_user_1 stop replying?", [+ { key: "@_user_1", name: "PenguinHarness", id: { open_id: "ou_this_bot" } },+ ]),+ );+ await waitFor(() => runs.length === 1);+ // Only the addressing prefix is dropped. Named mid-sentence, this bot is a word the user+ // chose — cutting it would hand the model a sentence with a hole (and a double space) in it.+ expect(runs[0]![0]!.text).toBe("why did @PenguinHarness stop replying?");+ });++ it("substitutes over the original text, never over its own output", async () => {+ await bindWithIdentity(SID);+ // A display name that reads like another key: substituting key by key would let the+ // `@_user_10` round rewrite what the `@_user_1` round had just written.+ await fake.lastConnection().fire(+ groupMention("@_user_1 and @_user_10 ship it", [+ { key: "@_user_1", name: "Alice", id: { open_id: "ou_alice" } },+ { key: "@_user_10", name: "_user_1", id: { open_id: "ou_weird" } },+ ]),+ );+ await waitFor(() => runs.length === 1);+ expect(runs[0]![0]!.text).toBe("@Alice and @_user_1 ship it");+ });++ it("leaves a repeat of a key alone: Feishu emits each one once, so the rest is typed text", async () => {+ await bindWithIdentity(SID);+ await fake+ .lastConnection()+ .fire(+ groupMention("@_user_1 why did you say @_user_1 to me?", [+ { key: "@_user_1", name: "PenguinHarness", id: { open_id: "ou_this_bot" } },+ ]),+ );+ await waitFor(() => runs.length === 1);+ // The head placeholder is this bot's own mention; the second is eight characters the user+ // typed by hand, and they reach the model as typed.+ expect(runs[0]![0]!.text).toBe("why did you say @_user_1 to me?");+ });++ it("connects without waiting for the bot-identity lookup to answer", async () => {+ // The lookup is an HTTP round trip with no timeout under it, and every enabled binding+ // connects on the server's boot path: an endpoint that accepts TCP and then says nothing+ // must not keep the HTTP listener from ever binding.+ fake.stallBotOpenId = true;+ fake.botOpenId = "ou_this_bot";+ await bindEnabled(SID);+ await waitFor(() => fake.botIdentityLookups === 1);+ await fake+ .lastConnection()+ .fire(+ groupMention("@_user_1 status?", [+ { key: "@_user_1", name: "PenguinHarness", id: { open_id: "ou_this_bot" } },+ ]),+ );+ await waitFor(() => runs.length === 1);+ // The connection is live with the identity still outstanding, so this bot's mention is+ // named like anyone else's — the degraded mode an app that cannot report one already has.+ expect(runs[0]![0]!.text).toBe("@PenguinHarness status?");+ });+// —— Inbound deduplication ————————————————————————————————————————————————// A channel can hand the bridge the same message twice: a Feishu long connection// replays across a reconnect, and any connector that resumes an unconfirmed stream can