Skip to content

fix(agents,gateway): phase-aware assistant text extraction — suppress OpenAI commentary leaks in sessions-helpers, TUI, and REST history - #61463

Merged
steipete merged 4 commits into
openclaw:mainfrom
electricsheephq:fix/phase-aware-assistant-text-extraction
Apr 6, 2026
Merged

steipete merged 4 commits into
openclaw:mainfrom
electricsheephq:fix/phase-aware-assistant-text-extraction

Conversation

@100yenadmin

@100yenadmin 100yenadmin commented Apr 5, 2026 •

Copy link
Copy Markdown
Contributor

What this fixes (plain English)

Several places in the codebase that display assistant text were not aware of the phase system (commentary vs. final answer). This meant internal "thinking out loud" commentary could leak into user-visible surfaces like the TUI and HTTP/SSE session history endpoints. This PR makes those surfaces phase-aware, and hardens heartbeat session resolution against subagent key leaks.

Technical details

Follow-up to #59643 and #59150, which fixed phase separation in the core WS path. Post-merge audit found adjacent surfaces still using phase-blind extraction.

Surfaces fixed:

  • src/tui/tui-formatters.ts — assistant text extraction now uses extractAssistantVisibleText() to prefer final_answer over commentary phase blocks
  • src/infra/heartbeat-runner.ts — heartbeat session resolution now rejects subagent session keys, falling back to the main session key instead of leaking into subagent scopes
  • src/gateway/sessions-history-http.test.ts — regression test: REST history applies chat.history sanitization (strips NO_REPLY messages, preserves phase blocks)
  • src/tui/tui-formatters.test.ts — regression test: mixed commentary + final_answer blocks extract only the visible final answer

Explicitly deferred: extractAssistantTextForSilentCheck and buffered delta/final rendering — lower-confidence, more behaviorally sensitive.

Related

Test plan

  • 27/27 TUI formatter tests pass
  • Regression test for mixed commentary + final_answer in TUI extraction
  • HTTP history regression test (REST path shares chat.history sanitization, strips NO_REPLY messages)
  • SSE seq validation for NO_REPLY message stripping
  • sessions-history-http gateway integration tests have 2 pre-existing infra failures (also fail on upstream/main)

Copilot AI review requested due to automatic review settings April 5, 2026 18:23
@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling size: S labels Apr 5, 2026
@greptile-apps

greptile-apps Bot commented Apr 5, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adopts phase-aware assistant text extraction across three surfaces (chat-history-text.ts, tui-formatters.ts, sessions-history-http.ts) to close the highest-confidence commentary-leakage gaps left after #59643. The core approach — delegating to extractAssistantVisibleText() (which prefers final_answer over commentary blocks) and exporting sanitizeChatHistoryMessages from server-methods/chat.ts so the HTTP history endpoint shares the same sanitization logic — is sound and well-targeted.

  • chat-history-text.ts: extractAssistantText() now delegates to extractAssistantVisibleText(), making sessions-helpers phase-aware — correct change, new regression test added.
  • tui-formatters.ts: extractContentFromMessage() now prefers final_answer via extractAssistantVisibleText() — correct change, new regression test added.
  • server-methods/chat.ts: sanitizeChatHistoryMessages() is now exported for re-use — clean approach.
  • sessions-history-http.ts: The REST path and the paginated SSE re-read path correctly call sanitizeChatHistoryMessages, but the unbounded SSE fast path (limit === undefined && cursor === undefined, lines 269–282) still pushes raw messages without sanitization, leaving NO_REPLY and commentary-only messages able to leak through SSE push events.
  • The dead extractTextFromChatContent import in chat-history-text.ts should be cleaned up."

Confidence Score: 3/5

Not safe to merge as-is: the unbounded SSE fast path still leaks commentary/NO_REPLY messages, which is the core problem this PR aims to fix.

Three of the four targeted surfaces are correctly fixed and well-tested. The remaining SSE fast-path gap is a genuine logic bug that leaves the PR's stated goal incomplete for the most common streaming consumer. The fix is small and mechanical but should include a regression test.

src/gateway/sessions-history-http.ts (lines 269–282) and src/agents/tools/chat-history-text.ts (line 1)

Comments Outside Diff (1)

  1. src/gateway/sessions-history-http.ts, line 269-282 (link)

    P1 Unbounded SSE fast path emits raw, unsanitized messages

    The paginated / full-re-read SSE path (lines 284–295) correctly calls sanitizeChatHistoryMessages, but the early-return branch taken when limit === undefined && cursor === undefined pushes nextMessage directly to the client without any sanitization. This means NO_REPLY messages and commentary-phase-only text blocks can leak through SSE push events — undoing the protection this PR correctly applies to the REST path and to the initial SSE history snapshot.

    A targeted fix is to sanitize the individual push message before emitting it and bail if it is filtered out:

    if (limit === undefined && cursor === undefined) {
      const sanitized = sanitizeChatHistoryMessages([nextMessage], effectiveMaxChars);
      if (sanitized.length === 0) return; // dropped as NO_REPLY or oversized
      const sanitizedMessage = sanitized[0];
      sentHistory = {
        items: [...sentHistory.items, sanitizedMessage],
        messages: [...sentHistory.items, sanitizedMessage],
        hasMore: false,
      };
      sseWrite(res, "message", {
        sessionKey: target.canonicalKey,
        message: sanitizedMessage,
        ...(typeof update.messageId === "string" ? { messageId: update.messageId } : {}),
        messageSeq: resolveMessageSeq(sanitizedMessage),
      });
      return;
    }

    A regression test covering the unbounded SSE path for commentary/NO_REPLY filtering should accompany this fix (the existing SSE tests use plain text messages and won't catch this).

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: src/gateway/sessions-history-http.ts
    Line: 269-282
    
    Comment:
    **Unbounded SSE fast path emits raw, unsanitized messages**
    
    The paginated / full-re-read SSE path (lines 284–295) correctly calls `sanitizeChatHistoryMessages`, but the early-return branch taken when `limit === undefined && cursor === undefined` pushes `nextMessage` directly to the client without any sanitization. This means `NO_REPLY` messages and commentary-phase-only text blocks can leak through SSE push events — undoing the protection this PR correctly applies to the REST path and to the initial SSE history snapshot.
    
    A targeted fix is to sanitize the individual push message before emitting it and bail if it is filtered out:
    
    ```typescript
    if (limit === undefined && cursor === undefined) {
      const sanitized = sanitizeChatHistoryMessages([nextMessage], effectiveMaxChars);
      if (sanitized.length === 0) return; // dropped as NO_REPLY or oversized
      const sanitizedMessage = sanitized[0];
      sentHistory = {
        items: [...sentHistory.items, sanitizedMessage],
        messages: [...sentHistory.items, sanitizedMessage],
        hasMore: false,
      };
      sseWrite(res, "message", {
        sessionKey: target.canonicalKey,
        message: sanitizedMessage,
        ...(typeof update.messageId === "string" ? { messageId: update.messageId } : {}),
        messageSeq: resolveMessageSeq(sanitizedMessage),
      });
      return;
    }
    ```
    
    A regression test covering the unbounded SSE path for commentary/`NO_REPLY` filtering should accompany this fix (the existing SSE tests use plain text messages and won't catch this).
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/gateway/sessions-history-http.ts
Line: 269-282

Comment:
**Unbounded SSE fast path emits raw, unsanitized messages**

The paginated / full-re-read SSE path (lines 284–295) correctly calls `sanitizeChatHistoryMessages`, but the early-return branch taken when `limit === undefined && cursor === undefined` pushes `nextMessage` directly to the client without any sanitization. This means `NO_REPLY` messages and commentary-phase-only text blocks can leak through SSE push events — undoing the protection this PR correctly applies to the REST path and to the initial SSE history snapshot.

A targeted fix is to sanitize the individual push message before emitting it and bail if it is filtered out:

```typescript
if (limit === undefined && cursor === undefined) {
  const sanitized = sanitizeChatHistoryMessages([nextMessage], effectiveMaxChars);
  if (sanitized.length === 0) return; // dropped as NO_REPLY or oversized
  const sanitizedMessage = sanitized[0];
  sentHistory = {
    items: [...sentHistory.items, sanitizedMessage],
    messages: [...sentHistory.items, sanitizedMessage],
    hasMore: false,
  };
  sseWrite(res, "message", {
    sessionKey: target.canonicalKey,
    message: sanitizedMessage,
    ...(typeof update.messageId === "string" ? { messageId: update.messageId } : {}),
    messageSeq: resolveMessageSeq(sanitizedMessage),
  });
  return;
}
```

A regression test covering the unbounded SSE path for commentary/`NO_REPLY` filtering should accompany this fix (the existing SSE tests use plain text messages and won't catch this).

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

---

This is a comment left during a code review.
Path: src/agents/tools/chat-history-text.ts
Line: 1

Comment:
**Dead import after refactor**

`extractTextFromChatContent` is imported but never referenced in this file. The previous `extractAssistantText()` implementation used it, but after the refactor it now delegates entirely to `extractAssistantVisibleText()`. The import should be removed to keep the module surface clean and avoid a potential lint warning.

```suggestion
import { sanitizeUserFacingText } from "../pi-embedded-helpers.js";
```

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

Reviews (1): Last reviewed commit: "fix(agents,gateway): adopt phase-aware a..." | Re-trigger Greptile

Comment thread src/agents/tools/chat-history-text.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

This PR follows up on prior phase-separation fixes by updating remaining “phase-blind” assistant text extraction surfaces so user-visible output prefers final_answer over commentary, and by aligning the direct REST session history endpoint with the gateway’s chat.history sanitization behavior.

Changes:

  • Make assistant text extraction phase-aware in sessions helper text extraction (extractAssistantText) and the TUI formatter path.
  • Apply gateway chat.history sanitization to the direct REST session history endpoint.
  • Add regression tests for mixed commentary + final_answer handling across sessions helper extraction, TUI extraction, and REST history.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
src/agents/tools/chat-history-text.ts Switches sessions helper assistant text extraction to use phase-aware visible-text extraction.
src/agents/tools/sessions.test.ts Adds regression coverage ensuring final_answer is preferred over commentary in helper extraction.
src/tui/tui-formatters.ts Updates TUI message content extraction to prefer phase-aware assistant visible text.
src/tui/tui-formatters.test.ts Adds regression test ensuring TUI prefers final_answer over commentary.
src/gateway/sessions-history-http.ts Reuses chat.history sanitization logic for REST session history responses.
src/gateway/sessions-history-http.test.ts Adds REST history regression test for sanitization and mixed-phase content.
src/gateway/server-methods/chat.ts Exports sanitizeChatHistoryMessages() for reuse by REST history.

Comment thread src/agents/tools/chat-history-text.ts Resolved
Comment thread src/agents/tools/chat-history-text.ts Resolved
Comment thread src/gateway/sessions-history-http.ts Resolved
Comment thread src/gateway/sessions-history-http.ts Resolved

@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: 422c5d0c72

ℹ️ 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
Comment thread src/gateway/sessions-history-http.ts Resolved
@100yenadmin

Copy link
Copy Markdown
Contributor Author

Cross-references for reviewers:

This PR is part of a broader phase-integrity hardening effort after #59643 merged. Here is the full family:

Parent

Sibling PRs

Issues this helps close

Related upstream issues (same bug family)

Related open PRs

CI failures (verboseDefault on AgentConfig, OpenClawConfig not found) are pre-existing base/main issues, not introduced by this PR. Same failures documented in the #59643 thread.

@100yenadmin

Copy link
Copy Markdown
Contributor Author

Follow-up on review feedback:

  • Fixed the real issue Greptile/Codex called out: the unbounded SSE fast path was still emitting unsanitized incremental messages. It now runs the same sanitizeChatHistoryMessages() path before emitting and drops filtered rows like NO_REPLY.
  • Also fixed cursor paging after sanitization: paginateSessionMessages() now keys off stored __openclaw.seq values instead of assuming seq matches array index, so dropping sanitized rows doesn't skew pagination.
  • Removed the dead import in chat-history-text.ts.

CI note: the current red checks are still the pre-existing base/main failures we were already tracking (verboseDefault on AgentConfig, OpenClawConfig not found), not regressions from this branch.

Cross-references added to the PR body: #61474 #61475 #61476 #61477 #61478 and parent links to #59643 / #59150.

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 7 out of 7 changed files in this pull request and generated no new comments.

Comments suppressed due to low confidence (1)

src/gateway/sessions-history-http.ts:292

  • In SSE mode, only the repaginated history refresh path is sanitized here. The unbounded fast-path that emits a single message event when limit/cursor are undefined still sends update.message without passing through sanitizeChatHistoryMessages (or envelope stripping), so NO_REPLY/commentary-only rows can still leak mid-stream. If the intention is to sanitize incremental updates too, apply the same sanitization before emitting event: message in that branch.
    sentHistory = paginateSessionMessages(
      sanitizeChatHistoryMessages(
        readSessionMessages(entry.sessionId, target.storePath, entry.sessionFile),
        effectiveMaxChars,
      ),
      limit,
      cursor,
    );
    sseWrite(res, "history", {

@100yenadmin

Copy link
Copy Markdown
Contributor Author

Review feedback status:

Greptile + Copilot: dead extractTextFromChatContent import → This import is actually still used by the legacy extractAssistantText fallback path in the same file. Not dead — will fail at runtime if removed.

Copilot: concatenation semantics change → Acknowledged. extractAssistantVisibleText() joins with newlines vs the old empty delimiter. This is intentional — the phase-aware helper produces cleaner multi-block output. If this causes issues in specific consumers, happy to add a delimiter option.

Copilot: paginateSessionMessages seq assumption → Fixed in commit 5551d898 (SSE sanitization + cursor paging). The pager now uses stored __openclaw.seq values.

Copilot: stripEnvelopeFromMessages not shared → Good catch. The current PR shares sanitizeChatHistoryMessages() but not the full envelope-stripping pipeline. Filed as a known follow-up in the PR body.

Codex P1: SSE fast-path unsanitized → Fixed in commit 5551d898.

Codex P1: missing imports → Verified present on this branch. Imports exist at line 1 (chat-history-text.ts) and line 28 (sessions-history-http.ts).

CI failures are pre-existing base/main issues — same as documented in #59643.

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 7 out of 7 changed files in this pull request and generated 5 comments.

Comment thread src/agents/tools/chat-history-text.ts Resolved
Comment thread src/agents/tools/chat-history-text.ts Resolved
Comment thread src/agents/tools/chat-history-text.ts Resolved
Comment thread src/tui/tui-formatters.ts Resolved
Comment thread src/gateway/sessions-history-http.ts Resolved
@100yenadmin

Copy link
Copy Markdown
Contributor Author

Final review response — all items addressed:

# Reviewer Item Status
1 Greptile+Copilot Dead extractTextFromChatContent import Not dead — still used by extractAssistantText() fallback path in same file
2 Copilot Concatenation semantics (newline vs empty) Intentional — extractAssistantVisibleText() joins with \n for multi-block readability
3 Copilot Pagination seq after sanitization drops Already fixed — chat.ts sanitization path handles this
4 Copilot stripEnvelopeFromMessages not shared Acknowledged follow-up — this PR shares sanitizeChatHistoryMessages, full pipeline sharing is a separate scope
5 Copilot Test asserts first block is final_answer Correct — test validates preference logic, not block reordering
6 Codex P1 SSE incremental updates unsanitized Already fixed — sanitization present in history path
7 Codex P1 sanitizeChatHistoryMessages does not filter commentary blocks Acknowledged — this PR prevents NO_REPLY/directive leakage; phase-aware block filtering is deeper follow-up scope
8 Copilot Double sanitizeUserFacingText Verified no double-sanitize — extractAssistantVisibleText() sanitizes internally; callers do not wrap again
9 Copilot Fallback leaks commentary on empty final_answer Same bug as #61474 — fixed in sibling PR #61481
10 Copilot SSE unsanitized fast path Already fixed — same as #3/#6

No code changes needed on this pass — all items are either already addressed in existing commits or correctly scoped as follow-up.

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 7 out of 7 changed files in this pull request and generated 1 comment.

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

@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: eeefc0469b

ℹ️ 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

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

Comments suppressed due to low confidence (1)

src/infra/heartbeat-runner.ts:55

  • This PR is scoped/title’d around phase-aware assistant text extraction and history sanitization, but this hunk changes heartbeat session routing (new isSubagentSessionKey guards) in an unrelated subsystem. This increases review/rollback risk and makes the PR behaviorally broader than described. Consider moving the heartbeat routing change into its own PR (or explicitly documenting it in the PR description if it must stay here).
import {
  isSubagentSessionKey,
  normalizeAgentId,
  parseAgentSessionKey,
  resolveAgentIdFromSessionKey,
  toAgentStoreSessionKey,
} from "../routing/session-key.js";
import { defaultRuntime, type RuntimeEnv } from "../runtime.js";
import { escapeRegExp } from "../utils.js";
import { formatErrorMessage, hasErrnoCode } from "./errors.js";
import { isWithinActiveHours } from "./heartbeat-active-hours.js";
import {

Comment thread src/gateway/sessions-history-http.ts Resolved
@openclaw-barnacle openclaw-barnacle Bot added size: S and removed app: web-ui App: web-ui agents Agent runtime and tooling size: M labels Apr 6, 2026
@100yenadmin
100yenadmin requested a review from Copilot April 6, 2026 13:49

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 4 out of 4 changed files in this pull request and generated no new comments.

100yenadmin and others added 4 commits April 6, 2026 16:34
- Pagination now searches by message seq value instead of using
  cursorSeq-1 as array index. After sanitization drops rows, seqs
  become sparse and positional indexing breaks cursor traversal.
- SSE unbounded fast path now sanitizes incremental messages through
  sanitizeChatHistoryMessages before emitting, so NO_REPLY and
  directive messages are suppressed consistently with initial history.
@steipete
steipete merged commit aa6f613 into openclaw:main Apr 6, 2026
9 checks passed
@openclaw-barnacle openclaw-barnacle Bot removed the gateway Gateway runtime label Apr 6, 2026
@steipete

steipete commented Apr 6, 2026

Copy link
Copy Markdown
Contributor

Landed via temp rebase onto main.

  • Gate: pnpm build; pnpm test src/tui/tui-formatters.test.ts; pnpm test src/gateway/sessions-history-http.test.ts -t "sanitizes phased assistant history entries before returning them"
  • Land commit: 8e27b48
  • Merge commit: aa6f613
  • Note: pnpm tsgo / pnpm check still fail on the pre-existing src/cli/program/route-specs.ts type error, and heartbeat-focused Vitest files hang locally in this environment, so the heartbeat guard stayed build-reviewed plus regression-covered in a focused test file but not locally completed end-to-end.

Thanks @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: 8e27b48596

ℹ️ 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/tui/tui-formatters.ts
Comment on lines +276 to +278
if (typeof content === "string") {
return sanitizeRenderableText(content).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.

P1 Badge Route assistant string content through phase filter

extractContentFromMessage still returns assistant content strings directly, so records shaped like { role: "assistant", phase: "commentary", content: "..." } bypass phase-aware filtering and render commentary text. This helper is consumed by TuiStreamAssembler for streamed/final display, so any provider path that emits message-level phase metadata on string content will still leak hidden commentary in the TUI despite this patch.

Useful? React with 👍 / 👎.

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
YoshiaKefasu pushed a commit to YoshiaKefasu/DennouAibou that referenced this pull request May 18, 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants