Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(feishu): bound quote notes and history expansion reads
Chris8299828adced
diff --git a/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts b/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.tsindex b45cb0cd05..357e674403 100644--- a/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts+++ b/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts@@ -476,6 +476,28 @@ describe('feishu group lane adapter hooks', () => {expect(downloadMessageAttachments).toHaveBeenCalledWith('om_child', [{ kind: 'image', imageKey: 'img_child', messageId: 'om_child' }]);});+ // Unit regression r4374812155: many long filenames used to grow both model+ // facts and the display snapshot without a bound; previous cases had one image.+ it('bounds unavailable quote descriptions and summarizes excess attachments', async () => {+ downloadMessageAttachments.mockClear();+ scopeMocks.utilityText.mockResolvedValueOnce({ ok: true, text: 'NONE' });+ for (let i = 0; i < 4; i++) {+ downloadMessageAttachments.mockResolvedValueOnce({ attachments: [], unsupported: [{ type: 'file', label: 'failure '.repeat(1000) }] });+ }+ const result = await adapter.prepareAgentTurnText?.(groupEvent({+ senderId: 'ou_owner',+ replyContext: { author: 'Alice', text: 'Readable quoted record' },+ feishuReplyAttachments: Array.from({ length: 100 }, (_, i) => ({+ kind: 'file' as const, fileKey: `file_${i}`, messageId: `om_${i}`, fileName: 'long-name'.repeat(1000),+ })),+ }));+ expect(downloadMessageAttachments).toHaveBeenCalledTimes(4);+ expect(JSON.stringify(result?.replyContext?.unavailableAttachments).length).toBeLessThanOrEqual(1000);+ expect(result?.replyContext?.unavailableAttachments?.at(-1)).toContain('96');+ expect(result?.agentText).toContain('Readable quoted record');+ expect(result?.contextSnapshot?.replyContext?.length).toBeLessThan(1500);+ });+it('does not download filtered quote resources and reports failed downloads for accepted quotes', async () => {downloadMessageAttachments.mockClear();const refs = [{ kind: 'image' as const, imageKey: 'img_child', messageId: 'om_child' }];diff --git a/apps/desktop/src/main/im/feishu/__tests__/groupContext.test.ts b/apps/desktop/src/main/im/feishu/__tests__/groupContext.test.tsindex 9e3c244235..2a7688014b 100644--- a/apps/desktop/src/main/im/feishu/__tests__/groupContext.test.ts+++ b/apps/desktop/src/main/im/feishu/__tests__/groupContext.test.ts@@ -101,8 +101,12 @@ describe('buildFeishuGroupContext 分页与相关性早停', () => {// 第二页请求带上了第一页的 pageTokenexpect(fetchPage).toHaveBeenNthCalledWith(2,- expect.objectContaining({ pageToken: 'tok2', pageSize: HISTORY_PAGE_SIZE }),+ expect.objectContaining({ pageToken: 'tok2', pageSize: HISTORY_PAGE_SIZE, excludeMessageId: 'om_trigger' }),);+ // The transport's read allowance must survive pagination, rather than reset+ // per page (r4374812162). Other protocol behavior is covered in outboundLane.+ expect(fetchPage.mock.calls[1]?.[0].mergeForwardReadBudget).toBe(fetchPage.mock.calls[0]?.[0].mergeForwardReadBudget);+ expect(fetchPage.mock.calls[0]?.[0].mergeForwardReadBudget).toEqual({ remaining: 20 });});it('judge 恒相关时最多翻 HISTORY_MAX_PAGES 页', async () => {diff --git a/apps/desktop/src/main/im/feishu/adapter.ts b/apps/desktop/src/main/im/feishu/adapter.tsindex ec65d0f099..59738b4017 100644--- a/apps/desktop/src/main/im/feishu/adapter.ts+++ b/apps/desktop/src/main/im/feishu/adapter.ts@@ -460,25 +460,41 @@ export function buildFeishuAdapter(if (!filtered) {let images = 0;let files = 0;- const unavailable = [...(safeReply.unavailableAttachments ?? [])];+ // These notes also enter messageHandler's inbound facts. Bound the+ // structured value itself, rather than only its display rendering.+ const unavailable: string[] = [];+ let unavailableChars = 2; // JSON array brackets+ let omitted = 0;+ const addUnavailable = (description: string) => {+ const note = description.slice(0, 160);+ const size = JSON.stringify(note).length + 1;+ if (unavailableChars + size > 900) {+ omitted++;+ return;+ }+ unavailable.push(note);+ unavailableChars += size;+ };+ for (const note of safeReply.unavailableAttachments ?? []) addUnavailable(note);for (const ref of event.feishuReplyAttachments ?? []) {- const label = ref.kind === 'image' ? '引用图片' : `引用文件 ${ref.fileName}`;const overLimit = ref.kind === 'image' ? images++ >= HISTORY_IMAGE_MAX : files++ >= HISTORY_FILE_MAX;if (!ref.messageId || overLimit) {- unavailable.push(`${label}:超出本轮附件数量上限或缺少来源`);+ omitted++;continue;}+ const label = ref.kind === 'image' ? '引用图片' : `引用文件 ${ref.fileName.slice(0, 80)}`;try {const downloaded = await feishuIm.downloadMessageAttachments(ref.messageId, [ref]);contextAttachments.push(...downloaded.attachments);- unavailable.push(...downloaded.unsupported.map((entry) => `${label}:${entry.label}`));+ for (const entry of downloaded.unsupported) addUnavailable(`${label}:${entry.label}`);if (!downloaded.attachments.length && !downloaded.unsupported.length) {- unavailable.push(`${label}:未能下载`);+ addUnavailable(`${label}:未能下载`);}} catch {- unavailable.push(`${label}:下载失败`);+ addUnavailable(`${label}:下载失败`);}}+ if (omitted) unavailable.push(`另有 ${omitted} 条引用附件未提供说明已省略(含超出数量上限或缺少来源的附件)`);if (contextAttachments.length) safeReply.attachmentCount = contextAttachments.length;if (unavailable.length) safeReply.unavailableAttachments = unavailable;}diff --git a/apps/desktop/src/main/im/feishu/groupContext.ts b/apps/desktop/src/main/im/feishu/groupContext.tsindex 399a82dd2b..0744cbe37f 100644--- a/apps/desktop/src/main/im/feishu/groupContext.ts+++ b/apps/desktop/src/main/im/feishu/groupContext.ts@@ -91,6 +91,8 @@ export interface FeishuGroupContextDeps {threadId?: string;pageToken?: string;pageSize?: number;+ excludeMessageId?: string;+ mergeForwardReadBudget?: { remaining: number };}) => Promise<FeishuChatHistoryPage>;/** 下载某条历史消息的附件(单附件失败隔离进 unsupported)。 */download: (messageId: string, refs: FeishuAttachmentRef[]) => Promise<FeishuDownloadResult>;@@ -247,6 +249,7 @@ export async function buildFeishuGroupContext(args: {// 纯附件触发没有问题文本作判断依据, 只取最新一页。const latestPageOnly = question.trim().length === 0;const keptPages: FeishuRecentChatMessage[][] = [];+ const mergeForwardReadBudget = { remaining: 20 };let pageToken: string | undefined;try {for (let pageIdx = 0; pageIdx < HISTORY_MAX_PAGES; pageIdx++) {@@ -255,6 +258,8 @@ export async function buildFeishuGroupContext(args: {threadId: lane.threadId || undefined,pageToken,pageSize: HISTORY_PAGE_SIZE,+ excludeMessageId: triggerMessageId,+ mergeForwardReadBudget,});// thread 容器只回本话题消息, 无需再过滤; chat 容器混入话题消息,// 群主流 lane 只取 threadId 为空的(话题消息归各话题 lane)。diff --git a/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts b/packages/lizi-im/src/feishu/__tests__/outboundLane.test.tsindex 9cbfe1fe47..498e403b5b 100644--- a/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts@@ -528,6 +528,43 @@ describe('feishu outbound lane routing', () => {});});+ // Unit regressions r4374812162, through the production history entry: excluded+ // envelopes must cause no reads, and nested reads must share the turn's budget.+ it('excludes the trigger and other topics before expanding merged history', async () => {+ larkMocks.list.mockResolvedValueOnce({ code: 0, data: { items: [+ { message_id: 'om_trigger', chat_id: 'oc_group1', thread_id: '', msg_type: 'merge_forward' },+ { message_id: 'om_other_topic', chat_id: 'oc_group1', thread_id: 'omt_other', msg_type: 'merge_forward' },+ { message_id: 'om_kept', chat_id: 'oc_group1', thread_id: '', msg_type: 'text', body: { content: '{"text":"retained"}' } },+ ] } });+ const result = await outbound.fetchChatHistoryPage({ chatId: 'oc_group1', excludeMessageId: 'om_trigger' });+ expect(result.messages.map((item) => item.text)).toEqual(['retained']);+ expect(larkMocks.getMessage).not.toHaveBeenCalled();+ });++ it('shares merged-history reads across nested envelopes and pages', async () => {+ const mergeForwardReadBudget = { remaining: 2 };+ larkMocks.list.mockResolvedValueOnce({ code: 0, data: { items: [+ { message_id: 'om_bundle', chat_id: 'oc_group1', thread_id: '', msg_type: 'merge_forward' },+ ] } });+ larkMocks.getMessage.mockResolvedValueOnce({ code: 0, data: { items: [+ { message_id: 'om_bundle', chat_id: 'oc_group1', msg_type: 'merge_forward' },+ { message_id: 'om_nested', upper_message_id: 'om_bundle', msg_type: 'merge_forward' },+ ] } });+ larkMocks.getMessage.mockResolvedValueOnce({ code: 0, data: { items: [+ { message_id: 'om_nested', msg_type: 'merge_forward' },+ { message_id: 'om_child', upper_message_id: 'om_nested', msg_type: 'text', body: { content: '{"text":"nested record"}' } },+ ] } });+ const first = await outbound.fetchChatHistoryPage({ chatId: 'oc_group1', mergeForwardReadBudget });+ expect(first.messages[0]?.text).toContain('nested record');+ larkMocks.list.mockResolvedValueOnce({ code: 0, data: { items: [+ { message_id: 'om_older_bundle', chat_id: 'oc_group1', thread_id: '', msg_type: 'merge_forward' },+ { message_id: 'om_text', chat_id: 'oc_group1', thread_id: '', msg_type: 'text', body: { content: '{"text":"older text"}' } },+ ] } });+ const second = await outbound.fetchChatHistoryPage({ chatId: 'oc_group1', pageToken: 'older', mergeForwardReadBudget });+ expect(second.messages.map((item) => item.text)).toEqual(['older text', '[合并转发消息:读取预算已用完]']);+ expect(larkMocks.getMessage).toHaveBeenCalledTimes(2);+ });+it('keeps an unreadable merged forward visible rather than dropping it', async () => {larkMocks.getMessage.mockResolvedValueOnce({ code: 0, data: { items: [{ message_id: 'om_empty', chat_id: 'oc_group1', msg_type: 'merge_forward' },diff --git a/packages/lizi-im/src/feishu/index.ts b/packages/lizi-im/src/feishu/index.tsindex 4ca4b7bf7c..3e0738f69b 100644--- a/packages/lizi-im/src/feishu/index.ts+++ b/packages/lizi-im/src/feishu/index.ts@@ -825,12 +825,7 @@ export class FeishuIM extends BaseIM implements ChannelIM {* threadId 走 thread 容器。**权限不足/调用失败直接抛错** — 调用方据此* 区分「无历史」与「拉取失败」并给 owner 可见提示;turn 降级照跑由调用方兜。*/- fetchChatHistoryPage(args: {- chatId: string;- threadId?: string;- pageToken?: string;- pageSize?: number;- }): Promise<outbound.ChatHistoryPage> {+ fetchChatHistoryPage(args: Parameters<typeof outbound.fetchChatHistoryPage>[0]): Promise<outbound.ChatHistoryPage> {return outbound.fetchChatHistoryPage(args);}diff --git a/packages/lizi-im/src/feishu/outbound.ts b/packages/lizi-im/src/feishu/outbound.tsindex 81252bf55a..b72319f2c6 100644--- a/packages/lizi-im/src/feishu/outbound.ts+++ b/packages/lizi-im/src/feishu/outbound.ts@@ -1810,9 +1810,12 @@ async function resolveReplyWithClient(c: Lark.Client,messageId: string,expectedChatId: string,+ readBudget = { remaining: 21 },): Promise<ResolvedReplyMessage | null> {const log = getLog();try {+ if (readBudget.remaining <= 0) return null;+ readBudget.remaining--;const res = await c.im.v1.message.get({params: { user_id_type: 'open_id', with_sender_name: true },path: { message_id: messageId },@@ -1830,7 +1833,6 @@ async function resolveReplyWithClient(.replace(/[\p{Cc}\p{Cf}]/gu, ' ').trim().slice(0, 64);const attachments: AttachmentRef[] = [];const visited = new Set<string>();- let nestedFetches = 0;const render = async (item: typeof root): Promise<string> => {if (!item.message_id || item.deleted || visited.has(item.message_id)) return '';// The envelope is checked against the triggering chat above. Forwarded@@ -1840,8 +1842,9 @@ async function resolveReplyWithClient(let children = items.filter((child) => child.upper_message_id === item.message_id);// Some responses include only the immediate level. Fetch deeper envelopes// with the same client; never follow arbitrary message IDs from body text.- if (!children.length && item !== root && nestedFetches++ < 20) {+ if (!children.length && item !== root && readBudget.remaining > 0) {try {+ readBudget.remaining--;const nested = await c.im.v1.message.get({params: { user_id_type: 'open_id', with_sender_name: true },path: { message_id: item.message_id },@@ -1862,7 +1865,8 @@ async function resolveReplyWithClient(const text = await render(child);if (text) lines.push(`[${authorOf(child)}] ${text}`);}- return lines.length ? `[合并转发消息]\n${lines.join('\n')}` : '[合并转发消息:未能读取子消息]';+ return lines.length ? `[合并转发消息]\n${lines.join('\n')}`+ : readBudget.remaining <= 0 ? '[合并转发消息:读取预算已用完]' : '[合并转发消息:未能读取子消息]';}const parsed = parseIncoming(item.msg_type ?? '', item.body?.content ?? '');attachments.push(...parsed.attachments.map((ref) => ({ ...ref, messageId: item.message_id })));@@ -1908,8 +1912,7 @@ export interface ChatHistoryPage {/*** 按页拉群/话题历史(群 lane 触发时 adapter 拼上下文用)。倒序拉一页, 返回- * 页内升序。话题 lane 传 threadId 走 thread 容器, 只回本话题消息; 群主流- * 不传, 调用方自行按 thread_id 过滤(chat 容器会混入话题消息)。+ * 页内升序。展开转发前按 threadId 筛选; 缺省只保留群主流。** 需要「获取群组中所有消息」权限。**失败(权限不足/网络)直接抛错** — 调用方* 需要区分「真的没有历史」与「拉取失败」来做降级提示, 不能吞成空数组。@@ -1920,6 +1923,9 @@ export async function fetchChatHistoryPage(args: {threadId?: string;pageToken?: string;pageSize?: number;+ excludeMessageId?: string;+ /** Mutable per-turn allowance, shared by every page and nested message.get. */+ mergeForwardReadBudget?: { remaining: number };}): Promise<ChatHistoryPage> {const c = S().client;if (!c) throw new Error('feishu client not bound');@@ -1938,15 +1944,18 @@ export async function fetchChatHistoryPage(args: {}const items = res.data?.items ?? [];const out: RecentChatMessage[] = [];+ const readBudget = args.mergeForwardReadBudget ?? { remaining: 20 };for (const item of items) {if (!item.message_id || item.deleted) continue;+ if (item.message_id === args.excludeMessageId || (item.thread_id ?? '') !== (args.threadId ?? '')) continue;const msgType = item.msg_type ?? '';const rawContent = item.body?.content ?? '';let text = '';let attachments: AttachmentRef[] = [];if (msgType === 'merge_forward') {- const resolved = await resolveReplyWithClient(c, item.message_id, args.chatId);- text = resolved?.replyContext.text ?? '[合并转发消息:读取失败]';+ const exhausted = readBudget.remaining <= 0;+ const resolved = exhausted ? null : await resolveReplyWithClient(c, item.message_id, args.chatId, readBudget);+ text = resolved?.replyContext.text ?? (exhausted ? '[合并转发消息:读取预算已用完]' : '[合并转发消息:读取失败]');attachments = resolved?.attachments ?? [];} else if (msgType === 'text' ||