Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(telegram): preserve rich text limits and structured semantics
Dash73c2c2310cd3
diff --git a/docs/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.mdindex f52e127d09..22b7aecd12 100644--- a/docs/product-rules/telegram-bot-parity.md+++ b/docs/product-rules/telegram-bot-parity.md@@ -13,7 +13,9 @@ Cindy 有两个 Telegram bot,用户看到的是同一个产品:2026-10-28 入站引用:个人 bot 的 `telegram/messageText.ts` 与官方服务端同名投影按`quote.text` → 原消息 `text` / `caption` / `rich_message.blocks` 提取可见正文;群窗口也-读取富文本块。引用关系独立于正文:原消息无可读文字时仍携带原消息 ID 和缺失说明,+读取富文本块;列表保留勾选状态,表格保留空列及合并行列占位。遍历预算与文字上限分开,+允许官方上限内的 500 个块和 16 层格式包装,异常深度与处理量仍有界。+引用关系独立于正文:原消息无可读文字时仍携带原消息 ID 和缺失说明,个人侧已识别的纯附件继续使用类型占位;受保护原消息仍不导出。原消息 ID 与触发消息ID 分开保存。官方在入队前组装引用,沿用既有任务持久化恢复;普通群窗口中继仍只送在线桌面。两仓分别维护投影与回归测试,客户端升级不能代替官方服务端部署。diff --git a/packages/lizi-im/src/telegram/__tests__/inbound.test.ts b/packages/lizi-im/src/telegram/__tests__/inbound.test.tsindex d0cc860f32..b28d016bd9 100644--- a/packages/lizi-im/src/telegram/__tests__/inbound.test.ts+++ b/packages/lizi-im/src/telegram/__tests__/inbound.test.ts@@ -1,7 +1,12 @@import { describe, expect, it } from 'vitest';import type { TgMessage } from '../api.js';-import { detectGroupTrigger, groupWindowEntryOf, laneThreadIdOf, replyContextOf } from '../inbound.js';+import {+ detectGroupTrigger,+ groupWindowEntryOf,+ laneThreadIdOf,+ replyContextOf,+} from '../inbound.js';const BOT_ID = 999;const BOT_USERNAME = 'my_cindy_bot';@@ -18,23 +23,31 @@ function msg(overrides: Partial<TgMessage> = {}): TgMessage {}describe('detectGroupTrigger', () => {- it.each(['Cindy 赞助', 'Cindy 现在也有', 'cindy 帮我看看', 'Cindy', ' Cindy?', '我问过 Cindy 了'])(- '仅提到显示名不触发:%s',+ it.each([+ 'Cindy 赞助',+ 'Cindy 现在也有',+ 'cindy 帮我看看',+ 'Cindy',+ ' Cindy?',+ '我问过 Cindy 了',+ ])('仅提到显示名不触发:%s', (text) => {+ expect(detectGroupTrigger(msg({ text }), BOT_ID, BOT_USERNAME, 'Cindy')).toBeNull();+ expect(+ detectGroupTrigger(msg({ text: undefined, caption: text }), BOT_ID, BOT_USERNAME, 'Cindy'),+ ).toBeNull();+ });++ it.each(['@CindyOther', '@Cindy_bot', '@Cindy2'])(+ '提及以显示名开头的其它账号不触发:%s',(text) => {expect(detectGroupTrigger(msg({ text }), BOT_ID, BOT_USERNAME, 'Cindy')).toBeNull();- expect(- detectGroupTrigger(msg({ text: undefined, caption: text }), BOT_ID, BOT_USERNAME, 'Cindy'),- ).toBeNull();},);- it.each(['@CindyOther', '@Cindy_bot', '@Cindy2'])('提及以显示名开头的其它账号不触发:%s', (text) => {- expect(detectGroupTrigger(msg({ text }), BOT_ID, BOT_USERNAME, 'Cindy')).toBeNull();- });-it('保留显式 @显示名的兼容入口', () => {- expect(detectGroupTrigger(msg({ text: '@Cindy 帮我看看' }), BOT_ID, BOT_USERNAME, 'Cindy'))- .toEqual({ text: '帮我看看' });+ expect(+ detectGroupTrigger(msg({ text: '@Cindy 帮我看看' }), BOT_ID, BOT_USERNAME, 'Cindy'),+ ).toEqual({ text: '帮我看看' });});it('@bot 提及触发并剥掉提及', () => {@@ -251,16 +264,56 @@ describe('replyContextOf', () => {expect(replyContextOf(m)).toBeNull();});- it('keeps all 500 short paragraphs without charging absent fields to the node budget', () => {+ it('keeps 500 paragraphs with 16 levels of inline formatting in replies and history', () => {const lines = Array.from({ length: 500 }, (_, i) => `段落 ${i}`);const rich = msg({text: undefined,- rich_message: { blocks: lines.map((text) => ({ type: 'paragraph', text })) },+ rich_message: {+ blocks: lines.map((text) => {+ let formatted: unknown = text;+ for (let i = 0; i < 16; i++) formatted = { type: 'bold', text: [formatted] };+ return { type: 'paragraph', text: formatted };+ }),+ },});expect(replyContextOf(msg({ reply_to_message: rich }))?.text).toBe(lines.join('\n'));expect(groupWindowEntryOf(rich).text).toBe(lines.join('\n'));});+ it('preserves checkbox state and merged table coordinates in replies and history', () => {+ const rich = msg({+ text: undefined,+ rich_message: {+ blocks: [+ {+ type: 'list',+ items: [+ {+ label: '-',+ has_checkbox: true,+ is_checked: true,+ blocks: [{ type: 'paragraph', text: 'Done' }],+ },+ { label: '-', has_checkbox: true, blocks: [{ type: 'paragraph', text: 'Todo' }] },+ { label: '1.', is_checked: true, blocks: [{ type: 'paragraph', text: 'Plain' }] },+ ],+ },+ {+ type: 'table',+ cells: [+ [{ text: 'A', colspan: 2, rowspan: 2 }, { text: 'C1' }],+ [{ text: 'C2' }],+ [{ text: 'A3' }, {}, { text: 'C3' }],+ ],+ },+ ],+ },+ });+ const expected = '- [x] Done\n- [ ] Todo\n1. Plain\nA\t\tC1\n\t\tC2\nA3\t\tC3';+ expect(replyContextOf(msg({ reply_to_message: rich }))?.text).toBe(expected);+ expect(groupWindowEntryOf(rich).text).toBe(expected);+ });+it('reports unreadable rich references and bounds deeply nested or long content', () => {const rich = msg({text: undefined,@@ -271,10 +324,12 @@ describe('replyContextOf', () => {for (let i = 0; i < 100; i++) nested = { type: 'bold', text: nested };rich.rich_message = { blocks: [{ type: 'paragraph', text: nested }] };expect(groupWindowEntryOf(rich).text).toBe('');- rich.rich_message = { blocks: [- ...Array(3000).fill({ type: 'unknown', metadata: 'not-visible' }),- { type: 'paragraph', text: 'past budget' },- ] };+ rich.rich_message = {+ blocks: [+ ...Array(3000).fill({ type: 'unknown', metadata: 'not-visible' }),+ { type: 'paragraph', text: 'past budget' },+ ],+ };expect(groupWindowEntryOf(rich).text).toBe('');rich.rich_message = {blocks: [{ type: 'paragraph', text: 'x'.repeat(100_000) }],@@ -289,7 +344,11 @@ describe('replyContextOf', () => {text: '昨天的部署日志在这',}),});- expect(replyContextOf(m)).toEqual({ messageId: '1', author: 'Bob', text: '昨天的部署日志在这' });+ expect(replyContextOf(m)).toEqual({+ messageId: '1',+ author: 'Bob',+ text: '昨天的部署日志在这',+ });});it('回复 bot 的消息标 isBot', () => {@@ -299,7 +358,12 @@ describe('replyContextOf', () => {text: '已完成',}),});- expect(replyContextOf(m)).toEqual({ messageId: '1', author: 'Cindy', text: '已完成', isBot: true });+ expect(replyContextOf(m)).toEqual({+ messageId: '1',+ author: 'Cindy',+ text: '已完成',+ isBot: true,+ });});it('纯附件回复给类型占位; 正文不可读仍保留原消息 ID', () => {@@ -319,7 +383,8 @@ describe('replyContextOf', () => {expect(replyContextOf(docReply)?.text).toBe('[文件: a.pdf]');const empty = msg({ reply_to_message: msg({ message_id: 42, text: undefined }) });expect(replyContextOf(empty)).toMatchObject({- messageId: '42', text: '[引用消息的正文无法读取]',+ messageId: '42',+ text: '[引用消息的正文无法读取]',});expect(replyContextOf(msg())).toBeNull();});diff --git a/packages/lizi-im/src/telegram/messageText.ts b/packages/lizi-im/src/telegram/messageText.tsindex 027a6fe229..0e440c1c17 100644--- a/packages/lizi-im/src/telegram/messageText.ts+++ b/packages/lizi-im/src/telegram/messageText.ts@@ -9,16 +9,21 @@ export interface TelegramTextContent {}const MAX_TEXT = 16_384;+const MAX_BLOCKS = 500;+const MAX_COLUMNS = 20;+// Bot API permits 16 semantic nesting levels. JSON arrays/objects add levels+// of their own; budget work independently of the visible output length.+const MAX_DEPTH = 64;+const MAX_NODES = 32_768 * MAX_DEPTH;export function telegramMessageText(message: TelegramTextContent): string {if (message.text?.trim()) return message.text;if (message.caption?.trim()) return message.caption;let remaining = MAX_TEXT;- let nodes = 2048;- function visit(value: unknown, depth = 0, separator = '', childSeparator = ''): string {- // Missing optional fields are not nodes in the incoming document.+ let nodes = MAX_NODES;+ function visit(value: unknown, depth = 0, separator = ''): string {+ if (depth > MAX_DEPTH || --nodes < 0 || remaining <= 0) return '';if (value === undefined || value === null) return '';- if (depth > 20 || --nodes < 0 || remaining <= 0) return '';if (typeof value === 'string') {const text = value.slice(0, remaining);remaining -= text.length;@@ -26,11 +31,11 @@ export function telegramMessageText(message: TelegramTextContent): string {}if (Array.isArray(value)) {const parts: string[] = [];- for (const item of value) {+ const items = separator === '\n' ? value.slice(0, MAX_BLOCKS) : value;+ for (const item of items) {if (nodes <= 0 || remaining <= 0) break;- const text = visit(item, depth + 1, childSeparator);- // Empty cells still occupy a column in a table row.- if (text || separator === '\t') parts.push(text);+ const text = visit(item, depth + 1);+ if (text) parts.push(text);}return parts.join(separator);}@@ -44,14 +49,44 @@ export function telegramMessageText(message: TelegramTextContent): string {if (item.type === 'mathematical_expression') return visit(item.expression, depth + 1);if (item.type === 'custom_emoji') return visit(item.alternative_text, depth + 1);if (item.type === 'button') return visit(item.button, depth + 1);- // https://core.telegram.org/bots/api#richblocktable: cells is a row matrix.+ // Tables use HTML-style spans: reserve covered columns/rows, including+ // empty cells, rather than sliding subsequent values into the wrong column.if (item.type === 'table') {- return [visit(item.cells, depth + 1, '\n', '\t'), visit(item.caption, depth + 1)]- .filter(Boolean)- .join('\n');+ const rows: string[] = [];+ const occupiedUntil: number[] = Array(MAX_COLUMNS).fill(0);+ if (Array.isArray(item.cells)) {+ for (const [rowIndex, row] of item.cells.slice(0, MAX_BLOCKS).entries()) {+ if (nodes <= 0 || remaining <= 0) break;+ if (!Array.isArray(row)) continue;+ const cells: string[] = [];+ for (const cell of row) {+ while (cells.length < MAX_COLUMNS && occupiedUntil[cells.length] > rowIndex) {+ cells.push('');+ }+ if (cells.length >= MAX_COLUMNS || nodes <= 0 || remaining <= 0) break;+ const column = cells.length;+ const span = (key: 'colspan' | 'rowspan', limit: number): number => {+ const value = cell && typeof cell === 'object' ? cell[key] : undefined;+ return Number.isInteger(value) && value > 1 ? Math.min(value, limit) : 1;+ };+ const columns = span('colspan', MAX_COLUMNS - column);+ const until = rowIndex + span('rowspan', MAX_BLOCKS - rowIndex);+ cells.push(visit(cell, depth + 3), ...Array(columns - 1).fill(''));+ occupiedUntil.fill(until, column, column + columns);+ }+ for (let column = cells.length; column < MAX_COLUMNS; column++) {+ if (occupiedUntil[column] > rowIndex) {+ while (cells.length <= column) cells.push('');+ }+ }+ rows.push(cells.join('\t'));+ }+ }+ return [rows.join('\n'), visit(item.caption, depth + 1)].filter(Boolean).join('\n');}if (typeof item.label === 'string' && Array.isArray(item.blocks)) {- return [visit(item.label, depth + 1), visit(item.blocks, depth + 1, '\n')]+ const checkbox = item.has_checkbox === true ? (item.is_checked === true ? '[x]' : '[ ]') : '';+ return [visit(item.label, depth + 1), checkbox, visit(item.blocks, depth + 1, '\n')].filter(Boolean).join(' ');}@@ -59,6 +94,8 @@ export function telegramMessageText(message: TelegramTextContent): string {// their boundaries. Do not return early on text: captions/quotes have credit.const parts: string[] = [];for (const key of ['text', 'summary', 'blocks', 'items', 'caption', 'credit', 'buttons']) {+ // Missing optional fields do not consume the traversal budget.+ if (item[key] === undefined || item[key] === null) continue;const separator = key === 'blocks' || key === 'items' || key === 'buttons' ? '\n' : '';const text = visit(item[key], depth + 1, separator);if (text) parts.push(text);