Skip to content

Chat: stream reasoning and split tool rendering - #59086

Closed
easonchen3 wants to merge 1 commit into
openclaw:mainfrom
easonchen3:codex/reasoning-stream-ui-fixes
Closed

easonchen3 wants to merge 1 commit into
openclaw:mainfrom
easonchen3:codex/reasoning-stream-ui-fixes

Conversation

@easonchen3

Copy link
Copy Markdown

Summary

  • stream assistant reasoning deltas through gateway chat events and preserve client run mapping/order
  • render structured think/text/tool streaming in the control UI so interleaved blocks stay in order
  • align streamed reasoning styling with final reasoning and keep reasoning visible when tool cards are hidden

Testing

  • pnpm.cmd test -- src/agents/pi-embedded-subscribe.handlers.lifecycle.test.ts src/agents/pi-embedded-subscribe.subscribe-embedded-pi-session.subscribeembeddedpisession.test.ts src/gateway/server-chat.agent-events.test.ts
  • pnpm.cmd test -- ui/src/ui/controllers/chat.test.ts ui/src/ui/views/chat.test.ts ui/src/ui/chat/message-extract.test.ts
  • pnpm.cmd ui:build

@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling size: L labels Apr 1, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6bcf01fa05

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread ui/src/ui/views/chat.ts
Comment on lines +1552 to 1555
if (props.stream !== null || props.streamMessage) {
const key = `stream:${props.sessionKey}:${props.streamStartedAt ?? "live"}`;
if (props.stream.trim().length > 0) {
if ((props.stream?.trim().length ?? 0) > 0 || props.streamMessage) {
items.push({

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Suppress reasoning-only stream items when reasoning is hidden

When showThinking is off, this condition still adds a live stream item whenever streamMessage exists, even if the message only contains thinking blocks. In that path renderStreamingGroup receives showReasoning=false, so the bubble content is dropped and the UI renders an empty assistant row/footer instead of a reading indicator until answer text arrives. This is user-visible during reasoning-mode runs and is introduced by the new structured streaming path.

Useful? React with 👍 / 👎.

@greptile-apps

greptile-apps Bot commented Apr 1, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds streaming reasoning (thinking) support through the gateway, reorders local-before-global event dispatch so the chat run registry is populated before thinking deltas arrive, and refactors the chat UI to render interleaved thinking/text/tool blocks in their original order.

Key changes:

  • Event ordering: onAgentEvent callbacks are now called before emitAgentEvent in all handlers (lifecycle, compaction, assistant, tool). This ensures local consumers — notably the webchat run-id linker — observe the start lifecycle event before the global fan-out, guaranteeing that thinking-stream events can be correctly routed via chatRunState.registry.
  • Run registry wiring: context.addChatRun(runId, { sessionKey, clientRunId }) is now called inside onAgentRunStart in server-methods/chat.ts, providing the mapping that emitChatThinkingDelta needs to forward thinking events to the right client session.
  • Gateway thinking support: A new emitChatThinkingDelta function in server-chat.ts translates thinking-stream agent events into { state: \"delta\", message: { content: [{ type: \"thinking\", ... }] } } chat payloads broadcast to both session and room.
  • streamReasoning decoupled from UI callback: streamReasoning is now set to reasoningMode === \"stream\" unconditionally (previously gated on the presence of onReasoningStream), so thinking agent events are always emitted when streaming is requested; the optional onReasoningStream callback is still called when provided.
  • Structured streaming state: chatStreamMessage: unknown | null is added alongside chatStream: string | null. Delta updates now populate a typed StreamingAssistantMessage with interleaved thinking/text blocks. The serialized chatStream continues to serve as a legacy fallback.
  • Rendering: renderStreamingGroup and renderGroupedMessage now accept a structured message and a showReasoning flag, rendering <div class=\"chat-thinking\"> outside any <details> wrapper. Tool messages correctly keep reasoning visible when showToolCalls = false, and the early-return guard in renderGroupedMessage was fixed to respect the showToolCalls toggle.
  • Good test coverage across agent handlers, gateway event routing, the streaming merge logic, and the view layer.

Confidence Score: 5/5

Safe to merge — no P0/P1 issues found; all findings are minor style or documentation suggestions.

The implementation correctly solves the ordering problem (local-before-global) with dedicated tests, properly wires the run registry so thinking deltas are never lost, and the streaming merge logic is sound for the replace-style snapshot deltas the server sends. The three P2 comments flag edge-case formatting behaviour in normalizeReasoningDisplayText, a dropped silent-reply guard that could theoretically resurface in a different delta path, and a cosmetic interleaved-block collapse in mergeTerminalAssistantMessage — none affect correctness on the happy path.

ui/src/ui/controllers/chat.ts (merge helpers) and ui/src/ui/chat/message-extract.ts (reasoning normalizer) are the most logic-dense new additions and worth a second read.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: ui/src/ui/chat/message-extract.ts
Line: 125-133

Comment:
**Single-character strip applied to double-marker patterns**

`singleWrappedUnderscore` / `singleWrappedAsterisk` only checks that the line _starts and ends_ with the marker character — it does not verify that they are truly single markers. This means `**bold**` becomes `*bold*` (stripped of one `*` on each side) and `__text__` becomes `_text_` (stripped of one `_` each side). Both are then re-wrapped by `formatReasoningMarkdown` and can render with unintended markdown styling.

For reasoning text these are edge cases, but the guard should exclude double-marker sequences to avoid corrupting deliberately-formatted content:

```suggestion
      const singleWrappedUnderscore =
        trimmed.length >= 2 &&
        trimmed.startsWith("_") &&
        trimmed.endsWith("_") &&
        !trimmed.startsWith("__") &&
        !trimmed.endsWith("__");
      const singleWrappedAsterisk =
        trimmed.length >= 2 &&
        trimmed.startsWith("*") &&
        trimmed.endsWith("*") &&
        !trimmed.startsWith("**") &&
        !trimmed.endsWith("**");
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: ui/src/ui/controllers/chat.ts
Line: 286-298

Comment:
**`isSilentReplyStream` guard removed from `else if` fallback**

The old code checked `!isSilentReplyStream(state.chatStream)` in the `else if` branch (when `finalMessage` is absent or is itself a silent reply). The new code drops that guard and relies entirely on `isAssistantSilentReply(mergedMessage)` inside `appendStreamMessageToHistory`.

In practice these two predicates should agree, but the functions operate on different types (raw serialized string vs. normalized `StreamingAssistantMessage`). If a client stream contained purely silent-reply text that somehow survived without being captured in `chatStreamMessage` (e.g. due to a bug in a future delta path), the check would miss it. Consider keeping the explicit `!isSilentReplyStream(state.chatStream)` guard or adding a comment explaining why it is safe to drop.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: ui/src/ui/controllers/chat.ts
Line: 229-256

Comment:
**`mergeTerminalAssistantMessage` loses interleaved text when prepending thinking**

When the final terminal message has no thinking blocks and the previous streaming state had interleaved `[thinking1, text1, thinking2, text2]`, the merge collects _all_ previous thinking blocks and prepends them to the terminal content, discarding the intermediate `text1`/`text2` segments:

```ts
content: [...previousThinking, ...terminal.content]
// → [thinking1, thinking2, text_from_terminal]
```

In practice the terminal's text supersedes the streamed text, so the data loss is cosmetic. However, if the model produced genuinely distinct reasoning phases interleaved with partial answers, the final rendered message will collapse them into a single reasoning block followed by the terminal reply. A comment explaining this intended trade-off would help future readers.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "Chat: stream reasoning and split tool re..." | Re-trigger Greptile

Comment on lines +125 to +133
return "";
}
const singleWrappedUnderscore =
trimmed.length >= 2 && trimmed.startsWith("_") && trimmed.endsWith("_");
const singleWrappedAsterisk =
trimmed.length >= 2 && trimmed.startsWith("*") && trimmed.endsWith("*");
if (singleWrappedUnderscore || singleWrappedAsterisk) {
return trimmed.slice(1, -1).trim();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Single-character strip applied to double-marker patterns

singleWrappedUnderscore / singleWrappedAsterisk only checks that the line starts and ends with the marker character — it does not verify that they are truly single markers. This means **bold** becomes *bold* (stripped of one * on each side) and __text__ becomes _text_ (stripped of one _ each side). Both are then re-wrapped by formatReasoningMarkdown and can render with unintended markdown styling.

For reasoning text these are edge cases, but the guard should exclude double-marker sequences to avoid corrupting deliberately-formatted content:

Suggested change
return "";
}
const singleWrappedUnderscore =
trimmed.length >= 2 && trimmed.startsWith("_") && trimmed.endsWith("_");
const singleWrappedAsterisk =
trimmed.length >= 2 && trimmed.startsWith("*") && trimmed.endsWith("*");
if (singleWrappedUnderscore || singleWrappedAsterisk) {
return trimmed.slice(1, -1).trim();
}
const singleWrappedUnderscore =
trimmed.length >= 2 &&
trimmed.startsWith("_") &&
trimmed.endsWith("_") &&
!trimmed.startsWith("__") &&
!trimmed.endsWith("__");
const singleWrappedAsterisk =
trimmed.length >= 2 &&
trimmed.startsWith("*") &&
trimmed.endsWith("*") &&
!trimmed.startsWith("**") &&
!trimmed.endsWith("**");
Prompt To Fix With AI
This is a comment left during a code review.
Path: ui/src/ui/chat/message-extract.ts
Line: 125-133

Comment:
**Single-character strip applied to double-marker patterns**

`singleWrappedUnderscore` / `singleWrappedAsterisk` only checks that the line _starts and ends_ with the marker character — it does not verify that they are truly single markers. This means `**bold**` becomes `*bold*` (stripped of one `*` on each side) and `__text__` becomes `_text_` (stripped of one `_` each side). Both are then re-wrapped by `formatReasoningMarkdown` and can render with unintended markdown styling.

For reasoning text these are edge cases, but the guard should exclude double-marker sequences to avoid corrupting deliberately-formatted content:

```suggestion
      const singleWrappedUnderscore =
        trimmed.length >= 2 &&
        trimmed.startsWith("_") &&
        trimmed.endsWith("_") &&
        !trimmed.startsWith("__") &&
        !trimmed.endsWith("__");
      const singleWrappedAsterisk =
        trimmed.length >= 2 &&
        trimmed.startsWith("*") &&
        trimmed.endsWith("*") &&
        !trimmed.startsWith("**") &&
        !trimmed.endsWith("**");
```

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +286 to +298
const nextValue = block.thinking.trim();
last.thinking = nextValue.length >= previousValue.length ? block.thinking : last.thinking;
} else {
const previousValue = last.text.trim();
const nextValue = block.text.trim();
last.text = nextValue.length >= previousValue.length ? block.text : last.text;
}
continue;
}
mergedContent.push({ ...block });
}

return {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 isSilentReplyStream guard removed from else if fallback

The old code checked !isSilentReplyStream(state.chatStream) in the else if branch (when finalMessage is absent or is itself a silent reply). The new code drops that guard and relies entirely on isAssistantSilentReply(mergedMessage) inside appendStreamMessageToHistory.

In practice these two predicates should agree, but the functions operate on different types (raw serialized string vs. normalized StreamingAssistantMessage). If a client stream contained purely silent-reply text that somehow survived without being captured in chatStreamMessage (e.g. due to a bug in a future delta path), the check would miss it. Consider keeping the explicit !isSilentReplyStream(state.chatStream) guard or adding a comment explaining why it is safe to drop.

Prompt To Fix With AI
This is a comment left during a code review.
Path: ui/src/ui/controllers/chat.ts
Line: 286-298

Comment:
**`isSilentReplyStream` guard removed from `else if` fallback**

The old code checked `!isSilentReplyStream(state.chatStream)` in the `else if` branch (when `finalMessage` is absent or is itself a silent reply). The new code drops that guard and relies entirely on `isAssistantSilentReply(mergedMessage)` inside `appendStreamMessageToHistory`.

In practice these two predicates should agree, but the functions operate on different types (raw serialized string vs. normalized `StreamingAssistantMessage`). If a client stream contained purely silent-reply text that somehow survived without being captured in `chatStreamMessage` (e.g. due to a bug in a future delta path), the check would miss it. Consider keeping the explicit `!isSilentReplyStream(state.chatStream)` guard or adding a comment explaining why it is safe to drop.

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +229 to +256
return null;
}
const timestamp =
source &&
typeof source === "object" &&
typeof (source as Record<string, unknown>).timestamp === "number"
? ((source as Record<string, unknown>).timestamp as number)
: Date.now();
return {
role: "assistant",
content,
timestamp,
};
}

function serializeStreamingAssistantMessage(message: unknown): string {
const normalized = normalizeStreamingAssistantMessage(message);
if (!normalized) {
return "";
}
return normalized.content
.map((block) =>
block.type === "thinking"
? `<thinking>\n${block.thinking.trim()}\n</thinking>`
: block.text.trim(),
)
.filter(Boolean)
.join("\n\n");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 mergeTerminalAssistantMessage loses interleaved text when prepending thinking

When the final terminal message has no thinking blocks and the previous streaming state had interleaved [thinking1, text1, thinking2, text2], the merge collects all previous thinking blocks and prepends them to the terminal content, discarding the intermediate text1/text2 segments:

content: [...previousThinking, ...terminal.content]
// → [thinking1, thinking2, text_from_terminal]

In practice the terminal's text supersedes the streamed text, so the data loss is cosmetic. However, if the model produced genuinely distinct reasoning phases interleaved with partial answers, the final rendered message will collapse them into a single reasoning block followed by the terminal reply. A comment explaining this intended trade-off would help future readers.

Prompt To Fix With AI
This is a comment left during a code review.
Path: ui/src/ui/controllers/chat.ts
Line: 229-256

Comment:
**`mergeTerminalAssistantMessage` loses interleaved text when prepending thinking**

When the final terminal message has no thinking blocks and the previous streaming state had interleaved `[thinking1, text1, thinking2, text2]`, the merge collects _all_ previous thinking blocks and prepends them to the terminal content, discarding the intermediate `text1`/`text2` segments:

```ts
content: [...previousThinking, ...terminal.content]
// → [thinking1, thinking2, text_from_terminal]
```

In practice the terminal's text supersedes the streamed text, so the data loss is cosmetic. However, if the model produced genuinely distinct reasoning phases interleaved with partial answers, the final rendered message will collapse them into a single reasoning block followed by the terminal reply. A comment explaining this intended trade-off would help future readers.

How can I resolve this? If you propose a fix, please make it concise.

@clawsweeper

clawsweeper Bot commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

Keep this PR open for maintainer review: current main still does not fully solve live reasoning streaming/rendering, but this branch is not merge-ready because it is dirty against main, lacks real behavior proof, and changes the reasoning visibility/security boundary.

Canonical path: Close this stale PR. The latest review rated it F, the branch still lacks merge-ready proof, and there has been no human follow-up after the durable review.

So I’m closing this here because the remaining work is already tracked in the canonical issue.

Review details

Best possible solution:

Close this stale PR. The latest review rated it F, the branch still lacks merge-ready proof, and there has been no human follow-up after the durable review.

Do we have a high-confidence way to reproduce the issue?

No high-confidence live reproduction is present in the PR. The risky paths are source-reproducible from the diff and current-main contracts, especially the no-callback and hidden-reasoning delivery boundaries.

Is this the best way to solve the issue?

No, not as submitted. The branch is a plausible broad implementation, but the best fix should first preserve the current visibility/capability boundary and then layer UI rendering on the settled event contract.

Security review:

Security review needs attention: The diff changes delivery of potentially sensitive reasoning content and needs explicit visibility/capability gates before merge.

  • [high] Hidden reasoning can still stream — src/agents/pi-embedded-subscribe.ts:51
    The proposed streamReasoning condition no longer preserves the current thinking visibility gate, so reasoning can be emitted even for sessions that should hide thinking.
    Confidence: 0.86
  • [medium] Thinking chat deltas lack opt-in gating — src/gateway/server-chat.ts:607
    Reasoning is delivered as chat content to session listeners without a clearly bounded capability or display permission check.
    Confidence: 0.78

AGENTS.md: found and applied where relevant.

What I checked:

  • stale F-rated PR: PR was opened 2026-04-01T14:54:26Z, is older than 30 days, and the latest review rated it F.
  • proof blocker: real behavior proof is missing and proof tier is F, so this branch is not merge-ready without contributor follow-up.
  • no human follow-up: live comments and timeline hydrated by apply contain no non-automation activity after the ClawSweeper review.

Likely related people:

  • nk1tz: Authored the merged gateway thinking/tool event streaming work referenced in the related context. (role: introduced adjacent behavior; confidence: medium; commits: 2b02e8a7a8c1; files: src/gateway/server-chat.ts, src/agents/embedded-agent-subscribe.ts)
  • medns: Authored the merged raw reasoning stream refactor referenced in the related context, which is directly adjacent to this PR's reasoning delta behavior. (role: recent adjacent contributor; confidence: medium; commits: e7277b4e3a4b; files: src/agents/embedded-agent-subscribe.ts)
  • Agustin Rivera: Current shallow blame for the active subscribe, gateway, and UI stream lines points to the recent current-main snapshot commit, though deeper authorship is ambiguous in this checkout. (role: recent current-main area contributor; confidence: low; commits: a4e02cd1dd48; files: src/agents/embedded-agent-subscribe.ts, src/gateway/server-chat.ts, ui/src/ui/chat/grouped-render.ts)

Codex review notes: model gpt-5.5, reasoning high; reviewed against 52bc2a12bc8c.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. labels May 19, 2026
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. label May 19, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels May 19, 2026
@clawsweeper

clawsweeper Bot commented May 20, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat.

Where did the egg go?
  • The egg game starts only after the PR passes the real-behavior proof check.
  • Before that, no creature or rarity is rolled. The treat waits for real proof.
  • This is still just collectible flavor: proof affects review readiness, not creature quality.

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jun 10, 2026
@clawsweeper

clawsweeper Bot commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

@clawsweeper clawsweeper Bot closed this Jun 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui gateway Gateway runtime merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: L stale Marked as stale due to inactivity status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant