Skip to content

fix(go-agent): message double - #17353

Merged
yuzhichang merged 7 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:fix/agent-Message-double
Jul 24, 2026
Merged

yuzhichang merged 7 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:fix/agent-Message-double

Conversation

@Harry-Hz-Zhang

Copy link
Copy Markdown
Contributor

Summary

  • Preserve all streamed Agent deltas when Message consumes deferred output.
  • Prevent duplicate final answers while keeping Agent and Message event ordering consistent.
  • Add regression coverage for complete deferred streaming output.

Testing

  • CGO_ENABLED=0 go test ./internal/agent/component ./internal/agent/runtime -count=1

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 24, 2026
@Harry-Hz-Zhang Harry-Hz-Zhang added the ci Continue Integration label Jul 24, 2026
@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 36112207-94c2-49cc-a7ce-5d7ef6c2e1c0

📥 Commits

Reviewing files that changed from the base of the PR and between f7cb203 and f994987.

📒 Files selected for processing (7)
  • internal/agent/component/agent.go
  • internal/agent/component/agent_test.go
  • internal/agent/component/message.go
  • internal/agent/component/message_test.go
  • internal/agent/runtime/context.go
  • internal/agent/runtime/context_test.go
  • internal/service/agent.go
🚧 Files skipped from review as they are similar to previous changes (5)
  • internal/agent/component/agent_test.go
  • internal/agent/component/agent.go
  • internal/service/agent.go
  • internal/agent/runtime/context.go
  • internal/agent/component/message_test.go

📝 Walkthrough

Walkthrough

Agent responses can now defer execution to downstream Message nodes through runtime-managed streams. Canvas scheduling delays node completion, Message resolves streamed templates with thinking events, duplicate emissions are suppressed, and service-level terminal events account for emitted or suppressed message state.

Changes

Deferred streaming runtime

Layer / File(s) Summary
Runtime deferred-stream contracts
internal/agent/runtime/context.go, internal/agent/runtime/context_test.go
Adds deferred streams, execution options, delta sinks, thinking-aware canvas events, deferred-node completion, synchronized emission state, and lifecycle tests.
Agent deferred production
internal/agent/component/agent.go, internal/agent/component/agent_test.go, internal/entity/models/*
Agent execution can return deferred streams, route deltas through sinks, avoid duplicate final answers, and no longer uses ChatConfig.StreamCallback.

Canvas and Message flow

Layer / File(s) Summary
Canvas execution and completion lifecycle
internal/agent/canvas/*
Detects direct Agent-to-Message edges, propagates execution options, and delays node_finished until deferred content completes.
Message consumption and run finalization
internal/agent/component/message*, internal/service/agent.go
Message templates consume deferred streams and emit ordered reasoning/content events; service finalization gates aggregate message events based on emission state.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CanvasScheduler
  participant AgentComponent
  participant RuntimeDeferredStream
  participant MessageComponent
  participant AgentService
  CanvasScheduler->>AgentComponent: pass deferral execution options
  AgentComponent-->>RuntimeDeferredStream: return deferred stream
  MessageComponent->>RuntimeDeferredStream: open stream
  RuntimeDeferredStream-->>MessageComponent: emit reasoning and content deltas
  MessageComponent->>AgentService: present canvas message events
  AgentService-->>CanvasScheduler: complete deferred node and emit terminal events
Loading

Possibly related PRs

Suggested labels: ☯️ refactor

Suggested reviewers: euvre, haruko386, yuzhichang

Poem

I’m a rabbit with streams in my ears,
Deferred little answers hop past old fears.
Messages bloom without doubling the sound,
Thinking then content arrive safe and round.
The workflow waits, then completion bells ring—
Hop, hop, hooray for the new streaming thing!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.91% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly references the core fix: duplicate Go agent messages.
Description check ✅ Passed The description includes the required Summary and Testing details and explains the problem and fix.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai 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.

Actionable comments posted: 8

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/agent/component/agent.go (1)

248-295: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Don’t stop Agent model streaming after the first chunk.

After ChatConfig.StreamCallback is removed, emitAgentModelStreams is the only delta-forwarding path for Agent components without a direct Message downstream. Its guard skips all chunks once AgentMessageEventsEmitted(ctx) becomes true — and the final invokeNow consolidated emission is also skipped because streamed is true. The deferred Message-sink path avoids this by checking !HasDeferredAgentMessageSink(ctx), but the eager eino stream loop needs the same per-chunk forward behavior, not a one-shot suppression.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/agent/component/agent.go` around lines 248 - 295, The guard in
emitAgentModelStreams must not suppress subsequent Agent model chunks after
AgentMessageEventsEmitted(ctx) becomes true. Remove or adjust the one-shot event
check so every eligible non-empty assistant message is forwarded through
runtime.EmitAgentMessage, while preserving the deferred-sink condition and
existing filtering behavior.
🧹 Nitpick comments (1)
internal/agent/component/message_test.go (1)

272-330: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Missing regression coverage for non-deferred templated refs.

All new tests here use either plain content input (no {{...}}) or a template whose ref resolves to an actual *runtime.DeferredStream. None cover a template referencing an ordinary (non-deferred) state variable, e.g. {{node@field}} where field holds a plain string — which is exactly the case that triggers the double-emission bug flagged in internal/agent/component/message.go's resolveDeferredTemplate. Want me to add a test asserting exactly one WithCanvasMessageEmitter call for that case?

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/agent/component/message_test.go` around lines 272 - 330, The tests
lack regression coverage for templated references to ordinary state values. Add
a test alongside TestMessage_ConsumesDeferredAgentStream that stores a plain
string in a state variable, invokes Message with a template such as
{{node@field}}, and uses WithCanvasMessageEmitter to count emissions; assert the
rendered content is correct and exactly one emitter call occurs.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/agent/component/agent.go`:
- Around line 713-726: The deferred stream created in AgentComponent.Invoke must
apply a fresh Agent timeout when DeferredStream.Open executes. Update the Open
callback to wrap its received openCtx with the existing Agent-class timeout
mechanism before calling c.invokeNow, preserving the sink attachment and
deferred execution behavior.

In `@internal/agent/component/message.go`:
- Around line 189-201: Update resolveDeferredTemplate and its callers in
Message.Invoke so templated messages with ordinary, non-deferred references are
not emitted during resolution and then emitted again during final rendering.
Track whether the template actually contains a DeferredStream, preserve the
resolved value for non-streamed templates, and ensure EmitCanvasMessage is
called exactly once while retaining the existing deferred-stream behavior.
- Around line 366-401: Update the deferred stream handling around deferred.Open
so finalText uses the completed result["content"] whenever available, preserving
visible.String() only as a fallback when the result has no content. Ensure the
grounded or artifact-annotated content is used for state.SetVar,
CompleteDeferredNode, and the returned output while retaining streamed deltas
for live events.

In `@internal/agent/runtime/context.go`:
- Around line 213-222: Update the WithCanvasMessageEventEmitter doc comment to
remove the compatibility and migration framing, including the reference to
existing plain-content callers. Describe only its current role of installing a
Message presentation callback that supports thinking-boundary-aware
presentation.
- Around line 276-293: Update the EmitCanvasMessageEvent doc comment to remove
the “historical” and “preserving existing component tests and non-streaming
callers” compatibility wording, while retaining a concise description of the
plain-content fallback behavior and leaving the implementation unchanged.
- Around line 233-264: In internal/agent/runtime/context.go:233-264, update
EmitAgentMessage to copy callbacks under sinkState.mu/state.mu, unlock before
invoking sink or state.emit, then re-lock only to update emitted and
agentContent; apply the same pattern in
internal/agent/runtime/context.go:295-330 for EmitCanvasMessage, 375-380 for
FinalizeAgentMessage, and 383-400 for ResetAgentMessageEmission, copying
finalize/reset callbacks before unlocking and performing state updates
afterward.
- Around line 114-122: Update RegisterDeferredNode to preserve existing
callbacks when the same nodeID is registered again by storing a queue or
collection of pending completions per node instead of overwriting the prior
callback. Update CompleteDeferredNode and CompleteAllDeferredNodes to invoke
every queued callback exactly once while retaining existing synchronization and
cleanup behavior.

In `@internal/service/agent.go`:
- Around line 1421-1427: The service-level shouldEmitMessage calculation after
FinalizeAgentMessage must not rely on invocation-scoped
AgentMessageEventsEmitted() or AgentMessageEventsSuppressed() values. Track
whether any Agent node emitted content and whether terminal message emission is
suppressed across the entire run, then use those run-level values to decide
terminal message/message_end events; preserve per-node suppression only for
preventing duplicate aggregation.

---

Outside diff comments:
In `@internal/agent/component/agent.go`:
- Around line 248-295: The guard in emitAgentModelStreams must not suppress
subsequent Agent model chunks after AgentMessageEventsEmitted(ctx) becomes true.
Remove or adjust the one-shot event check so every eligible non-empty assistant
message is forwarded through runtime.EmitAgentMessage, while preserving the
deferred-sink condition and existing filtering behavior.

---

Nitpick comments:
In `@internal/agent/component/message_test.go`:
- Around line 272-330: The tests lack regression coverage for templated
references to ordinary state values. Add a test alongside
TestMessage_ConsumesDeferredAgentStream that stores a plain string in a state
variable, invokes Message with a template such as {{node@field}}, and uses
WithCanvasMessageEmitter to count emissions; assert the rendered content is
correct and exactly one emitter call occurs.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5c2ac70b-c2e3-4db8-bd4a-83bb126f3e1b

📥 Commits

Reviewing files that changed from the base of the PR and between bdfc3ad and 6322859.

📒 Files selected for processing (12)
  • internal/agent/canvas/loop_subgraph.go
  • internal/agent/canvas/node_body.go
  • internal/agent/canvas/scheduler.go
  • internal/agent/component/agent.go
  • internal/agent/component/agent_test.go
  • internal/agent/component/message.go
  • internal/agent/component/message_test.go
  • internal/agent/runtime/context.go
  • internal/entity/models/llm.go
  • internal/entity/models/llm_test.go
  • internal/entity/models/types.go
  • internal/service/agent.go
💤 Files with no reviewable changes (2)
  • internal/entity/models/llm.go
  • internal/entity/models/types.go

Comment thread internal/agent/component/agent.go Resolved
Comment thread internal/agent/component/message.go Resolved
Comment thread internal/agent/component/message.go Resolved
Comment thread internal/agent/runtime/context.go Resolved
Comment thread internal/agent/runtime/context.go Resolved
Comment thread internal/agent/runtime/context.go Resolved
Comment thread internal/agent/runtime/context.go Resolved
Comment thread internal/service/agent.go Resolved
@yuzhichang
yuzhichang merged commit 601742e into infiniflow:main Jul 24, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants