Skip to content

fix(gateway): sanitize assistant reasoning before history truncation - #90924

Closed
849261680 wants to merge 1 commit into
openclaw:mainfrom
849261680:fix/90692-history-reasoning-sanitize
Closed

849261680 wants to merge 1 commit into
openclaw:mainfrom
849261680:fix/90692-history-reasoning-sanitize

Conversation

@849261680

@849261680 849261680 commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

What problem does this PR solve?

  • Fixes WebChat/history projection leaking raw assistant reasoning scaffolding when a stored assistant message contains malformed or unclosed thinking tags and is reloaded/truncated.
  • Routes assistant display text through the existing assistant-visible history sanitizer before applying the chat-history text cap.
  • Treats <final> and <final/> as visible-answer boundaries for strict unclosed reasoning recovery, while recursively sanitizing any later reasoning tags.
  • Preserves exact tool payload text; tool outputs that happen to contain reasoning-like XML are not rewritten.

Why does this matter now?

What is the intended outcome?

  • History reloads show only the visible final answer text, with truncation applied after reasoning/final scaffolding is removed.

What is intentionally out of scope?

  • No config/env surface changes.
  • No frontend parser behavior changes.
  • No changes to structured tool payload preservation.

What does success look like?

  • chat.history no longer returns raw thinking/final tags or private reasoning text for the reported malformed transcript shape.
  • Existing history truncation, content-block projection, and tool-payload preservation continue to work.

What should reviewers focus on?

  • src/gateway/chat-display-projection.ts assistant display text path vs. exact tool payload path.
  • src/shared/text/reasoning-tags.ts strict-mode recovery for unclosed reasoning followed by final tags.

Linked context

Which issue does this close?

Closes #90692

Which issues, PRs, or discussions are related?

Related #90692

Was this requested by a maintainer or owner?

Maintainer follow-up from the ClawSweeper source-repro review on #90692.

Real behavior proof (required for external PRs)

  • Behavior addressed: WebChat chat.history reload/projection sanitizes assistant reasoning/final scaffolding before truncating history text, preventing raw <thinking> tags or private reasoning text from appearing after reload.
  • Real environment tested: Local OpenClaw source checkout on macOS with Node 24.15.0; actual OpenClaw gateway projection module loaded through tsx and run against a transcript-shaped assistant message.
  • Exact steps or command run after this patch: node --import tsx - <<'EOF' ... import { projectChatDisplayMessages } from './src/gateway/chat-display-projection.ts'; ... EOF
  • Evidence after fix (screenshot, recording, terminal capture, console output, redacted runtime log, linked artifact, or copied live output): copied console output from the command above:
{
  "projectedText": "\nVisible answer after reasoning. Visible answer after reasoning. Visible answer after reasoning.\n...(truncated)...",
  "hasThinkingTag": false,
  "hasFinalTag": false,
  "hasPrivateReasoning": false,
  "hasTruncationMarker": true
}
  • Observed result after fix: The projected history text keeps visible answer content and the truncation marker, while hasThinkingTag, hasFinalTag, and hasPrivateReasoning are all false.
  • What was not tested: A live Windows WebChat heartbeat with Google Gemini 3.5 Flash was not reproduced end-to-end.
  • Proof limitations or environment constraints: Crabbox/Testbox changed gate could not run because no usable crabbox binary was available in PATH or at ../crabbox/bin/crabbox; focused local gateway/shared/UI checks, oxlint, tsgo, and autoreview were run instead.
  • Before evidence (optional but encouraged): [Bug]: Thinking tags leak and truncation (truncated) on heartbeat interrupt during streaming #90692 and the ClawSweeper source-repro comment identify current main truncating assistant text after directive-only stripping in chat-display-projection, which can expose malformed reasoning tags on history reload.

Tests and validation

Which commands did you run?

  • node --import tsx - <<'EOF' ... projectChatDisplayMessages(...) ... EOF
  • node scripts/run-vitest.mjs src/shared/text/assistant-visible-text.test.ts
  • node --no-maglev node_modules/vitest/vitest.mjs run --config test/vitest/vitest.gateway-methods.config.ts src/gateway/server-methods/server-methods.test.ts -t "sanitizeChatHistoryMessages" --reporter=dot
  • node --no-maglev node_modules/vitest/vitest.mjs run --config test/vitest/vitest.gateway-server.config.ts src/gateway/server.chat.gateway-server-chat-b.test.ts -t "chat.history" --reporter=dot
  • node --no-maglev node_modules/vitest/vitest.mjs run --config test/vitest/vitest.ui.config.ts ui/src/ui/format.test.ts --reporter=dot
  • git diff --check upstream/main...HEAD
  • node_modules/.bin/oxlint src/gateway/chat-display-projection.ts src/gateway/server-methods/server-methods.test.ts src/gateway/server.chat.gateway-server-chat-b.test.ts src/shared/text/assistant-visible-text.test.ts src/shared/text/reasoning-tags.ts
  • node scripts/run-tsgo.mjs -p tsconfig.core.json --incremental --tsBuildInfoFile .artifacts/tsgo-cache/core.tsbuildinfo
  • node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.core.test.json --incremental --tsBuildInfoFile .artifacts/tsgo-cache/core-test.tsbuildinfo
  • .agents/skills/autoreview/scripts/autoreview --mode branch --base upstream/main

What regression coverage was added or updated?

  • Shared assistant-visible sanitizer tests for unclosed reasoning followed by <final> and <final/>, including later nested reasoning tags after the recovered final boundary.
  • Gateway projection tests for assistant text, assistant text content blocks, truncation after sanitization, and exact tool payload preservation.
  • Gateway chat.history RPC test for transcript-backed reload projection with maxChars.

What failed before this fix, if known?

  • Source-level behavior: assistant history text was truncated after directive-only stripping, leaving malformed reasoning/final scaffolding available to the UI on reload.

If no test was added, why not?

  • N/A. Focused regression tests were added.

Risk checklist

Did user-visible behavior change? (Yes/No)

Yes. Assistant history display hides reasoning/final scaffolding before truncation.

Did config, environment, or migration behavior change? (Yes/No)

No.

Did security, auth, secrets, network, or tool execution behavior change? (Yes/No)

Yes, security-relevant display sanitization changed to reduce reasoning leakage in history projection. No auth/secrets/network/tool execution behavior changed.

What is the highest-risk area?

Over-sanitizing non-assistant or tool payload text that should remain exact.

How is that risk mitigated?

The new sanitizer is only applied to assistant display text paths and mixed assistant text projection; exact tool payload branches continue to use the previous directive-only path and have regression coverage.

Current review state

What is the next action?

Ready for maintainer and ClawSweeper review.

What review or CI state should maintainers know about?

Local focused checks, oxlint, core tsgo, and autoreview are clean. Crabbox/Testbox changed gate is not available in this environment because the Crabbox binary is missing.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M triage: mock-only-proof Candidate: PR proof only shows tests, mocks, snapshots, lint, typecheck, or CI. labels Jun 6, 2026
@clawsweeper

clawsweeper Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed June 30, 2026, 1:14 PM ET / 17:14 UTC.

Summary
The PR sanitizes assistant-visible reasoning/final scaffolding in gateway chat-history projection before truncation while preserving exact tool payload text.

PR surface: Source +42, Tests +149. Total +191 across 5 files.

Reproducibility: yes. source-reproducible: current main still projects chat.history through directive-only stripping and truncation without the shared history reasoning sanitizer. I did not run the original Windows WebChat plus Gemini heartbeat sequence in this read-only review.

Review metrics: 1 noteworthy metric.

  • Mergeability: 1 dirty PR head. The useful sanitizer cannot be merged until conflicts or stale-base drift are resolved on current main.

Stored data model
Persistent data-model change detected: serialized state: src/gateway/server.chat.gateway-server-chat-b.test.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #90692
Summary: This PR is the open server-side projection fix candidate for the canonical WebChat history truncation and reasoning-leak issue.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🦐 gold shrimp
Proof: 🐚 platinum hermit
Patch quality: 🦐 gold shrimp
Result: needs maintainer review before merge.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Port or rebase the sanitizer onto current main and rerun focused gateway/shared checks.

Proof path suggestion
A browser/WebChat proof on the merge result would materially help confirm the user-visible history reload and truncation behavior. Mantis is currently scoped to Telegram, Discord, and web UI chat proof, so it is not the right proof path for this surface.
Use maintainer screenshot/manual proof, browser or Playwright proof, Crabbox where appropriate, or normal local artifact proof instead.

Risk before merge

  • [P1] The PR is dirty against current main, and the local merge-tree check cannot produce a merge result, so maintainers cannot land this branch without a rebase or narrow replacement.
  • [P1] The diff intentionally rewrites assistant history display text before WebChat delivery; an overmatch in the shared sanitizer could suppress visible assistant prose that resembles reasoning or final scaffolding.
  • [P1] The PR was authored against older source, so any port must preserve current-main sanitizer additions such as reasoning scope and namespaced tag support instead of reverting them.

Maintainer options:

  1. Port The Sanitizer To Current Main (recommended)
    Carry the assistant-history sanitization behavior onto current main while preserving newer reasoning-tag behavior and rerun focused gateway/shared checks.
  2. Accept The Bounded Display Risk
    Maintainers may accept the sanitizer risk after merge-ref proof confirms assistant display text is cleaned and tool payloads remain exact.
  3. Pause For A Narrower Contract
    Pause if owners want a history-specific parser contract instead of reusing the shared assistant-visible sanitizer.

Next step before merge

  • [P2] A narrow repair lane can port this useful but dirty PR onto current main without changing the product direction.

Security
Cleared: Cleared: the diff reduces a reasoning-display exposure and touches only gateway/shared text projection plus tests, with no dependency, workflow, package, auth, secret, or code-execution surface change found.

Review details

Best possible solution:

Port or rebase the bounded gateway/shared sanitizer onto current main, preserve exact tool payloads and current sanitizer improvements, then validate chat.history projection before merge.

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

Yes, source-reproducible: current main still projects chat.history through directive-only stripping and truncation without the shared history reasoning sanitizer. I did not run the original Windows WebChat plus Gemini heartbeat sequence in this read-only review.

Is this the best way to solve the issue?

Yes, as a fix shape: gateway history projection is the right layer because it owns bounded transcript history returned to WebChat. The branch still needs rebase or porting before the implementation can be considered merge-ready.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against f284ce3b4df7.

Label changes

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.

Label justifications:

  • P2: This is a normal-priority gateway/WebChat history bugfix with reasoning-leak impact and a focused implementation path.
  • merge-risk: 🚨 message-delivery: The PR rewrites assistant history display text before WebChat delivery, so sanitizer overmatch could suppress or alter visible assistant content.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body includes after-fix live console output from the actual gateway projection module showing reasoning/final tags removed while visible answer text and the truncation marker remain.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes after-fix live console output from the actual gateway projection module showing reasoning/final tags removed while visible answer text and the truncation marker remain.
Evidence reviewed

PR surface:

Source +42, Tests +149. Total +191 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 2 49 7 +42
Tests 3 149 0 +149
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 198 7 +191

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/shared/text/assistant-visible-text.test.ts.
  • [P1] node scripts/run-vitest.mjs src/gateway/server-methods/server-methods.test.ts -t "sanitizeChatHistoryMessages".
  • [P1] node scripts/run-vitest.mjs src/gateway/server.chat.gateway-server-chat-b.test.ts -t "chat.history".
  • [P1] git diff --check.

What I checked:

  • Repository policy read: Root AGENTS.md was read completely and applied to require whole-surface PR review, proof review, best-fix judgment, and merge-risk handling. (AGENTS.md:1, f284ce3b4df7)
  • Scoped gateway policy read: Scoped gateway and server-methods AGENTS.md files were read; the touched path has gateway hot-path and transcript-writing review guidance. (src/gateway/AGENTS.md:1, f284ce3b4df7)
  • Current main still truncates after directive-only stripping: Current main strips only inline directive tags from assistant history content/text before truncating, so malformed reasoning/final scaffolding can still reach WebChat history output. (src/gateway/chat-display-projection.ts:508, f284ce3b4df7)
  • chat.history uses the affected projection path: The chat.history method projects transcript messages through projectRecentChatDisplayMessages/projectChatDisplayMessages with the effective maxChars, so gateway projection order controls reload output. (src/gateway/server-methods/chat.ts:2834, f284ce3b4df7)
  • Latest release still has old projection behavior: Release v2026.6.11 has the same directive-only strip-before-truncate path in chat-display-projection, so the fix is not shipped there. (src/gateway/chat-display-projection.ts:508, e085fa1a3ffd)
  • PR sanitizer boundary: PR head adds sanitizeAssistantHistoryDisplayText, which strips inline directives and then runs sanitizeAssistantVisibleTextWithProfile with the history profile before truncation. (src/gateway/chat-display-projection.ts:65, cb1f22014555)

Likely related people:

  • steipete: Peter Steinberger authored the unified chat display projection and shared assistant-visible sanitizer commits that this PR extends. (role: shared sanitizer feature-history owner; confidence: high; commits: 5f2273e81efc, 712479eea1a1, cf79689ca1bd; files: src/gateway/chat-display-projection.ts, src/shared/text/reasoning-tags.ts, src/shared/text/assistant-visible-text.ts)
  • vincentkoc: Vincent Koc has recent adjacent commits in gateway history projection and delivery-mirror behavior around the affected file. (role: recent gateway history contributor; confidence: medium; commits: f5eddc2b6d1f, 25f3d2d714e9; files: src/gateway/chat-display-projection.ts, src/gateway/server-methods/server-methods.test.ts)
  • 849261680: Yzx authored this PR and has prior adjacent merged WebChat display projection work, so they are relevant beyond being only the proposer. (role: linked repair author and adjacent contributor; confidence: medium; commits: cb1f22014555, 932d6ea8e5ce; files: src/gateway/chat-display-projection.ts, src/shared/text/reasoning-tags.ts)
  • lin-hongkuan: Current blame for the affected lines points to a broad recent main commit, but the commit subject suggests this is less likely to be feature ownership than carry-forward history. (role: recent current-main carrier; confidence: low; commits: bc7f0f1223cd; files: src/gateway/chat-display-projection.ts, src/shared/text/reasoning-tags.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (1 earlier review cycle)
  • reviewed 2026-06-21T07:49:28.538Z sha cb1f220 :: needs maintainer review before merge. :: none

@openclaw-barnacle openclaw-barnacle Bot added proof: supplied External PR includes structured after-fix real behavior proof. and removed triage: mock-only-proof Candidate: PR proof only shows tests, mocks, snapshots, lint, typecheck, or CI. labels Jun 6, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P2 Normal backlog priority with limited blast radius. labels Jun 6, 2026
@849261680
849261680 force-pushed the fix/90692-history-reasoning-sanitize branch from 39ff6ee to 6888ec4 Compare June 6, 2026 12:49
@myles-mworks

Copy link
Copy Markdown

@clawsweeper re-review

@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 6, 2026
@849261680

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 6, 2026
@849261680
849261680 force-pushed the fix/90692-history-reasoning-sanitize branch from 6888ec4 to 2176a75 Compare June 7, 2026 20:17
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 7, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 7, 2026
@849261680
849261680 force-pushed the fix/90692-history-reasoning-sanitize branch from 2176a75 to cb1f220 Compare June 7, 2026 20:33
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 7, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 7, 2026
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. label Jun 15, 2026
@xuwei-xy

Copy link
Copy Markdown

Great work on this PR! The changes look clean and well-structured.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Jul 6, 2026
@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 Jul 21, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M stale Marked as stale due to inactivity status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Thinking tags leak and truncation (truncated) on heartbeat interrupt during streaming

3 participants