Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(im): 飞书超长助手回复不再静默丢失 (#1160)

Chris Zhange9866cbfab7e
diff --git a/packages/lizi-im/src/feishu/__tests__/streamingText.test.ts b/packages/lizi-im/src/feishu/__tests__/streamingText.test.ts
new file mode 100644
index 0000000000..97ee5484d5
--- /dev/null
+++ b/packages/lizi-im/src/feishu/__tests__/streamingText.test.ts
@@ -0,0 +1,92 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ patchCardRaw: vi.fn(),
+ sendCardRaw: vi.fn(),
+ sendFile: vi.fn(),
+ sendText: vi.fn(),
+ uploadImage: vi.fn(),
+}));
+
+vi.mock('../outbound.js', () => mocks);
+vi.mock('../moduleScope.js', () => ({
+ getLog: () => ({ debug: vi.fn(), error: vi.fn(), warn: vi.fn() }),
+}));
+
+import { messages } from '../messages.js';
+import { FEISHU_CARD_REQUEST_MAX_BYTES, start } from '../streamingText.js';
+
+function markdownContent(card: unknown): string {
+ return (card as { body: { elements: Array<{ content: string }> } }).body.elements[0].content;
+}
+
+function requestBytes(card: unknown): number {
+ return Buffer.byteLength(JSON.stringify({ content: JSON.stringify(card) }), 'utf8');
+}
+
+describe('feishu streaming text', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.sendCardRaw.mockResolvedValue({ messageId: 'om_stream' });
+ mocks.patchCardRaw.mockResolvedValue(undefined);
+ mocks.sendText.mockResolvedValue({ messageId: 'om_fallback' });
+ });
+
+ it('keeps an in-limit final card unchanged', async () => {
+ const handle = await start('ou_owner');
+ await handle.finalize('正常正文');
+
+ expect(markdownContent(mocks.patchCardRaw.mock.calls[0][1])).toBe('正常正文');
+ });
+
+ it('truncates an oversized final card within Feishu request limits', async () => {
+ const handle = await start('ou_owner');
+ const longMarkdown = [
+ '| 列一 | 列二 |',
+ '| --- | --- |',
+ '| 很长的内容 | 更多内容 |',
+ '```ts',
+ 'const answer = "很长的代码块";',
+ '```',
+ ].join('\n').repeat(500);
+ await handle.finalize(longMarkdown);
+
+ const card = mocks.patchCardRaw.mock.calls[0][1];
+ expect(requestBytes(card)).toBeLessThanOrEqual(FEISHU_CARD_REQUEST_MAX_BYTES);
+ expect(markdownContent(card)).toContain('完整内容仍可在 Cindy 桌面端查看');
+ });
+
+ it('uses a bounded plain card when image elements alone exceed the limit', async () => {
+ mocks.uploadImage.mockImplementation(async (path: string) => `${path}-${'x'.repeat(128)}`);
+ const handle = await start('ou_owner');
+ for (let i = 0; i < 200; i++) handle.addExtraImageAbsPath?.(`/tmp/${i}.png`);
+ await handle.finalize('正文');
+
+ const card = mocks.patchCardRaw.mock.calls[0][1];
+ expect(requestBytes(card)).toBeLessThanOrEqual(FEISHU_CARD_REQUEST_MAX_BYTES);
+ expect(markdownContent(card)).toBe(messages.streaming.deliveryFailed);
+ });
+
+ it('patches a short user-visible notice when the final card shape is rejected', async () => {
+ mocks.patchCardRaw.mockRejectedValueOnce(new Error('unsupported card shape'));
+ const handle = await start('ou_owner');
+ await handle.finalize('正文');
+
+ expect(mocks.patchCardRaw).toHaveBeenCalledTimes(2);
+ expect(markdownContent(mocks.patchCardRaw.mock.calls[1][1])).toBe(
+ messages.streaming.deliveryFailed,
+ );
+ expect(mocks.sendText).not.toHaveBeenCalled();
+ });
+
+ it('falls back to plain text when even the short card patch fails', async () => {
+ mocks.patchCardRaw.mockRejectedValue(new Error('card patch unavailable'));
+ const handle = await start('ou_owner');
+ await handle.finalize('正文');
+
+ expect(mocks.sendText).toHaveBeenCalledWith(
+ 'ou_owner',
+ messages.streaming.deliveryFailed,
+ );
+ });
+});
diff --git a/packages/lizi-im/src/feishu/messages.ts b/packages/lizi-im/src/feishu/messages.ts
index d83e97e5c1..45a3aa88a0 100644
--- a/packages/lizi-im/src/feishu/messages.ts
+++ b/packages/lizi-im/src/feishu/messages.ts
@@ -44,6 +44,10 @@ export const messages = {
},
/** Finalize: card text empty AND no files (rare — agent emitted nothing useful). */
emptyReply: '_(空回复)_',
+ replyTruncated:
+ '\n\n---\n⚠️ 回复过长,飞书仅展示前半部分;完整内容仍可在 Cindy 桌面端查看。',
+ deliveryFailed:
+ '⚠️ 这条回复过长或包含飞书暂不支持的内容,请在 Cindy 桌面端查看完整回复。',
},
} as const;
diff --git a/packages/lizi-im/src/feishu/streamingText.ts b/packages/lizi-im/src/feishu/streamingText.ts
index eb9e42fa55..ffbc538434 100644
--- a/packages/lizi-im/src/feishu/streamingText.ts
+++ b/packages/lizi-im/src/feishu/streamingText.ts
@@ -24,7 +24,7 @@
* `[name](xdt-file:///abs/path)`).
*/
-import { sendCardRaw, patchCardRaw, uploadImage, sendFile } from './outbound.js';
+import { sendCardRaw, patchCardRaw, uploadImage, sendFile, sendText } from './outbound.js';
import { buildMarkdownCardV2, buildMixedMarkdownCardV2 } from './cards.js';
import { getLog } from './moduleScope.js';
import { messages as transportMessages } from './messages.js';
@@ -39,6 +39,40 @@ import {
} from '../xdtRefs.js';
const PATCH_THROTTLE_MS = 1500;
+/** Feishu caps serialized card request bodies at 30 KB. */
+export const FEISHU_CARD_REQUEST_MAX_BYTES = 30 * 1024;
+
+function cardRequestBytes(card: unknown): number {
+ return Buffer.byteLength(JSON.stringify({ content: JSON.stringify(card) }), 'utf8');
+}
+
+function fitCardToLimit(
+ text: string,
+ fullCard: unknown,
+ buildCard: (visibleText: string) => unknown,
+): unknown {
+ if (cardRequestBytes(fullCard) <= FEISHU_CARD_REQUEST_MAX_BYTES) return fullCard;
+
+ const chars = Array.from(text);
+ const suffix = transportMessages.streaming.replyTruncated;
+ let low = 0;
+ let high = chars.length;
+ let fitted = buildCard(suffix);
+ if (cardRequestBytes(fitted) > FEISHU_CARD_REQUEST_MAX_BYTES) {
+ return buildMarkdownCardV2(transportMessages.streaming.deliveryFailed);
+ }
+ while (low <= high) {
+ const middle = Math.floor((low + high) / 2);
+ const candidate = buildCard(`${chars.slice(0, middle).join('')}${suffix}`);
+ if (cardRequestBytes(candidate) <= FEISHU_CARD_REQUEST_MAX_BYTES) {
+ fitted = candidate;
+ low = middle + 1;
+ } else {
+ high = middle - 1;
+ }
+ }
+ return fitted;
+}
class FeishuStreamingTextHandle implements StreamingTextHandle {
readonly messageId: string;
@@ -272,11 +306,30 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {
} else {
card = buildMarkdownCardV2(cardTextTrimmed.length > 0 ? cardText : transportMessages.streaming.emptyReply);
}
+ card = fitCardToLimit(cardText, card, (visibleText) =>
+ hasAnyImage
+ ? buildMixedMarkdownCardV2(visibleText, imageMap, extraImageKeys)
+ : buildMarkdownCardV2(visibleText),
+ );
await patchCardRaw(this.messageId, card);
this.flushed = this.buffer;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
log.warn(`[feishu/streamingText] finalize patch failed: ${msg}`);
+ const notice = transportMessages.streaming.deliveryFailed;
+ try {
+ await patchCardRaw(this.messageId, buildMarkdownCardV2(notice));
+ } catch (fallbackErr) {
+ const fallbackMsg =
+ fallbackErr instanceof Error ? fallbackErr.message : String(fallbackErr);
+ log.warn(`[feishu/streamingText] fallback patch failed: ${fallbackMsg}`);
+ try {
+ await sendText(this.openId, notice);
+ } catch (textErr) {
+ const textMsg = textErr instanceof Error ? textErr.message : String(textErr);
+ log.error(`[feishu/streamingText] fallback text failed: ${textMsg}`);
+ }
+ }
}
}
}