Skip to content

Commit 455eba7

Browse files
authored
fix(feishu): coalesce streaming card final delivery
1 parent 38703ed commit 455eba7

5 files changed

Lines changed: 240 additions & 27 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ Docs: https://docs.openclaw.ai
2424
- Google Chat: preserve reply text when a typing indicator message is deleted or can no longer be updated, so media captions and first text chunks are resent instead of silently disappearing. (#71498) Thanks @colin-lgtm.
2525
- Cron: tolerate malformed legacy job rows in startup, main-session system-event payloads, and human-readable `cron list` output so missing `state`, `payload.text`, or display fields no longer crash the scheduler or CLI. Fixes #66016, #65916, #64137, #57872, #59968, #63813, #52804, and #43163. (#71509) Thanks @vincentkoc.
2626
- CLI/models: make `openclaw models scan` fall back to public OpenRouter free-model metadata when no `OPENROUTER_API_KEY` is configured, avoid config secret resolution for explicit `--no-probe` scans, and apply the scan timeout to the OpenRouter catalog request.
27+
- Feishu: keep streaming cards to one live card per turn, flush throttled card edits after meaningful text boundaries, and skip exact block/partial repeats so tool-heavy replies do not duplicate card output. Thanks @allan0509.
2728
- Heartbeat: clamp oversized scheduler delays through the shared safe timer helper, preventing `every` values over Node's timeout cap from becoming a 1 ms crash loop. Fixes #71414. (#71478) Thanks @hclsys.
2829
- Control UI/chat: collapse assistant token/model context details behind an explicit Context disclosure and show full dates in message footers, making historical transcript timing clear without noisy default metadata. (#71337) Thanks @BunsDev.
2930
- OpenAI/Codex OAuth: explain `unsupported_country_region_territory` token-exchange failures with a proxy/region hint instead of surfacing a generic OAuth error. Fixes #51175. (#71501) Thanks @vincentkoc and @wulala-xjj.

‎extensions/feishu/src/reply-dispatcher.test.ts‎

Lines changed: 49 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,7 @@ describe("createFeishuReplyDispatcher streaming behavior", () => {
296296
rootId: "om_root_topic",
297297
});
298298
await options.deliver({ text: "```ts\nconst x = 1\n```" }, { kind: "final" });
299+
await options.onIdle?.();
299300

300301
expect(streamingInstances).toHaveLength(1);
301302
expect(streamingInstances[0].start).toHaveBeenCalledTimes(1);
@@ -330,20 +331,17 @@ describe("createFeishuReplyDispatcher streaming behavior", () => {
330331
});
331332
});
332333

333-
it("delivers distinct final payloads after streaming close", async () => {
334+
it("coalesces distinct final payloads into one streaming card until idle", async () => {
334335
const { options } = createDispatcherHarness({
335336
runtime: createRuntimeLogger(),
336337
});
337338
await options.deliver({ text: "```md\n完整回复第一段\n```" }, { kind: "final" });
338339
await options.deliver({ text: "```md\n完整回复第一段 + 第二段\n```" }, { kind: "final" });
340+
await options.onIdle?.();
339341

340-
expect(streamingInstances).toHaveLength(2);
342+
expect(streamingInstances).toHaveLength(1);
341343
expect(streamingInstances[0].close).toHaveBeenCalledTimes(1);
342-
expect(streamingInstances[0].close).toHaveBeenCalledWith("```md\n完整回复第一段\n```", {
343-
note: "Agent: agent",
344-
});
345-
expect(streamingInstances[1].close).toHaveBeenCalledTimes(1);
346-
expect(streamingInstances[1].close).toHaveBeenCalledWith(
344+
expect(streamingInstances[0].close).toHaveBeenCalledWith(
347345
"```md\n完整回复第一段 + 第二段\n```",
348346
{
349347
note: "Agent: agent",
@@ -358,6 +356,7 @@ describe("createFeishuReplyDispatcher streaming behavior", () => {
358356
runtime: createRuntimeLogger(),
359357
});
360358
await options.deliver({ text: "```md\n同一条回复\n```" }, { kind: "final" });
359+
await options.onIdle?.();
361360
await options.deliver({ text: "```md\n同一条回复\n```" }, { kind: "final" });
362361

363362
expect(streamingInstances).toHaveLength(1);
@@ -370,6 +369,17 @@ describe("createFeishuReplyDispatcher streaming behavior", () => {
370369
});
371370

372371
it("skips final text already closed by idle streaming", async () => {
372+
resolveFeishuAccountMock.mockReturnValue({
373+
accountId: "main",
374+
appId: "app_id",
375+
appSecret: "app_secret",
376+
domain: "feishu",
377+
config: {
378+
renderMode: "card",
379+
streaming: true,
380+
},
381+
});
382+
373383
const { result, options } = createDispatcherHarness({
374384
runtime: createRuntimeLogger(),
375385
});
@@ -454,6 +464,33 @@ describe("createFeishuReplyDispatcher streaming behavior", () => {
454464
});
455465
});
456466

467+
it("skips block payloads that exactly repeat the latest partial snapshot", async () => {
468+
resolveFeishuAccountMock.mockReturnValue({
469+
accountId: "main",
470+
appId: "app_id",
471+
appSecret: "app_secret",
472+
domain: "feishu",
473+
config: {
474+
renderMode: "card",
475+
streaming: true,
476+
},
477+
});
478+
479+
const { result, options } = createDispatcherHarness({
480+
runtime: createRuntimeLogger(),
481+
});
482+
await options.onReplyStart?.();
483+
result.replyOptions.onPartialReply?.({ text: "```md\npartial\n```" });
484+
await options.deliver({ text: "```md\npartial\n```" }, { kind: "block" });
485+
await options.onIdle?.();
486+
487+
expect(streamingInstances).toHaveLength(1);
488+
expect(streamingInstances[0].close).toHaveBeenCalledTimes(1);
489+
expect(streamingInstances[0].close).toHaveBeenCalledWith("```md\npartial\n```", {
490+
note: "Agent: agent",
491+
});
492+
});
493+
457494
it("sends media-only payloads as attachments", async () => {
458495
const { options } = createDispatcherHarness();
459496
await options.deliver({ mediaUrl: "https://example.com/a.png" }, { kind: "final" });
@@ -508,6 +545,7 @@ describe("createFeishuReplyDispatcher streaming behavior", () => {
508545
{ text: "```ts\nconst x = 1\n```", mediaUrls: ["https://example.com/a.png"] },
509546
{ kind: "final" },
510547
);
548+
await options.onIdle?.();
511549

512550
expect(streamingInstances).toHaveLength(1);
513551
expect(streamingInstances[0].start).toHaveBeenCalledTimes(1);
@@ -576,6 +614,7 @@ describe("createFeishuReplyDispatcher streaming behavior", () => {
576614
result.replyOptions.onPartialReply?.({ text: "answer part" });
577615
result.replyOptions.onReasoningEnd?.();
578616
await options.deliver({ text: "answer part final" }, { kind: "final" });
617+
await options.onIdle?.();
579618

580619
expect(streamingInstances).toHaveLength(1);
581620
const updateCalls = streamingInstances[0].update.mock.calls.map((c: unknown[]) =>
@@ -667,6 +706,7 @@ describe("createFeishuReplyDispatcher streaming behavior", () => {
667706
result.replyOptions.onReasoningStream?.({ text: "" });
668707
result.replyOptions.onPartialReply?.({ text: "```ts\ncode\n```" });
669708
await options.deliver({ text: "```ts\ncode\n```" }, { kind: "final" });
709+
await options.onIdle?.();
670710

671711
expect(streamingInstances).toHaveLength(1);
672712
const closeArg = streamingInstances[0].close.mock.calls[0][0] as string;
@@ -684,6 +724,7 @@ describe("createFeishuReplyDispatcher streaming behavior", () => {
684724
result.replyOptions.onReasoningStream?.({ text: "Reasoning:\n_thought_" });
685725
result.replyOptions.onReasoningEnd?.();
686726
await options.deliver({ text: "```ts\nfinal answer\n```" }, { kind: "final" });
727+
await options.onIdle?.();
687728

688729
expect(streamingInstances).toHaveLength(1);
689730
expect(streamingInstances[0].close).toHaveBeenCalledTimes(1);
@@ -798,6 +839,7 @@ describe("createFeishuReplyDispatcher streaming behavior", () => {
798839
// or transient Feishu failures recover without a process restart.
799840
nowSpy.mockReturnValue(62_000);
800841
await options.deliver({ text: "```ts\nconst z = 3\n```" }, { kind: "final" });
842+
await options.onIdle?.();
801843

802844
expect(streamingInstances).toHaveLength(2);
803845
expect(streamingInstances[1].start).toHaveBeenCalled();

‎extensions/feishu/src/reply-dispatcher.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -453,12 +453,11 @@ export function createFeishuReplyDispatcher(params: CreateFeishuReplyDispatcherP
453453
if (info?.kind === "block") {
454454
// Some runtimes emit block payloads without onPartial/final callbacks.
455455
// Mirror block text into streamText so onIdle close still sends content.
456-
queueStreamingUpdate(text, { mode: "delta" });
456+
queueStreamingUpdate(text, { mode: "delta", dedupeWithLastPartial: true });
457457
}
458458
if (info?.kind === "final") {
459-
streamText = mergeStreamingText(streamText, text);
460-
await closeStreaming();
461-
deliveredFinalTexts.add(text);
459+
streamText = text;
460+
flushStreamingCardUpdate(buildCombinedStreamText(reasoningText, streamText));
462461
}
463462
// Send media even when streaming handled the text
464463
if (hasMedia) {

‎extensions/feishu/src/streaming-card.test.ts‎

Lines changed: 138 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,141 @@
1-
import { describe, expect, it } from "vitest";
2-
import { mergeStreamingText, resolveStreamingCardSendMode } from "./streaming-card.js";
1+
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
3+
const fetchWithSsrFGuardMock = vi.hoisted(() => vi.fn());
4+
5+
vi.mock("openclaw/plugin-sdk/ssrf-runtime", () => ({
6+
fetchWithSsrFGuard: fetchWithSsrFGuardMock,
7+
}));
8+
9+
import {
10+
FeishuStreamingSession,
11+
mergeStreamingText,
12+
resolveStreamingCardSendMode,
13+
} from "./streaming-card.js";
14+
15+
type StreamingSessionState = {
16+
cardId: string;
17+
messageId: string;
18+
sequence: number;
19+
currentText: string;
20+
hasNote: boolean;
21+
};
22+
23+
function setStreamingSessionInternals(
24+
session: FeishuStreamingSession,
25+
values: {
26+
state: StreamingSessionState;
27+
lastUpdateTime?: number;
28+
},
29+
) {
30+
const internals = session as unknown as {
31+
state: StreamingSessionState;
32+
lastUpdateTime: number;
33+
};
34+
internals.state = values.state;
35+
if (values.lastUpdateTime !== undefined) {
36+
internals.lastUpdateTime = values.lastUpdateTime;
37+
}
38+
}
39+
40+
describe("FeishuStreamingSession", () => {
41+
beforeEach(() => {
42+
vi.useRealTimers();
43+
fetchWithSsrFGuardMock.mockReset();
44+
});
45+
46+
function mockFetches(updateBodies: string[]) {
47+
fetchWithSsrFGuardMock.mockImplementation(
48+
async ({ url, init }: { url: string; init?: { body?: string } }) => {
49+
const release = vi.fn(async () => {});
50+
if (url.includes("/auth/")) {
51+
return {
52+
response: {
53+
ok: true,
54+
json: async () => ({
55+
code: 0,
56+
msg: "ok",
57+
tenant_access_token: "token",
58+
expire: 7200,
59+
}),
60+
},
61+
release,
62+
};
63+
}
64+
if (url.includes("/elements/content/content")) {
65+
updateBodies.push(init?.body ?? "");
66+
}
67+
return {
68+
response: {
69+
ok: true,
70+
json: async () => ({ code: 0, msg: "ok" }),
71+
},
72+
release,
73+
};
74+
},
75+
);
76+
}
77+
78+
it("flushes throttled pending text after the throttle window", async () => {
79+
vi.useFakeTimers();
80+
vi.setSystemTime(1_000);
81+
const updateBodies: string[] = [];
82+
mockFetches(updateBodies);
83+
84+
const session = new FeishuStreamingSession({} as never, {
85+
appId: "app_pending_flush",
86+
appSecret: "secret",
87+
});
88+
setStreamingSessionInternals(session, {
89+
state: {
90+
cardId: "card_1",
91+
messageId: "om_1",
92+
sequence: 1,
93+
currentText: "hello",
94+
hasNote: false,
95+
},
96+
lastUpdateTime: 1_000,
97+
});
98+
99+
await session.update("hello small");
100+
expect(updateBodies).toHaveLength(0);
101+
102+
await vi.advanceTimersByTimeAsync(160);
103+
104+
expect(updateBodies).toHaveLength(1);
105+
expect(JSON.parse(updateBodies[0] ?? "{}")).toMatchObject({
106+
content: "hello small",
107+
});
108+
});
109+
110+
it("pushes natural-boundary updates immediately inside the throttle window", async () => {
111+
vi.useFakeTimers();
112+
vi.setSystemTime(2_000);
113+
const updateBodies: string[] = [];
114+
mockFetches(updateBodies);
115+
116+
const session = new FeishuStreamingSession({} as never, {
117+
appId: "app_boundary_flush",
118+
appSecret: "secret",
119+
});
120+
setStreamingSessionInternals(session, {
121+
state: {
122+
cardId: "card_2",
123+
messageId: "om_2",
124+
sequence: 1,
125+
currentText: "hello",
126+
hasNote: false,
127+
},
128+
lastUpdateTime: 2_000,
129+
});
130+
131+
await session.update("hello!");
132+
133+
expect(updateBodies).toHaveLength(1);
134+
expect(JSON.parse(updateBodies[0] ?? "{}")).toMatchObject({
135+
content: "hello!",
136+
});
137+
});
138+
});
3139

4140
describe("mergeStreamingText", () => {
5141
it("prefers the latest full text when it already includes prior text", () => {

0 commit comments

Comments
 (0)