Skip to content

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

Closed as not planned

Description

@hnykda

Bug Description

When an OpenClaw agent performs multi-step tool calls, any text written between tool calls appears as standalone unthreaded messages in the Mattermost channel — outside the reply thread. Only the final answer appears in the thread.

Example:

  • Agent receives a question, writes "Let me check that for you...", then calls a tool
  • "Let me check that for you..." appears as an orphaned unthreaded message in the channel
  • The actual answer appears in the thread

Root Cause

In text_end block-streaming mode (Mattermost's delivery path), onBlockReply fires during streaming — before message_end reveals the stopReason. So at emission time, there's no way to know whether the text is intermediate "thinking" or the final answer.

Additionally, emitBlockChunk pushes text to state.assistantTexts independently of the onBlockReply path. This array is later consumed by buildEmbeddedRunPayloads to build the final Mattermost message. The deduplication via blockReplyPipeline.hasSentPayload() can't filter out discarded intermediate texts because they were never enqueued into the pipeline.

Two independent delivery paths both need fixing:

text_end → emitBlockChunk → assistantTexts.push() → buildEmbeddedRunPayloads → final Mattermost message
                         └→ emitBlockReplySafely  → onBlockReply (fires immediately — too early)

Fix (implemented in hnykda/openclaw, branch fix/suppress-pre-tool-text)

Based on the buffering approach described in PR #19932.

Layer 1 — Buffer onBlockReply until stopReason is known

Add to EmbeddedPiSubscribeState:

suppressPreToolText: boolean;      // true when onBlockReply is set
pendingBlockReplies: BlockReplyPayload[];

Instead of calling onBlockReply immediately in emitBlockReplySafely, push to pendingBlockReplies. At message_end, check stopReason:

  • "toolUse" → discard the buffer (intermediate turn, suppress it)
  • anything else → flush the buffer by calling onBlockReply for each payload

Layer 2 — Remove intermediate texts from assistantTexts

Capture preTurnAssistantTextBaseline before finalizeAssistantTexts updates it. When discarding for toolUse, also:

ctx.state.assistantTexts.splice(preTurnAssistantTextBaseline);
ctx.state.assistantTextBaseline = preTurnAssistantTextBaseline;

This ensures intermediate turn text doesn't appear in the final reply payload.

Files Changed

File Change
src/agents/pi-embedded-subscribe.handlers.types.ts Added suppressPreToolText, pendingBlockReplies to EmbeddedPiSubscribeState
src/agents/pi-embedded-subscribe.ts Buffering in outer emitBlockReplySafely; init state; clear in resetAssistantMessageState
src/agents/pi-embedded-subscribe.handlers.messages.ts Flush/discard logic at message_end; preTurnAssistantTextBaseline + assistantTexts.splice for Layer 2
src/agents/pi-embedded-subscribe.suppress-pre-tool-text.test.ts New test file — 4 tests covering both delivery paths

Tests

Four tests in src/agents/pi-embedded-subscribe.suppress-pre-tool-text.test.ts:

  1. text_end mode: intermediate turn with text + tool call → onBlockReply must NOT be called until final turn
  2. message_end mode: same suppression via non-streaming path
  3. Multiple sequential intermediate turns: all suppressed, only final reply delivered
  4. Regression test: subscription.assistantTexts must not contain intermediate text after a toolUse turn

Key insight: emitStreamingTurn helper must emit text_delta + text_end + message_end events (not just message_start + message_end) because in text_end mode, onBlockReply fires on text_end streaming events via flushBlockReplyBuffer → emitBlockChunk, not at message_end.

Known Remaining Limitation (GAMMA case)

If the model writes thinking text AND the actual reply as separate text blocks within the same final turn (stopReason="stop"), both get flushed — the thinking text appears in the thread alongside the answer. This is fundamentally harder to fix without a model-level signal. Options:

  1. enforceFinalTag — require replies inside <final>...</final> tags; strip text outside
  2. "Deliver only the last text block" — risky assumption

In practice this occurs rarely in normal usage. The primary production bug (intermediate tool-call turn leaks) is fully resolved.

Related PRs

PR

See hnykda/openclaw → fix/suppress-pre-tool-text for the full diff.

Activity

  1. Ryce commented on Mar 13, 2026

    @Ryce
  2. Vicky-v7 commented on Mar 18, 2026

    @Vicky-v7

    Additional confirmation: embedded CLI mode also affected

    We independently discovered the same root cause while investigating duplicate messages in embedded CLI mode (not just Mattermost).

    Symptoms

    When using openclaw agent --agent main --message "..." --json, the payloads array frequently contains 2 very similar but not identical text entries — one from the preamble turn (before tool call) and one from the final answer.

    This also manifests in Feishu delivery: users receive two near-identical messages from the agent.

    Root cause confirmation

    We traced it to buildEmbeddedRunPayloads() in reply-Bm8VrLQh.js (line ~110193 in the compiled dist):

    // Current (buggy): uses ALL accumulated texts
    const answerTexts = params.assistantTexts
    
    // Fix: only use texts from the final turn
    const lastTurnTexts = params.assistantTextBaseline != null 
        ? params.assistantTexts.slice(params.assistantTextBaseline) 
        : params.assistantTexts;
    const answerTexts = lastTurnTexts

    The assistantTextBaseline field already exists in state (initialized at line 107082, updated at line 107182), but is never passed to or used by buildEmbeddedRunPayloads(). The call site (line ~111172) needs to include assistantTextBaseline: attempt.assistantTextBaseline.

    Additional context

    This matches exactly with the Layer 2 fix described in OP's branch (fix/suppress-pre-tool-text), which splices assistantTexts at the baseline. Our approach achieves the same result by slicing at read time rather than mutating the array.

    Both approaches fix the same underlying issue: buildEmbeddedRunPayloads consumes cumulative assistant texts instead of turn-local texts.

    Would love to see this merged — it affects all delivery channels, not just Mattermost.

  3. openclaw-barnacle commented on Apr 28, 2026

    @openclaw-barnacle

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

  4. added
    stale
    on Apr 28, 2026
  5. clawsweeper commented on Apr 28, 2026

    @clawsweeper
    Contributor

    Closing this as duplicate or superseded after Codex automated review.

    This issue should close as a duplicate of the broader open messaging-channel tracker #25592. Current main does not implement the proposed stopReason-gated buffering/splice fix, but #25592 already tracks the same remaining core behavior across channels, while Mattermost-specific threading/preview handling has since improved separately.

    Best possible solution:

    Keep #25592 as the canonical open bug for suppressing unphased pre-tool assistant text across messaging channels. The eventual fix should land in the generic embedded subscribe and payload assembly paths, with Mattermost covered through shared channel delivery tests rather than a Mattermost-only patch.

    What I checked:

    So I’m closing this here and keeping the remaining discussion on the canonical linked item.

    Codex Review notes: model gpt-5.5, reasoning high; reviewed against d48c3e12a5d8.

  6. locked as resolved and limited conversation to collaborators on May 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stale

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions