Skip to content

Commit 9e8df16

Browse files
day253Takhoffman
andauthored
feat(feishu): add reasoning stream support to streaming cards (#46029)
Verified: - pnpm build - pnpm check - pnpm test:macmini Co-authored-by: day253 <[email protected]> Co-authored-by: Tak Hoffman <[email protected]>
1 parent 3928b48 commit 9e8df16

3 files changed

Lines changed: 168 additions & 9 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ Docs: https://docs.openclaw.ai
88

99
- Commands/btw: add `/btw` side questions for quick tool-less answers about the current session without changing future session context, with dismissible in-session TUI answers and explicit BTW replies on external channels. (#45444) Thanks @ngutman.
1010
- Refactor/channels: remove the legacy channel shim directories and point channel-specific imports directly at the extension-owned implementations. (#45967) thanks @scoootscooob.
11+
- Feishu/streaming: add `onReasoningStream` and `onReasoningEnd` support to streaming cards, so `/reasoning stream` renders thinking tokens as markdown blockquotes in the same card — matching the Telegram channel's reasoning lane behavior.
1112

1213
### Fixes
1314

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

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -462,6 +462,126 @@ describe("createFeishuReplyDispatcher streaming behavior", () => {
462462
);
463463
});
464464

465+
it("streams reasoning content as blockquote before answer", async () => {
466+
const { result, options } = createDispatcherHarness({
467+
runtime: createRuntimeLogger(),
468+
});
469+
470+
await options.onReplyStart?.();
471+
// Core agent sends pre-formatted text from formatReasoningMessage
472+
result.replyOptions.onReasoningStream?.({ text: "Reasoning:\n_thinking step 1_" });
473+
result.replyOptions.onReasoningStream?.({
474+
text: "Reasoning:\n_thinking step 1_\n_step 2_",
475+
});
476+
result.replyOptions.onPartialReply?.({ text: "answer part" });
477+
result.replyOptions.onReasoningEnd?.();
478+
await options.deliver({ text: "answer part final" }, { kind: "final" });
479+
480+
expect(streamingInstances).toHaveLength(1);
481+
const updateCalls = streamingInstances[0].update.mock.calls.map((c: unknown[]) => c[0]);
482+
const reasoningUpdate = updateCalls.find((c: string) => c.includes("Thinking"));
483+
expect(reasoningUpdate).toContain("> 💭 **Thinking**");
484+
// formatReasoningPrefix strips "Reasoning:" prefix and italic markers
485+
expect(reasoningUpdate).toContain("> thinking step");
486+
expect(reasoningUpdate).not.toContain("Reasoning:");
487+
expect(reasoningUpdate).not.toMatch(/> _.*_/);
488+
489+
const combinedUpdate = updateCalls.find(
490+
(c: string) => c.includes("Thinking") && c.includes("---"),
491+
);
492+
expect(combinedUpdate).toBeDefined();
493+
494+
expect(streamingInstances[0].close).toHaveBeenCalledTimes(1);
495+
const closeArg = streamingInstances[0].close.mock.calls[0][0] as string;
496+
expect(closeArg).toContain("> 💭 **Thinking**");
497+
expect(closeArg).toContain("---");
498+
expect(closeArg).toContain("answer part final");
499+
});
500+
501+
it("provides onReasoningStream and onReasoningEnd when streaming is enabled", () => {
502+
const { result } = createDispatcherHarness({
503+
runtime: createRuntimeLogger(),
504+
});
505+
506+
expect(result.replyOptions.onReasoningStream).toBeTypeOf("function");
507+
expect(result.replyOptions.onReasoningEnd).toBeTypeOf("function");
508+
});
509+
510+
it("omits reasoning callbacks when streaming is disabled", () => {
511+
resolveFeishuAccountMock.mockReturnValue({
512+
accountId: "main",
513+
appId: "app_id",
514+
appSecret: "app_secret",
515+
domain: "feishu",
516+
config: {
517+
renderMode: "auto",
518+
streaming: false,
519+
},
520+
});
521+
522+
const { result } = createDispatcherHarness({
523+
runtime: createRuntimeLogger(),
524+
});
525+
526+
expect(result.replyOptions.onReasoningStream).toBeUndefined();
527+
expect(result.replyOptions.onReasoningEnd).toBeUndefined();
528+
});
529+
530+
it("renders reasoning-only card when no answer text arrives", async () => {
531+
const { result, options } = createDispatcherHarness({
532+
runtime: createRuntimeLogger(),
533+
});
534+
535+
await options.onReplyStart?.();
536+
result.replyOptions.onReasoningStream?.({ text: "Reasoning:\n_deep thought_" });
537+
result.replyOptions.onReasoningEnd?.();
538+
await options.onIdle?.();
539+
540+
expect(streamingInstances).toHaveLength(1);
541+
expect(streamingInstances[0].close).toHaveBeenCalledTimes(1);
542+
const closeArg = streamingInstances[0].close.mock.calls[0][0] as string;
543+
expect(closeArg).toContain("> 💭 **Thinking**");
544+
expect(closeArg).toContain("> deep thought");
545+
expect(closeArg).not.toContain("Reasoning:");
546+
expect(closeArg).not.toContain("---");
547+
});
548+
549+
it("ignores empty reasoning payloads", async () => {
550+
const { result, options } = createDispatcherHarness({
551+
runtime: createRuntimeLogger(),
552+
});
553+
554+
await options.onReplyStart?.();
555+
result.replyOptions.onReasoningStream?.({ text: "" });
556+
result.replyOptions.onPartialReply?.({ text: "```ts\ncode\n```" });
557+
await options.deliver({ text: "```ts\ncode\n```" }, { kind: "final" });
558+
559+
expect(streamingInstances).toHaveLength(1);
560+
const closeArg = streamingInstances[0].close.mock.calls[0][0] as string;
561+
expect(closeArg).not.toContain("Thinking");
562+
expect(closeArg).toBe("```ts\ncode\n```");
563+
});
564+
565+
it("deduplicates final text by raw answer payload, not combined card text", async () => {
566+
const { result, options } = createDispatcherHarness({
567+
runtime: createRuntimeLogger(),
568+
});
569+
570+
await options.onReplyStart?.();
571+
result.replyOptions.onReasoningStream?.({ text: "Reasoning:\n_thought_" });
572+
result.replyOptions.onReasoningEnd?.();
573+
await options.deliver({ text: "```ts\nfinal answer\n```" }, { kind: "final" });
574+
575+
expect(streamingInstances).toHaveLength(1);
576+
expect(streamingInstances[0].close).toHaveBeenCalledTimes(1);
577+
578+
// Deliver the same raw answer text again — should be deduped
579+
await options.deliver({ text: "```ts\nfinal answer\n```" }, { kind: "final" });
580+
581+
// No second streaming session since the raw answer text matches
582+
expect(streamingInstances).toHaveLength(1);
583+
});
584+
465585
it("passes replyToMessageId and replyInThread to streaming.start()", async () => {
466586
const { options } = createDispatcherHarness({
467587
runtime: createRuntimeLogger(),

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

Lines changed: 47 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -143,11 +143,39 @@ export function createFeishuReplyDispatcher(params: CreateFeishuReplyDispatcherP
143143
let streaming: FeishuStreamingSession | null = null;
144144
let streamText = "";
145145
let lastPartial = "";
146+
let reasoningText = "";
146147
const deliveredFinalTexts = new Set<string>();
147148
let partialUpdateQueue: Promise<void> = Promise.resolve();
148149
let streamingStartPromise: Promise<void> | null = null;
149150
type StreamTextUpdateMode = "snapshot" | "delta";
150151

152+
const formatReasoningPrefix = (thinking: string): string => {
153+
if (!thinking) return "";
154+
const withoutLabel = thinking.replace(/^Reasoning:\n/, "");
155+
const plain = withoutLabel.replace(/^_(.*)_$/gm, "$1");
156+
const lines = plain.split("\n").map((line) => `> ${line}`);
157+
return `> 💭 **Thinking**\n${lines.join("\n")}`;
158+
};
159+
160+
const buildCombinedStreamText = (thinking: string, answer: string): string => {
161+
const parts: string[] = [];
162+
if (thinking) parts.push(formatReasoningPrefix(thinking));
163+
if (thinking && answer) parts.push("\n\n---\n\n");
164+
if (answer) parts.push(answer);
165+
return parts.join("");
166+
};
167+
168+
const flushStreamingCardUpdate = (combined: string) => {
169+
partialUpdateQueue = partialUpdateQueue.then(async () => {
170+
if (streamingStartPromise) {
171+
await streamingStartPromise;
172+
}
173+
if (streaming?.isActive()) {
174+
await streaming.update(combined);
175+
}
176+
});
177+
};
178+
151179
const queueStreamingUpdate = (
152180
nextText: string,
153181
options?: {
@@ -167,14 +195,13 @@ export function createFeishuReplyDispatcher(params: CreateFeishuReplyDispatcherP
167195
const mode = options?.mode ?? "snapshot";
168196
streamText =
169197
mode === "delta" ? `${streamText}${nextText}` : mergeStreamingText(streamText, nextText);
170-
partialUpdateQueue = partialUpdateQueue.then(async () => {
171-
if (streamingStartPromise) {
172-
await streamingStartPromise;
173-
}
174-
if (streaming?.isActive()) {
175-
await streaming.update(streamText);
176-
}
177-
});
198+
flushStreamingCardUpdate(buildCombinedStreamText(reasoningText, streamText));
199+
};
200+
201+
const queueReasoningUpdate = (nextThinking: string) => {
202+
if (!nextThinking) return;
203+
reasoningText = nextThinking;
204+
flushStreamingCardUpdate(buildCombinedStreamText(reasoningText, streamText));
178205
};
179206

180207
const startStreaming = () => {
@@ -213,7 +240,7 @@ export function createFeishuReplyDispatcher(params: CreateFeishuReplyDispatcherP
213240
}
214241
await partialUpdateQueue;
215242
if (streaming?.isActive()) {
216-
let text = streamText;
243+
let text = buildCombinedStreamText(reasoningText, streamText);
217244
if (mentionTargets?.length) {
218245
text = buildMentionedCardContent(mentionTargets, text);
219246
}
@@ -223,6 +250,7 @@ export function createFeishuReplyDispatcher(params: CreateFeishuReplyDispatcherP
223250
streamingStartPromise = null;
224251
streamText = "";
225252
lastPartial = "";
253+
reasoningText = "";
226254
};
227255

228256
const sendChunkedTextReply = async (params: {
@@ -392,6 +420,16 @@ export function createFeishuReplyDispatcher(params: CreateFeishuReplyDispatcherP
392420
});
393421
}
394422
: undefined,
423+
onReasoningStream: streamingEnabled
424+
? (payload: ReplyPayload) => {
425+
if (!payload.text) {
426+
return;
427+
}
428+
startStreaming();
429+
queueReasoningUpdate(payload.text);
430+
}
431+
: undefined,
432+
onReasoningEnd: streamingEnabled ? () => {} : undefined,
395433
},
396434
markDispatchIdle,
397435
};

0 commit comments

Comments
 (0)