Skip to content

Commit d94e7f5

Browse files
authored
fix(discord): show reasoning text in progress drafts (#78050)
* fix(discord): show reasoning text in progress drafts * fix(discord): handle reasoning progress snapshots * test: isolate usage-format models fixture
1 parent 01dda73 commit d94e7f5

7 files changed

Lines changed: 177 additions & 6 deletions

File tree

‎CHANGELOG.md‎

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

8787
### Fixes
8888

89+
- Discord/streaming: show live reasoning text in progress drafts instead of a bare `Reasoning` status line.
8990
- Doctor/status: warn when `OPENCLAW_GATEWAY_TOKEN` would shadow a different active `gateway.auth.token` source for local CLI commands, while avoiding false positives when config points at the same env token. Fixes #74271. Thanks @yelog.
9091
- Gateway/OpenAI-compatible: send the assistant role SSE chunk as soon as streaming chat-completion headers are accepted, so cold agent setup cannot leave `/v1/chat/completions` clients with a bodyless 200 response until their idle timeout fires.
9192
- Agents/media: avoid direct generated-media completion fallback while the announce-agent run is still pending, so async video and music completions do not duplicate raw media messages. (#77754)

‎extensions/discord/src/monitor/message-handler.draft-preview.ts‎

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,8 @@ export function createDiscordDraftPreviewController(params: {
8282
});
8383
let previewToolProgressSuppressed = false;
8484
let previewToolProgressLines: string[] = [];
85+
let reasoningProgressRawText = "";
86+
let lastReasoningProgressLine: string | undefined;
8587
const progressSeed = `${params.accountId}:${params.deliverChannelId}`;
8688

8789
const renderProgressDraft = async (options?: { flush?: boolean }) => {
@@ -116,6 +118,8 @@ export function createDiscordDraftPreviewController(params: {
116118
draftChunker?.reset();
117119
previewToolProgressSuppressed = false;
118120
previewToolProgressLines = [];
121+
reasoningProgressRawText = "";
122+
lastReasoningProgressLine = undefined;
119123
};
120124

121125
const forceNewMessageIfNeeded = () => {
@@ -163,8 +167,11 @@ export function createDiscordDraftPreviewController(params: {
163167
return;
164168
}
165169
const normalized = line?.replace(/\s+/g, " ").trim();
170+
if (!normalized) {
171+
return;
172+
}
166173
if (discordStreamMode !== "progress") {
167-
if (!previewToolProgressEnabled || previewToolProgressSuppressed || !normalized) {
174+
if (!previewToolProgressEnabled || previewToolProgressSuppressed) {
168175
return;
169176
}
170177
const previous = previewToolProgressLines.at(-1);
@@ -200,6 +207,36 @@ export function createDiscordDraftPreviewController(params: {
200207
await renderProgressDraft();
201208
}
202209
},
210+
async pushReasoningProgress(text?: string) {
211+
if (!draftStream || discordStreamMode !== "progress" || !text) {
212+
return;
213+
}
214+
reasoningProgressRawText = mergeReasoningProgressText(reasoningProgressRawText, text);
215+
const normalized = normalizeReasoningProgressLine(reasoningProgressRawText);
216+
if (!normalized) {
217+
return;
218+
}
219+
if (previewToolProgressEnabled && !previewToolProgressSuppressed) {
220+
const priorIndex =
221+
lastReasoningProgressLine === undefined
222+
? -1
223+
: previewToolProgressLines.lastIndexOf(lastReasoningProgressLine);
224+
if (priorIndex >= 0) {
225+
previewToolProgressLines = [...previewToolProgressLines];
226+
previewToolProgressLines[priorIndex] = normalized;
227+
} else {
228+
previewToolProgressLines = [...previewToolProgressLines, normalized].slice(
229+
-resolveChannelProgressDraftMaxLines(params.discordConfig),
230+
);
231+
}
232+
lastReasoningProgressLine = normalized;
233+
}
234+
const alreadyStarted = progressDraftGate.hasStarted;
235+
await progressDraftGate.noteWork();
236+
if (alreadyStarted && progressDraftGate.hasStarted) {
237+
await renderProgressDraft();
238+
}
239+
},
203240
resolvePreviewFinalText(text?: string) {
204241
if (typeof text !== "string") {
205242
return undefined;
@@ -329,3 +366,29 @@ export function createDiscordDraftPreviewController(params: {
329366
},
330367
};
331368
}
369+
370+
function normalizeReasoningProgressLine(text: string): string {
371+
return text
372+
.replace(/^\s*(?:>\s*)?Reasoning:\s*/i, "")
373+
.replace(/\s+/g, " ")
374+
.trim();
375+
}
376+
377+
function mergeReasoningProgressText(current: string, incoming: string): string {
378+
if (!current) {
379+
return incoming;
380+
}
381+
const normalizedCurrent = normalizeReasoningProgressLine(current);
382+
const normalizedIncoming = normalizeReasoningProgressLine(incoming);
383+
if (!normalizedIncoming || normalizedIncoming === normalizedCurrent) {
384+
return current;
385+
}
386+
if (isReasoningSnapshotText(incoming) || normalizedIncoming.startsWith(normalizedCurrent)) {
387+
return incoming;
388+
}
389+
return `${current}${incoming}`;
390+
}
391+
392+
function isReasoningSnapshotText(text: string): boolean {
393+
return /^\s*(?:>\s*)?Reasoning:\s*/i.test(text);
394+
}

‎extensions/discord/src/monitor/message-handler.process.test.ts‎

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ type DispatchInboundParams = {
9696
sendFinalReply: (payload: ReplyPayload) => boolean | Promise<boolean>;
9797
};
9898
replyOptions?: {
99-
onReasoningStream?: () => Promise<void> | void;
99+
onReasoningStream?: (payload?: { text?: string }) => Promise<void> | void;
100100
onReasoningEnd?: () => Promise<void> | void;
101101
onToolStart?: (payload: {
102102
name?: string;
@@ -105,6 +105,7 @@ type DispatchInboundParams = {
105105
detailMode?: "explain" | "raw";
106106
}) => Promise<void> | void;
107107
onItemEvent?: (payload: {
108+
kind?: string;
108109
progressText?: string;
109110
summary?: string;
110111
title?: string;
@@ -1616,6 +1617,72 @@ describe("processDiscordMessage draft streaming", () => {
16161617
expect(draftStream.update).toHaveBeenCalledWith("Shelling\n🛠️ Exec\n• done");
16171618
});
16181619

1620+
it("shows reasoning text instead of a bare Reasoning progress line", async () => {
1621+
const draftStream = createMockDraftStreamForTest();
1622+
1623+
dispatchInboundMessage.mockImplementationOnce(async (params?: DispatchInboundParams) => {
1624+
await params?.replyOptions?.onToolStart?.({ name: "exec", phase: "start" });
1625+
await params?.replyOptions?.onItemEvent?.({
1626+
kind: "analysis",
1627+
title: "Reasoning",
1628+
});
1629+
await params?.replyOptions?.onReasoningStream?.({ text: "Reading " });
1630+
await params?.replyOptions?.onReasoningStream?.({ text: "the event projector" });
1631+
return createNoQueuedDispatchResult();
1632+
});
1633+
1634+
const ctx = await createAutomaticSourceDeliveryContext({
1635+
discordConfig: {
1636+
streaming: {
1637+
mode: "progress",
1638+
progress: {
1639+
label: "Clawing...",
1640+
},
1641+
},
1642+
},
1643+
});
1644+
1645+
await runProcessDiscordMessage(ctx);
1646+
1647+
expect(draftStream.update).toHaveBeenCalledWith(
1648+
"Clawing...\n🛠️ Exec\n• Reading the event projector",
1649+
);
1650+
expect(draftStream.update).not.toHaveBeenCalledWith(expect.stringContaining("Reasoning"));
1651+
});
1652+
1653+
it("replaces reasoning snapshots instead of appending duplicates", async () => {
1654+
const draftStream = createMockDraftStreamForTest();
1655+
1656+
dispatchInboundMessage.mockImplementationOnce(async (params?: DispatchInboundParams) => {
1657+
await params?.replyOptions?.onToolStart?.({ name: "exec", phase: "start" });
1658+
await params?.replyOptions?.onReasoningStream?.({ text: "Reasoning:\n_Checking files_" });
1659+
await params?.replyOptions?.onReasoningStream?.({
1660+
text: "Reasoning:\n_Checking files and tests_",
1661+
});
1662+
return createNoQueuedDispatchResult();
1663+
});
1664+
1665+
const ctx = await createAutomaticSourceDeliveryContext({
1666+
discordConfig: {
1667+
streaming: {
1668+
mode: "progress",
1669+
progress: {
1670+
label: "Clawing...",
1671+
},
1672+
},
1673+
},
1674+
});
1675+
1676+
await runProcessDiscordMessage(ctx);
1677+
1678+
expect(draftStream.update).toHaveBeenCalledWith(
1679+
"Clawing...\n🛠️ Exec\n• _Checking files and tests_",
1680+
);
1681+
expect(draftStream.update).not.toHaveBeenCalledWith(
1682+
expect.stringContaining("_Checking files_Reasoning:"),
1683+
);
1684+
});
1685+
16191686
it("keeps Discord progress lines across assistant boundaries", async () => {
16201687
const draftStream = createMockDraftStreamForTest();
16211688

‎extensions/discord/src/monitor/message-handler.process.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -660,8 +660,9 @@ export async function processDiscordMessage(
660660
onModelSelected,
661661
suppressDefaultToolProgressMessages:
662662
draftPreview.suppressDefaultToolProgressMessages ? true : undefined,
663-
onReasoningStream: async () => {
663+
onReasoningStream: async (payload) => {
664664
await statusReactions.setThinking();
665+
await draftPreview.pushReasoningProgress(payload?.text);
665666
},
666667
onToolStart: async (payload) => {
667668
if (isProcessAborted(abortSignal)) {

‎src/plugin-sdk/channel-streaming.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,21 @@ describe("channel-streaming", () => {
337337
},
338338
),
339339
).toBe("🛠️ Exec");
340+
expect(
341+
formatChannelProgressDraftLine({
342+
event: "item",
343+
itemKind: "analysis",
344+
title: "Reasoning",
345+
}),
346+
).toBeUndefined();
347+
expect(
348+
formatChannelProgressDraftLine({
349+
event: "item",
350+
itemKind: "analysis",
351+
title: "Reasoning",
352+
progressText: "Reading the code path",
353+
}),
354+
).toBe("Reading the code path");
340355
});
341356

342357
it("starts progress drafts after five seconds or a second work event", async () => {

‎src/plugin-sdk/channel-streaming.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,17 @@ function isCommandProgressItem(input: Extract<ChannelProgressDraftLineInput, { e
275275
return itemKind === "command" || isCommandToolName(input.name);
276276
}
277277

278+
function isEmptyReasoningProgressItem(
279+
input: Extract<ChannelProgressDraftLineInput, { event: "item" }>,
280+
meta: string | undefined,
281+
): boolean {
282+
return (
283+
!meta &&
284+
normalizeOptionalLowercaseString(input.itemKind) === "analysis" &&
285+
normalizeOptionalLowercaseString(input.title) === "reasoning"
286+
);
287+
}
288+
278289
function patchMetas(input: Extract<ChannelProgressDraftLineInput, { event: "patch" }>): string[] {
279290
const fileMetas = [...(input.added ?? []), ...(input.modified ?? []), ...(input.deleted ?? [])];
280291
return compactStrings([input.summary, ...fileMetas, input.title]);
@@ -346,6 +357,9 @@ export function buildChannelProgressDraftLine(
346357
(options?.commandText === "status" && isCommandProgressItem(input)
347358
? undefined
348359
: input.progressText);
360+
if (isEmptyReasoningProgressItem(input, meta)) {
361+
return undefined;
362+
}
349363
if (name) {
350364
return buildNamedProgressLine(input.event, name, [meta], options, {
351365
status: input.status,

‎src/utils/usage-format.test.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,16 @@ import {
1818

1919
describe("usage-format", () => {
2020
const originalAgentDir = process.env.OPENCLAW_AGENT_DIR;
21+
const originalStateDir = process.env.OPENCLAW_STATE_DIR;
22+
let stateDir: string;
2123
let agentDir: string;
2224

2325
beforeEach(async () => {
24-
agentDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-usage-format-"));
25-
process.env.OPENCLAW_AGENT_DIR = agentDir;
26+
stateDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-usage-format-"));
27+
agentDir = path.join(stateDir, "agents", "main", "agent");
28+
process.env.OPENCLAW_STATE_DIR = stateDir;
29+
delete process.env.OPENCLAW_AGENT_DIR;
30+
await fs.mkdir(agentDir, { recursive: true });
2631
__resetUsageFormatCachesForTest();
2732
__resetGatewayModelPricingCacheForTest();
2833
});
@@ -33,9 +38,14 @@ describe("usage-format", () => {
3338
} else {
3439
process.env.OPENCLAW_AGENT_DIR = originalAgentDir;
3540
}
41+
if (originalStateDir === undefined) {
42+
delete process.env.OPENCLAW_STATE_DIR;
43+
} else {
44+
process.env.OPENCLAW_STATE_DIR = originalStateDir;
45+
}
3646
__resetUsageFormatCachesForTest();
3747
__resetGatewayModelPricingCacheForTest();
38-
await fs.rm(agentDir, { recursive: true, force: true });
48+
await fs.rm(stateDir, { recursive: true, force: true });
3949
});
4050

4151
it("formats token counts", () => {

0 commit comments

Comments
 (0)