Skip to content

fix(ui): prevent duplicate assistant messages when session.message races with chat final - #92732

Closed
scotthuang wants to merge 2 commits into
openclaw:mainfrom
scotthuang:debug/webchat-duplicate-messages
Closed

scotthuang wants to merge 2 commits into
openclaw:mainfrom
scotthuang:debug/webchat-duplicate-messages

Conversation

@scotthuang

Copy link
Copy Markdown
Contributor

Summary

When a plugin registers a before_agent_finalize hook that blocks streaming, session.message and chat final can arrive in an unexpected order, causing both paths to write to chatMessages concurrently — producing duplicate assistant messages in webchat.

This PR establishes a single-terminal-owner model: only chat final/error/aborted owns ending the local chat run and reconciling transcript state. session.message during an active run only records a pendingTranscriptSync flag; the terminal handler consumes it after the final message is committed, avoiding concurrent writes to chatMessages.

  • Establishes chat final/error/aborted as the sole owner of local run termination and transcript reconciliation
  • session.message during an active run records pendingTranscriptSync and returns immediately — no loadChatHistory, loadSessions, or run reconciliation
  • Terminal handler consumes pending sync at most once, after committing the final message
  • Removes previous workarounds: text-signature dedup, chatRunId guards, polling retry mechanisms, and all [DEDUPE] debug logs

Linked context

Closes # (no existing issue)

Related to internal design doc at docs/duplicate-message-ordering-design.md

Real behavior proof (required for external PRs)

  • Behavior or issue addressed: Duplicate assistant messages in webchat when a before_agent_finalize hook defers terminal delivery
  • Real environment tested: macOS, source-built gateway on port 18789
  • Exact steps or command run after this patch:
    1. Plugin with before_agent_finalize hook registered
    2. Send a chat message
    3. Observe webchat UI — only one assistant reply appears
  • Evidence after fix: Webchat shows a single assistant message per turn; no duplicate entries in chatMessages
  • Observed result after fix: No duplicate messages across multiple test runs with the hook scenario
  • What was not tested: Multi-client scenario; subagent session.message sources; transcript injection paths
  • Proof limitations or environment constraints: Tested on single-client macOS setup

Tests and validation

Which commands did you run?

  • pnpm test ui/src/ui/app-gateway.sessions.node.test.ts — 35 tests pass
  • pnpm test ui/src/ui/controllers/chat.test.ts — 119 tests pass
  • pnpm test ui/src/ui/controllers/sessions.test.ts — 77 tests pass
  • pnpm test ui/src/ui/chat/build-chat-items.test.ts — 33 tests pass
  • pnpm test src/gateway/server-chat.agent-events.test.ts — 170 tests pass
  • pnpm test src/gateway/session-message-events.test.ts — 68 tests pass
  • pnpm build:strict-smoke — passes
  • pnpm ui:build — passes

What regression coverage was added or updated?

  • 7 new test cases in app-gateway.sessions.node.test.ts covering: session.message before/after chat final, multiple session.messages coalescing, old-run terminal not consuming new-run pending sync, session-switch guard
  • 2 new regression tests in chat.test.ts verifying same-text different-turn messages are both preserved, and no text-only dedup occurs

What failed before this fix, if known?

  • Duplicate assistant messages appeared when a before_agent_finalize hook deferred terminal delivery, causing session.message to arrive before chat final

Risk checklist

Did user-visible behavior change? (Yes/No)
Yes — eliminates duplicate assistant messages

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

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

What is the highest-risk area?
Event ordering invariants. The fix assumes chat final always eventually arrives as the terminal owner. If a chat final is never delivered (e.g., gateway crash mid-run), pendingTranscriptSync would never be consumed.

How is that risk mitigated?
Gateway lifecycle broadcasts (chat final → sessions.changed phase:end) are synchronous on the same WebSocket connection. The sessions.changed path still performs reconciliation as a safety net for runs without a local owner. This PR only restricts session.message from reconciling during active runs.

Current review state

What is the next action?
Awaiting reviewer feedback

What is still waiting on author, maintainer, CI, or external proof?
All local tests pass; awaiting CI and maintainer review

@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling size: L triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels Jun 13, 2026
@clawsweeper

clawsweeper Bot commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

Close: the WebChat ordering race is real, but this branch should not remain the landing candidate because it removes current stale-run recovery and the overlapping safer work is already tracked by a proof-positive PR plus the generic duplicate-message issue.

Canonical path: Close this branch as superseded, keep the safer deferred-transcript implementation on #91810, and leave broader duplicate-message follow-up on #85771.

So I’m closing this here and keeping the remaining discussion on #91810 and #85771.

Review details

Best possible solution:

Close this branch as superseded, keep the safer deferred-transcript implementation on #91810, and leave broader duplicate-message follow-up on #85771.

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

No high-confidence live reproduction was established in this review. Source and existing tests show the relevant session.message versus terminal-chat ordering path, but the PR body only gives prose observations without observable after-fix output.

Is this the best way to solve the issue?

No. The single-terminal-owner direction is plausible, but this branch removes the existing stale-run recovery path; the safer solution preserves fallback reconciliation while narrowing the duplicate/reload case as in the canonical related PR.

Security review:

Security review cleared: Cleared: the final PR diff only changes Control UI TypeScript and tests, with no dependency, workflow, permission, credential, package, or code-execution surface change.

AGENTS.md: found and applied where relevant.

What I checked:

  • Repository policy read: Root AGENTS.md and scoped ui/AGENTS.md were read fully; the review applied the root requirement to check current source, tests, related PRs, proof, and history instead of diff-only review. (AGENTS.md:1, 45e36a241a79)
  • Current-main stale-run recovery: Current main keeps a recovery path for active-run session.message: it records the pending reload, calls loadSessions, and can later replay the deferred history reload after a stale run is cleared. (ui/src/ui/app-gateway.ts:1178, 45e36a241a79)
  • Current-main regression coverage for recovery: Existing tests assert that a stale active run is cleared, history reloads, pending queue items clear, and the chat queue flushes after the session refresh resolves. (ui/src/ui/app-gateway.sessions.node.test.ts:793, 45e36a241a79)
  • PR removes that fallback: At PR head, session.message applies session metadata with reconcileCurrentChatRun: false and returns while host.chatRunId is set, leaving pending sync dependent on a later terminal chat event. (ui/src/ui/app-gateway.ts:1175, 874327b09e74)
  • Canonical overlapping PR is open and proof-positive: The related PR preserves the existing stale-run loadSessions replay path while adding a narrower thinking-aware deferred reload, has proof: sufficient, and is currently open and mergeable clean. (ui/src/ui/app-gateway.ts:1173, f68625750c83)
  • Generic duplicate-message work remains tracked: The broader WebChat duplicate assistant message report remains open separately, so closing this branch does not lose the canonical issue for non-thinking duplicate-message cases.

Likely related people:

  • vincentkoc: Authored merged WebChat final reload reconciliation and the stale-run deferred reload follow-up that this PR would remove or replace. (role: feature-history owner; confidence: high; commits: cbd2ab17c64a, 0efb227f465f; files: ui/src/ui/app-gateway.ts, ui/src/ui/chat-event-reload.ts, ui/src/ui/controllers/chat.ts)
  • BunsDev: Authored the merged live transcript run-state work that changed selected-session session.message, gateway chat delivery, and WebChat transcript behavior near this PR's surface. (role: recent area contributor; confidence: high; commits: 346cba2f0ac6, 2ecf9250d7b5; files: ui/src/ui/app-gateway.ts, ui/src/ui/controllers/sessions.ts, ui/src/ui/chat/build-chat-items.ts)
  • scotthuang: Beyond authoring this PR, also authored the earlier merged active-send session.message guard that this branch builds on. (role: prior active-run guard contributor; confidence: medium; commits: 9eb497c4f5a8, 28871e7dd95d, 7734a40a5650; files: ui/src/ui/app-gateway.ts, ui/src/ui/app-gateway.sessions.node.test.ts)
  • steipete: Authored the final-event history reload optimization that the later deferred transcript fixes narrow rather than revert. (role: adjacent feature-history owner; confidence: medium; commits: dc6afeb4f882; files: ui/src/ui/app-gateway.ts, ui/src/ui/chat-event-reload.ts)

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

@scotthuang scotthuang left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review found two blocking issues. The single-terminal-owner direction is correct, but this revision regresses the existing no-reload terminal path and still contains debug instrumentation that breaks required checks. Local proof: the focused changed tests pass, but ui/src/ui/app-gateway.node.test.ts fails 3 existing cases and focused oxlint reports 6 errors.

Comment thread ui/src/ui/app-gateway.ts Outdated
return;
}
if (shouldReplayDeferredSessionMessageReload && !historyReloaded) {
if (shouldConsumePendingTranscriptSync && !historyReloaded) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Consume the pending marker without always reloading history. A normal webchat turn publishes session.message while the run is active, so this branch now calls chat.history even when final already carried the complete assistant message. That restores the optimistic-message replacement/flicker path the surrounding code intentionally avoids. node scripts/run-vitest.mjs ui/src/ui/app-gateway.node.test.ts currently fails three existing cases, including does not reload chat history after final assistant payload reconciles an active run. Keep the pending sync clear, but only reload for aborted/error or a final that actually needs history (shouldReloadHistoryForFinalEvent(payload)).

Comment thread ui/src/ui/chat/build-chat-items.ts Outdated

export function buildChatItems(props: BuildChatItemsProps): Array<ChatItem | MessageGroup> {
let items: ChatItem[] = [];
const debugItems = typeof (globalThis as any).window !== "undefined";

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Remove the leftover [DEDUPE] instrumentation before merge. This hot render path introduces explicit any values and an unused previews computation; related debug warnings also remain in src/gateway/server-chat.ts and src/agents/embedded-agent-subscribe.handlers.lifecycle.ts, contrary to the PR summary. Focused oxlint reports six errors, including no-unused-vars, three no-explicit-any/style errors here, and the now-unused scopedAgentListParamsForSession import.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jun 13, 2026
@openclaw-barnacle openclaw-barnacle Bot removed gateway Gateway runtime agents Agent runtime and tooling labels Jun 13, 2026
@clawsweeper

clawsweeper Bot commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

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

Labels

app: web-ui App: web-ui merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant