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(feishu): 原位更新进度卡展示最终回复

xd8789e0eff75a
diff --git a/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts b/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts
index 498e403b5b..4005340800 100644
--- a/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts
+++ b/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts
@@ -154,12 +154,15 @@ describe('feishu outbound lane routing', () => {
handle.replace('revised');
await vi.advanceTimersByTimeAsync(1500);
await handle.finalize('finished');
- expect(larkMocks.patch).toHaveBeenCalledTimes(2);
+ expect(larkMocks.patch).toHaveBeenCalledTimes(3);
for (const client of larkMocks.patch.mock.contexts) expect(client).toBe(creator);
expect(larkMocks.create.mock.contexts.at(-1)).toBe(creator);
- expect(larkMocks.create).toHaveBeenLastCalledWith(expect.objectContaining({
+ expect(larkMocks.create).toHaveBeenCalledTimes(1);
+ expect(larkMocks.patch).toHaveBeenLastCalledWith(expect.objectContaining({
+ path: { message_id: handle.messageId },
data: expect.objectContaining({ content: expect.stringContaining('finished') }),
}));
+ expect(larkMocks.request).not.toHaveBeenCalled();
},
);
@@ -186,16 +189,36 @@ describe('feishu outbound lane routing', () => {
const handle = await start(lane);
expect(larkMocks.reply.mock.calls[0][0].path).toEqual({ message_id: 'om_first' });
await handle.finalize('answer');
+ if (!thread) expect(larkMocks.reply.mock.calls[0][0].data).not.toHaveProperty('reply_in_thread');
+ expect(larkMocks.reply).toHaveBeenCalledTimes(1);
+ expect(larkMocks.create).not.toHaveBeenCalled();
+ expect(larkMocks.patch).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({
+ path: { message_id: handle.messageId },
+ data: expect.objectContaining({ content: expect.stringContaining('answer') }),
+ }));
+ expect(larkMocks.request).not.toHaveBeenCalled();
+ const next = await start(lane);
+ expect(larkMocks.reply.mock.calls.at(-1)?.[0].path).toEqual({ message_id: 'om_second' });
+ next.close();
+ });
+
+ it.each([false, true])('failed final edit falls back in the same lane without taking the next turn (thread=%s)', async (thread) => {
+ const lane = thread ? 'g/oc_chat/omt_topic' : 'g/oc_chat';
+ outbound.pushReplyAnchor(lane, 'om_first');
+ outbound.pushReplyAnchor(lane, 'om_second');
+ const handle = await start(lane);
+ larkMocks.patch.mockRejectedValueOnce(new Error('card no longer editable'));
+ await handle.finalize('answer');
if (thread) {
expect(larkMocks.reply.mock.calls[1][0].path).toEqual({ message_id: 'om_first' });
expect(larkMocks.create).not.toHaveBeenCalled();
} else {
- expect(larkMocks.reply.mock.calls[0][0].data).not.toHaveProperty('reply_in_thread');
- expect(larkMocks.create).toHaveBeenCalledWith(expect.objectContaining({
+ expect(larkMocks.create).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({
params: { receive_id_type: 'chat_id' },
data: expect.objectContaining({ receive_id: 'oc_chat', content: expect.stringContaining('answer') }),
}));
}
+ expect(larkMocks.request).not.toHaveBeenCalled();
const next = await start(lane);
expect(larkMocks.reply.mock.calls.at(-1)?.[0].path).toEqual({ message_id: 'om_second' });
next.close();
diff --git a/packages/lizi-im/src/feishu/__tests__/streamingText.test.ts b/packages/lizi-im/src/feishu/__tests__/streamingText.test.ts
index 6e4a038d18..59382e347a 100644
--- a/packages/lizi-im/src/feishu/__tests__/streamingText.test.ts
+++ b/packages/lizi-im/src/feishu/__tests__/streamingText.test.ts
@@ -9,7 +9,7 @@ const mocks = vi.hoisted(() => ({
sendFile: vi.fn(),
sendText: vi.fn(),
uploadImage: vi.fn(),
- claimPatchableOpener: vi.fn(() => null),
+ claimPatchableOpener: vi.fn((): string | null => null),
resolveMediaUrl: vi.fn((): string | null => null),
}));
@@ -48,11 +48,15 @@ describe('feishu streaming text', () => {
mocks.resolveMediaUrl.mockReturnValue(null);
});
- it('keeps an in-limit final card unchanged', async () => {
+ it('updates the original card with the final answer without sending or recalling a message', async () => {
const handle = await start('ou_owner');
await handle.finalize('正常正文');
- expect(markdownContent(mocks.sendCardRaw.mock.calls[1][1])).toBe('正常正文');
+ expect(mocks.patchCardRaw).toHaveBeenCalledExactlyOnceWith('om_stream', expect.anything());
+ expect(markdownContent(mocks.patchCardRaw.mock.calls[0][1])).toBe('正常正文');
+ expect(mocks.sendCardRaw).toHaveBeenCalledTimes(1);
+ expect(mocks.recallMessage).not.toHaveBeenCalled();
+ expect(handle.messageId).toBe('om_stream');
});
it.each(['', ' \n '])('recalls an empty final %j without a placeholder', async (text) => {
@@ -76,8 +80,10 @@ describe('feishu streaming text', () => {
handle.addExtraImageAbsPath?.('/tmp/image.png');
await handle.finalize('');
expect(mocks.uploadImage).toHaveBeenCalledWith('/tmp/image.png');
- expect(mocks.sendCardRaw).toHaveBeenCalledTimes(2);
- expect(mocks.recallMessage).toHaveBeenCalledWith('om_stream');
+ expect(mocks.sendCardRaw).toHaveBeenCalledTimes(1);
+ const card = mocks.patchCardRaw.mock.calls[0][1];
+ expect(card.body.elements).toEqual([expect.objectContaining({ tag: 'img', img_key: 'image_key' })]);
+ expect(mocks.recallMessage).not.toHaveBeenCalled();
});
it('truncates an oversized final card within Feishu request limits', async () => {
@@ -92,33 +98,49 @@ describe('feishu streaming text', () => {
].join('\n').repeat(500);
await handle.finalize(longMarkdown);
- const card = mocks.sendCardRaw.mock.calls[1][1];
+ const card = mocks.patchCardRaw.mock.calls[0][1];
expect(requestBytes(card)).toBeLessThanOrEqual(FEISHU_CARD_REQUEST_MAX_BYTES);
expect(markdownContent(card)).toContain('完整内容仍可在 Cindy 桌面端查看');
});
+ it('delivers a file separately and updates the original card with its receipt', async () => {
+ const handle = await start('ou_owner');
+ await handle.finalize('[report.txt](xdt-file:///tmp/report.txt)');
+ expect(mocks.sendFile).toHaveBeenCalledExactlyOnceWith('ou_owner', '/tmp/report.txt', 'report.txt', undefined);
+ expect(mocks.patchCardRaw).toHaveBeenCalledExactlyOnceWith('om_stream', expect.anything());
+ expect(markdownContent(mocks.patchCardRaw.mock.calls[0][1])).toBe(messages.streaming.fileSentDone(1));
+ expect(mocks.sendCardRaw).toHaveBeenCalledTimes(1);
+ expect(mocks.recallMessage).not.toHaveBeenCalled();
+ });
+
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.sendCardRaw.mock.calls[1][1];
+ 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('preserves the full final on the progress card if sending a new message fails', async () => {
- const handle = await start('ou_owner');
- mocks.sendCardRaw.mockRejectedValueOnce(new Error('send unavailable'));
+ // Regression for PR #6817: start/finalize must edit the existing message.
+ // Unit tier; the previous tests asserted fresh delivery and missed recall notices.
+ it('sends the full final only as a fallback when updating the original card fails', async () => {
+ const handle = await start('ou_owner', 'working', { threadTs: 'om_root' });
+ mocks.patchCardRaw.mockRejectedValueOnce(new Error('patch unavailable'));
await handle.finalize('正文');
- expect(mocks.patchCardRaw).toHaveBeenCalledTimes(1);
- expect(markdownContent(mocks.patchCardRaw.mock.calls[0][1])).toBe('正文');
+ await handle.finalize('正文');
+ expect(mocks.patchCardRaw).toHaveBeenCalledExactlyOnceWith('om_stream', expect.anything());
+ expect(mocks.sendCardRaw).toHaveBeenCalledTimes(2);
+ expect(markdownContent(mocks.sendCardRaw.mock.calls[1][1])).toBe('正文');
+ expect(mocks.sendCardRaw.mock.calls[1][2]).toEqual({ threadTs: 'om_root', advanceRound: false });
+ expect(handle.messageId).toBe('om_final');
expect(mocks.recallMessage).not.toHaveBeenCalled();
expect(mocks.sendText).not.toHaveBeenCalled();
});
- it('edits progress, then sends a fresh final before recalling progress, only once', async () => {
+ it('edits progress and then the final on the same card, only once', async () => {
vi.useFakeTimers();
try {
const handle = await start('ou_owner', 'working', { threadTs: 'om_root' });
@@ -129,23 +151,56 @@ describe('feishu streaming text', () => {
await handle.finalize('answer');
await handle.finalize('answer');
await vi.advanceTimersByTimeAsync(1500);
+ expect(mocks.patchCardRaw).toHaveBeenCalledTimes(2);
+ expect(mocks.patchCardRaw.mock.calls.map(([id]) => id)).toEqual(['om_stream', 'om_stream']);
+ expect(markdownContent(mocks.patchCardRaw.mock.calls[1][1])).toBe('answer');
+ expect(mocks.sendCardRaw).toHaveBeenCalledTimes(1);
+ expect(mocks.recallMessage).not.toHaveBeenCalled();
+ expect(handle.messageId).toBe('om_stream');
+ } finally { vi.useRealTimers(); }
+ });
+
+ it('waits for an in-flight progress edit before writing the final answer', async () => {
+ vi.useFakeTimers();
+ try {
+ let finishProgress!: () => void;
+ mocks.patchCardRaw.mockImplementationOnce(() => new Promise<void>((resolve) => { finishProgress = resolve; }));
+ const handle = await start('ou_owner');
+ handle.append('draft');
+ await vi.advanceTimersByTimeAsync(1500);
+ const finished = handle.finalize('answer');
expect(mocks.patchCardRaw).toHaveBeenCalledTimes(1);
- expect(mocks.sendCardRaw).toHaveBeenCalledTimes(2);
- expect(mocks.sendCardRaw.mock.calls[1][2]).toEqual({ threadTs: 'om_root', advanceRound: false });
- expect(mocks.sendCardRaw.mock.invocationCallOrder[1]).toBeLessThan(mocks.recallMessage.mock.invocationCallOrder[0]);
- expect(mocks.recallMessage).toHaveBeenCalledExactlyOnceWith('om_stream');
- expect(handle.messageId).toBe('om_final');
+ finishProgress();
+ await finished;
+ expect(mocks.patchCardRaw).toHaveBeenCalledTimes(2);
+ expect(markdownContent(mocks.patchCardRaw.mock.calls[1][1])).toBe('answer');
+ expect(mocks.sendCardRaw).toHaveBeenCalledTimes(1);
+ expect(mocks.recallMessage).not.toHaveBeenCalled();
} finally { vi.useRealTimers(); }
});
- it('does not resend the final if recalling progress fails', async () => {
- mocks.recallMessage.mockRejectedValue(new Error('recall unavailable'));
+ it('updates a claimed opener without recalling it or resetting its reply anchor', async () => {
+ mocks.claimPatchableOpener.mockReturnValueOnce('om_opener');
+ const handle = await start('g/oc_chat/omt_topic');
+ await handle.finalize('answer');
+ expect(mocks.patchCardRaw).toHaveBeenCalledExactlyOnceWith('om_opener', expect.anything());
+ expect(markdownContent(mocks.patchCardRaw.mock.calls[0][1])).toBe('answer');
+ expect(mocks.sendCardRaw).not.toHaveBeenCalled();
+ expect(mocks.recallMessage).not.toHaveBeenCalled();
+ expect(mocks.rearmAnchorToTrigger).not.toHaveBeenCalled();
+ expect(handle.messageId).toBe('om_opener');
+ });
+
+ it('does not send a fallback through a replacement account after a failed final edit', async () => {
const handle = await start('ou_owner');
+ mocks.patchCardRaw.mockImplementationOnce(async () => {
+ mocks.getAccountEpoch.mockReturnValue(2);
+ throw new Error('old account disconnected');
+ });
await handle.finalize('answer');
- expect(mocks.sendCardRaw).toHaveBeenCalledTimes(2);
- expect(mocks.patchCardRaw).not.toHaveBeenCalled();
+ expect(mocks.sendCardRaw).toHaveBeenCalledTimes(1);
expect(mocks.sendText).not.toHaveBeenCalled();
- expect(handle.messageId).toBe('om_final');
+ expect(mocks.recallMessage).not.toHaveBeenCalled();
});
it('does not send or recall through a replacement account after image upload', async () => {
@@ -161,7 +216,7 @@ describe('feishu streaming text', () => {
expect(mocks.recallMessage).not.toHaveBeenCalled();
});
- it('falls back to plain text when even the short card patch fails', async () => {
+ it('sends a delivery notice if both final editing and fallback delivery fail', async () => {
mocks.patchCardRaw.mockRejectedValue(new Error('card patch unavailable'));
const handle = await start('ou_owner');
mocks.sendCardRaw.mockRejectedValueOnce(new Error('send unavailable'));
@@ -185,7 +240,8 @@ describe('feishu streaming text', () => {
).resolves.toBeUndefined();
expect(mocks.uploadImage).toHaveBeenCalledTimes(1);
- expect(mocks.sendCardRaw).toHaveBeenCalledTimes(2);
- expect(markdownContent(mocks.sendCardRaw.mock.calls[1][1])).toContain('终态正文');
+ expect(mocks.sendCardRaw).toHaveBeenCalledTimes(1);
+ expect(markdownContent(mocks.patchCardRaw.mock.calls[0][1])).toContain('终态正文');
+ expect(mocks.recallMessage).not.toHaveBeenCalled();
});
});
diff --git a/packages/lizi-im/src/feishu/streamingText.ts b/packages/lizi-im/src/feishu/streamingText.ts
index 9cd74b7d20..d99fbbf16e 100644
--- a/packages/lizi-im/src/feishu/streamingText.ts
+++ b/packages/lizi-im/src/feishu/streamingText.ts
@@ -14,8 +14,8 @@
* 2) parse xdt-file URLs (dedup), send each
* as a separate file message
* 3) strip xdt-file from card text
- * 4) send final card with text/images, then
- * recall the progress card
+ * 4) update the progress card with final
+ * text/images
* handle.close() → cancel pending throttle, no further patches
*
* Design parity: matches the legacy feishuBot/replyClient.ts behaviour
@@ -230,7 +230,7 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {
await this.inFlight;
}
- // ── finalize: upload media, send final, recall progress ───────────────────
+ // ── finalize: upload media, replace progress with the final ───────────────
private async doFinalize(): Promise<void> {
const log = getLog();
@@ -329,7 +329,7 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {
const cardText = stripXdtFileLinks(text);
const cardTextTrimmed = cardText.trim();
- // 4. Send a new final message, then remove the progress card. Terminal shapes:
+ // 4. Update the original card without a recall notice. Terminal shapes:
// a) text only → plain markdown card v2
// b) text + images (markdown 内联 OR tool_result 追加) → mixed elements card
// c) empty text + only files → "🎉 N 个文件已送达" placeholder
@@ -353,32 +353,25 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {
? buildMixedMarkdownCardV2(visibleText, imageMap, extraImageKeys)
: buildMarkdownCardV2(visibleText),
);
- const progressId = this.messageId;
- const result = await sendCardRaw(this.openId, card, { ...this.opts, advanceRound: false });
- this.messageIdValue = result.messageId;
+ await patchCardRaw(this.messageId, card);
this.flushed = this.buffer;
- // Cleanup is best-effort: a failed recall must never resend the final.
- if (getAccountEpoch() !== this.accountEpoch) return;
- try {
- await recallMessage(progressId);
- if (this.claimedOpener && getAccountEpoch() === this.accountEpoch) {
- rearmAnchorToTrigger(this.openId, progressId);
- }
- } catch (err) {
- log.warn(`[feishu/streamingText] progress recall failed: ${String(err)}`);
- }
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
- log.warn(`[feishu/streamingText] finalize send failed: ${msg}`);
+ log.warn(`[feishu/streamingText] finalize patch failed: ${msg}`);
if (getAccountEpoch() !== this.accountEpoch) return;
const notice = transportMessages.streaming.deliveryFailed;
try {
- // Preserve the answer on the progress card when fresh delivery fails.
- await patchCardRaw(this.messageId, card ?? buildMarkdownCardV2(notice));
+ // Preserve the full answer if the original card can no longer be edited.
+ // Stay on this round's target and never recall the user's progress card.
+ const result = await sendCardRaw(this.openId, card ?? buildMarkdownCardV2(notice), {
+ ...this.opts, advanceRound: false,
+ });
+ this.messageIdValue = result.messageId;
+ this.flushed = this.buffer;
} catch (fallbackErr) {
const fallbackMsg =
fallbackErr instanceof Error ? fallbackErr.message : String(fallbackErr);
- log.warn(`[feishu/streamingText] fallback patch failed: ${fallbackMsg}`);
+ log.warn(`[feishu/streamingText] fallback send failed: ${fallbackMsg}`);
if (getAccountEpoch() !== this.accountEpoch) return;
try {
await sendText(this.openId, notice, this.opts);