Skip to content

fix: suppress intermediate assistant text from leaking to Mattermost channels (#45134) - #45136

Closed
hnykda wants to merge 2 commits into
openclaw:mainfrom
hnykda:fix/suppress-pre-tool-text
Closed

hnykda wants to merge 2 commits into
openclaw:mainfrom
hnykda:fix/suppress-pre-tool-text

Conversation

@hnykda

@hnykda hnykda commented Mar 13, 2026

Copy link
Copy Markdown
Contributor

Fixes #45134

Summary

When an agent performs multi-step tool calls in text_end streaming mode (Mattermost's delivery path), any text written between tool calls leaked as standalone unthreaded messages in the Mattermost channel. This PR implements the buffering approach from #19932.

Two-layer fix

Layer 1 — Buffer onBlockReply until stopReason is known

Added to EmbeddedPiSubscribeState:

suppressPreToolText: boolean;
pendingBlockReplies: BlockReplyPayload[];

Both emitBlockReplySafely functions (outer in subscribe.ts for text_end mode, local in handleMessageEnd for message_end mode) now push to pendingBlockReplies instead of calling onBlockReply immediately. At message_end, the buffer is flushed (final turn) or discarded (stopReason === "toolUse").

Layer 2 — Remove intermediate texts from assistantTexts

emitBlockChunk pushes text to state.assistantTexts independently of the onBlockReply path. This array is later consumed by buildEmbeddedRunPayloads. The hasSentPayload deduplication couldn't filter these out because discarded intermediate texts were never enqueued into the pipeline.

Fix: capture preTurnAssistantTextBaseline before finalizeAssistantTexts updates it, then splice assistantTexts back when discarding for toolUse.

Tests

New file: src/agents/pi-embedded-subscribe.suppress-pre-tool-text.test.ts

4 tests covering:

  • text_end mode suppression
  • message_end mode suppression
  • Multiple sequential intermediate turns all suppressed
  • assistantTexts regression (Layer 2)

Known limitation

Text written by the model in the final turn (stopReason=stop) before the actual answer cannot be suppressed without a model-level signal (e.g. enforceFinalTag). The primary production bug (intermediate tool-call turns leaking) is fully resolved.

Related

hnykda and others added 2 commits March 13, 2026 13:08
…enclaw#19932)

Buffer all onBlockReply payloads during each assistant turn; at message_end,
discard the buffer when stopReason === "toolUse" (tool-calling turn) or flush
it when stopReason === "stop" (final answer). Handles both text_end (streaming)
and message_end (non-streaming) delivery paths.

Adds EmbeddedPiSubscribeState.suppressPreToolText (enabled whenever onBlockReply
is registered) and pendingBlockReplies buffer. Both the outer emitBlockReplySafely
in subscribeEmbeddedPiSession (streaming/text_end path) and the local one in
handleMessageEnd (message_end path) buffer through pendingBlockReplies.

Regression test covers text_end mode (streaming), message_end mode, and
multiple intermediate turns all suppressed before a single final delivery.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…scard (openclaw#19932)

The previous suppression fix buffered onBlockReply calls and discarded
them for toolUse turns — preventing intermediate text from being streamed
to Mattermost as separate messages. But the texts were already pushed to
state.assistantTexts in emitBlockChunk before the stopReason was known.
This meant they survived in the final reply payload (hasSentPayload
deduplication can't filter them because they never touched the pipeline).

Fix: capture preTurnAssistantTextBaseline at the start of handleMessageEnd
(before finalizeAssistantTexts updates it), and when discarding for
toolUse, splice assistantTexts back to that baseline and reset the
baseline. Adds a regression test verifying intermediate texts are absent
from assistantTexts after a toolUse turn.
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Mar 13, 2026
@greptile-apps

greptile-apps Bot commented Mar 13, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes intermediate assistant text leaking as standalone unthreaded Mattermost messages during multi-step tool-call sequences. It implements a two-layer buffering approach: all onBlockReply calls are held in pendingBlockReplies until message_end, at which point they are either flushed (non-toolUse stop) or discarded and spliced out of assistantTexts (stopReason === "toolUse").

Key changes:

  • suppressPreToolText: Boolean(params.onBlockReply) — effectively a constant that switches the subscribe session from "emit immediately on text_end" to "buffer everything until message_end". Works correctly for both text_end and message_end delivery modes.
  • preTurnAssistantTextBaseline is captured before finalizeAssistantTexts updates it, enabling a precise splice that removes only the current intermediate turn's texts from assistantTexts (Layer 2 fix).
  • resetAssistantMessageState clears pendingBlockReplies at message_start as a safety net for any corner-case early-returns (e.g. deterministicApprovalPromptSent).
  • Four targeted regression tests cover both streaming modes, multiple sequential intermediate turns, and the assistantTexts dedup path.

Note on behavioral scope: suppressPreToolText being always true when onBlockReply is provided means text_end-mode callers that previously received block replies in real-time (per text block) will now receive them only at message_end. For Mattermost this is correct, but any other consumer relying on sub-message streaming delivery via onBlockReply should be validated separately.

Confidence Score: 4/5

  • This PR is safe to merge for the primary Mattermost use case; the buffering approach is logically sound and well-tested.
  • The two-layer fix is correct: pendingBlockReplies is populated from both the outer (text_end) and inner (message_end) emitBlockReplySafely paths, flushed or discarded based on stopReason, and assistantTexts is spliced precisely using preTurnAssistantTextBaseline. Edge cases like resetAssistantMessageState clearing the buffer at message_start and the deterministicApprovalPromptSent early-return are handled safely. The score is 4 rather than 5 because the change silently shifts all onBlockReply callers from real-time text_end delivery to deferred message_end delivery, which could affect non-Mattermost consumers that were not explicitly validated in this PR.
  • No files require special attention, though callers of subscribeEmbeddedPiSession that provide onBlockReply and rely on sub-message streaming cadence should be reviewed separately.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/pi-embedded-subscribe.suppress-pre-tool-text.test.ts
Line: 1-10

Comment:
**Misplaced JSDoc block comment**

The module-level JSDoc comment is placed between the first `import` statement and the rest of the imports. Most linters/formatters expect the file-level doc comment to appear before all imports, or alternatively the imports to be grouped before the comment. Consider moving it before line 1:

```suggestion
/**
 * Tests for suppressPreToolText behavior: intermediate text blocks written
 * between tool calls must NOT be delivered via onBlockReply.
 *
 * Regression test for the Mattermost intermediate-text leak:
 * https://github.com/openclaw/openclaw/pull/19932
 */
import type { AssistantMessage } from "@mariozechner/pi-ai";
import { describe, expect, it, vi } from "vitest";
import { createSubscribedSessionHarness } from "./pi-embedded-subscribe.e2e-harness.js";
```

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

Last reviewed commit: 35716ff

Comment on lines +1 to +10
import type { AssistantMessage } from "@mariozechner/pi-ai";
/**
* Tests for suppressPreToolText behavior: intermediate text blocks written
* between tool calls must NOT be delivered via onBlockReply.
*
* Regression test for the Mattermost intermediate-text leak:
* https://github.com/openclaw/openclaw/pull/19932
*/
import { describe, expect, it, vi } from "vitest";
import { createSubscribedSessionHarness } from "./pi-embedded-subscribe.e2e-harness.js";

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.

Misplaced JSDoc block comment

The module-level JSDoc comment is placed between the first import statement and the rest of the imports. Most linters/formatters expect the file-level doc comment to appear before all imports, or alternatively the imports to be grouped before the comment. Consider moving it before line 1:

Suggested change
import type { AssistantMessage } from "@mariozechner/pi-ai";
/**
* Tests for suppressPreToolText behavior: intermediate text blocks written
* between tool calls must NOT be delivered via onBlockReply.
*
* Regression test for the Mattermost intermediate-text leak:
* https://github.com/openclaw/openclaw/pull/19932
*/
import { describe, expect, it, vi } from "vitest";
import { createSubscribedSessionHarness } from "./pi-embedded-subscribe.e2e-harness.js";
/**
* Tests for suppressPreToolText behavior: intermediate text blocks written
* between tool calls must NOT be delivered via onBlockReply.
*
* Regression test for the Mattermost intermediate-text leak:
* https://github.com/openclaw/openclaw/pull/19932
*/
import type { AssistantMessage } from "@mariozechner/pi-ai";
import { describe, expect, it, vi } from "vitest";
import { createSubscribedSessionHarness } from "./pi-embedded-subscribe.e2e-harness.js";
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/pi-embedded-subscribe.suppress-pre-tool-text.test.ts
Line: 1-10

Comment:
**Misplaced JSDoc block comment**

The module-level JSDoc comment is placed between the first `import` statement and the rest of the imports. Most linters/formatters expect the file-level doc comment to appear before all imports, or alternatively the imports to be grouped before the comment. Consider moving it before line 1:

```suggestion
/**
 * Tests for suppressPreToolText behavior: intermediate text blocks written
 * between tool calls must NOT be delivered via onBlockReply.
 *
 * Regression test for the Mattermost intermediate-text leak:
 * https://github.com/openclaw/openclaw/pull/19932
 */
import type { AssistantMessage } from "@mariozechner/pi-ai";
import { describe, expect, it, vi } from "vitest";
import { createSubscribedSessionHarness } from "./pi-embedded-subscribe.e2e-harness.js";
```

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

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@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: 35716ff3e6

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

successfulCronAdds: 0,
pendingMessagingMediaUrls: new Map(),
deterministicApprovalPromptSent: false,
suppressPreToolText: Boolean(params.onBlockReply),

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 Keep text_end block replies streaming for non-tool turns

suppressPreToolText is enabled up front for any session with onBlockReply, so all block replies are buffered even before we know whether the turn is a tool-use turn. In blockReplyBreak: "text_end" mode this changes normal stop turns from emitting at text_end to emitting only at message_end, which regresses the existing text_end streaming behavior (for example, src/agents/pi-embedded-subscribe.subscribe-embedded-pi-session.emits-block-replies-text-end-does-not.test.ts expects emission on text_end) and risks dropping content if message_end is missing because pending payloads are later cleared on reset. Buffering should be conditional on detecting a tool-use turn rather than globally enabled.

Useful? React with 👍 / 👎.

@steipete

Copy link
Copy Markdown
Contributor

Closing this as implemented after Codex review.

Current main already addresses the Mattermost leak through the newer draft-preview delivery path: Mattermost disables generic block streaming for inbound replies, streams partial/tool/thinking updates into one preview post, and finalizes that post in place. That behavior is documented, covered by Mattermost tests, present in the shipped v2026.4.22 release, and the old generic text_end semantics this PR changes are still intentionally preserved by core tests.

What I checked:

So I’m closing this as already implemented rather than keeping a duplicate issue open.

Review notes: reviewed against 4630ce3d9e2f; fix evidence: release v2026.4.22, commit 00bd2cf7a376.

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

Labels

agents Agent runtime and tooling size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Intermediate assistant text leaks to Mattermost channels as unthreaded messages during multi-step tool calls

2 participants