Skip to content

fix(agents): harden OpenAI phase-aware visible text — suppress commentary partials, prevent empty final_answer fallback leak - #61829

Merged
steipete merged 9 commits into
openclaw:mainfrom
electricsheephq:fix/phase-integrity-hardening-v2
Apr 6, 2026
Merged

steipete merged 9 commits into
openclaw:mainfrom
electricsheephq:fix/phase-integrity-hardening-v2

Conversation

@100yenadmin

@100yenadmin 100yenadmin commented Apr 6, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #61474, #61475.

Recreated from clean branch (previous PR #61481 closed as dirty).

Summary

  • Prevent final_answer blocks from falling back to commentary text when sanitized to empty
  • Suppress all commentary-phase partial streaming output
  • Align session-history HTTP/SSE sanitization with hardened chat history paths
  • Add regression tests for leak prevention

Related

Test plan

  • Commentary partials suppressed in streaming
  • Empty final_answer doesn't fall back to commentary
  • SSE history sanitized consistently
  • Bounded SSE paths sanitized

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 (1M context) [email protected]

100yenadmin and others added 8 commits April 6, 2026 18:07
- Bounded/cursor SSE refresh path now sanitizes through
  sanitizeChatHistoryMessages before paginating, matching the
  unbounded path and initial history load.
- Export DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS from chat.ts and
  import in sessions-history-http.ts instead of duplicating.
Apply sanitizeChatHistoryMessages before pagination in the bounded SSE
history refresh path, consistent with the unbounded path. Initialize
rawTranscriptSeq from the raw transcript's last __openclaw.seq value
instead of the sanitized history length, preventing seq drift when
sanitization drops messages.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings April 6, 2026 11:08
@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling size: M labels Apr 6, 2026
@greptile-apps

greptile-apps Bot commented Apr 6, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

Hardens the OpenAI phase-aware visible text pipeline across three surfaces. extractAssistantVisibleText now returns "" instead of falling back to unphased text when a final_answer block exists but sanitizes to empty, preventing commentary-phase leakage into replies. handleMessageUpdate gets an early-return guard for deliveryPhase === "commentary" partial messages, suppressing stream events before any state mutation. The SSE history path in sessions-history-http.ts now tracks rawTranscriptSeq from the unsanitized transcript and calls sanitizeChatHistoryMessages on incremental events, keeping sequence numbers correct across suppressed NO_REPLY messages while aligning with the bounded and HTTP paths.

Confidence Score: 5/5

Safe to merge — all fixes are well-scoped and no P0/P1 issues found.

No correctness, data-integrity, or security issues found. The rawTranscriptSeq tracking logic correctly handles sanitization gaps. The only finding is a P2 test fixture inconsistency (tool-2 retaining input: {} after tool-1 was updated to arguments: {}) that does not affect test outcomes.

No files require special attention.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/pi-embedded-helpers.validate-turns.test.ts
Line: 13-16

Comment:
**Inconsistent field name in test fixture**

Only `tool-1` was updated from `input` to `arguments`; `tool-2` on the next line still uses `input: {}`. The filtering logic only checks `type` and `id` so this doesn't affect correctness, but the mixed shapes make the fixture misleading.

```suggestion
    { type: "toolUse", id: "tool-1", name: "test1", arguments: {} },
    { type: "toolUse", id: "tool-2", name: "test2", arguments: {} },
    { type: "text", text: "Done" },
```

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

Reviews (1): Last reviewed commit: "gateway: fix bounded SSE sanitization an..." | Re-trigger Greptile

@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: 99b8cdb6af

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/gateway/sessions-history-http.ts Resolved

Copilot AI 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.

Pull request overview

Hardens assistant visible-text handling to prevent commentary/partial output leaks (especially when final_answer is empty) and aligns HTTP/SSE session-history sanitization with the existing hardened chat history path.

Changes:

  • Prevent extractAssistantVisibleText() from falling back to unphased/commentary text when an explicit final_answer block exists but sanitizes to empty.
  • Suppress all commentary-phase partial streaming output and avoid final-answer partial fallbacks that could leak buffered commentary.
  • Apply sanitizeChatHistoryMessages() consistently for HTTP history + SSE (unbounded push updates and bounded refresh), with regression tests.

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
src/gateway/sessions-history-http.ts Sanitize history prior to pagination; sanitize SSE updates; keep seq numbering stable when messages are dropped.
src/gateway/sessions-history-http.test.ts Adds SSE sanitization + NO_REPLY suppression/seq regression tests.
src/gateway/server-methods/chat.ts Exports shared chat-history constants/sanitizer for reuse.
src/agents/tools/chat-history-text.ts Uses phase-aware extraction when textSignature metadata is present.
src/agents/pi-embedded-utils.ts Fixes empty-final_answer fallback leak by tracking presence of requested phase.
src/agents/pi-embedded-utils.test.ts Adds regression test for empty final_answer + legacy text fallback leak.
src/agents/pi-embedded-subscribe.handlers.messages.ts Suppresses all commentary partials; prevents final_answer fallback to deltaBuffer.
src/agents/pi-embedded-subscribe.handlers.messages.test.ts Updates/extends tests to assert commentary partial suppression.
src/agents/pi-embedded-helpers/turns.ts Expands dangling tool-call stripping to scan within assistant spans; avoids synthesizing fallback text for aborted/error turns.
src/agents/pi-embedded-helpers.validate-turns.test.ts Updates/adds validation tests for new dangling tool-call stripping behavior.

Copilot AI 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.

Pull request overview

Copilot reviewed 10 out of 10 changed files in this pull request and generated 2 comments.

Comment thread src/gateway/sessions-history-http.ts Resolved
Comment thread src/agents/pi-embedded-helpers/turns.ts Resolved
@steipete
steipete merged commit bbd0702 into openclaw:main Apr 6, 2026
9 checks passed
@steipete

steipete commented Apr 6, 2026

Copy link
Copy Markdown
Contributor

Landed via temp rebase onto main.\n\n- Gate: OPENCLAW_VITEST_MAX_WORKERS=1 pnpm test src/agents/pi-embedded-utils.test.ts -t "does not fall back to unphased legacy text when an empty final_answer block exists"; OPENCLAW_VITEST_MAX_WORKERS=1 pnpm test src/agents/pi-embedded-subscribe.handlers.messages.test.ts -t "suppresses commentary partials even when they contain visible text"; OPENCLAW_VITEST_MAX_WORKERS=1 pnpm test src/gateway/sessions-history-http.test.ts -t "sanitizes phased assistant history entries before returning them|suppresses NO_REPLY-only SSE fast-path updates while preserving raw sequence numbering|resyncs raw sequence numbering after transcript-only SSE refreshes"\n- Land commit: 14ee78b\n- Merge commit: bbd0702\n\nThanks @100yenadmin!

@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: 14ee78bb57

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/gateway/server-methods/chat.ts Resolved
@100yenadmin

100yenadmin commented Apr 6, 2026 •

Copy link
Copy Markdown
Contributor Author



OpenAI Agent Hardening — Companion PR Family

TL;DR: This merged PR (#61829) is the anchor of a 10-PR family that hardens OpenAI agent integration against commentary leakage, session corruption, and silent data loss. The remaining 10 PRs are all rebased on main, all review comments resolved, all tests passing, and ready for review.

Why this matters (plain English)

When OpenClaw agents talk to OpenAI's API, they use an internal "phase" system to separate thinking/commentary from final answers shown to users. Several bugs allowed internal commentary to leak into user-visible chat, heartbeat operations to corrupt subagent tasks, and tool-call replays to silently lose data. These fixes close those gaps across streaming, replay, history, and session management.

The PR Family

Group 1: Phase Separation & Commentary Leak Prevention (builds on this merged PR)

PR | What it fixes | Status -- | -- | -- #61529 | Replay drops message-level phase for untagged blocks → commentary leaks on history replay | Ready #61528 | WS buffering gates on key existence not phase validity → unphased commentary leaks to UI | Ready #61463 | Phase-blind text extraction in sessions-helpers, TUI, and REST history → commentary visible in chat history | Ready #61855 | SSE history handler reads transcript twice → race condition causes seq gaps | Ready

Dependency / Merge Order

#61529 (phase inheritance) ─┐
#61528 (phase gate)         ├─→ #61463 (extraction surfaces) ─→ #61855 (SSE race)
#61803 (heartbeat)          │
#61801 (orphan sweep)       │
#61525 (announce dedup)     │
#60555 (sessionKey backfill)│
#61527 (malformed args)     │
#49901 (scan-ahead)         ┘

#61529 and #61528 should merge first as #61463 builds on their phase-separation work. The rest can merge in any order. All are rebased on current main.

New Issues Filed

Review Status

All PRs have 0 unanswered review comments, human-readable descriptions, 4+ linked issues each, and tests passing. CI failures are pre-existing on main (extension shards, contracts-protocol).

cc @steipete — would appreciate your review on this family when you have a chance. Happy to walk through any of these in detail.


 @steipete 

@jalehman

Mlightsnow pushed a commit to Mlightsnow/openclaw that referenced this pull request Apr 6, 2026
lovewanwan pushed a commit to lovewanwan/openclaw that referenced this pull request Apr 28, 2026
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request Sep 29, 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 size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(agents): extractAssistantVisibleText leaks commentary when final_answer exists but is empty

3 participants