Skip to content

fix(agent): collect CodeExec artifacts from ReAct tool responses - #16609

Merged
yuzhichang merged 1 commit into
infiniflow:mainfrom
euvre:fix/go-agent-codeexec-artifacts
Jul 5, 2026
Merged

yuzhichang merged 1 commit into
infiniflow:mainfrom
euvre:fix/go-agent-codeexec-artifacts

Conversation

@euvre

@euvre euvre commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Summary

The Go backend Agent component was not returning artifacts produced by the CodeExec tool. While the Python agent collects the "_ARTIFACTS" envelope from tool responses and appends artifact markdown to the final content, the Go agent only returned the assistant text, so generated images were missing from the chat output.

Changes

  • Wire react.WithMessageFuture() in runEinoReActAgent and store the resulting MessageFuture in the invocation context.
  • After the ReAct loop finishes, drain the future and extract _ARTIFACTS entries from every tool response message.
  • Support reading the tool payload from both msg.Content and msg.UserInputMultiContent to match eino's tool contract.
  • De-duplicate artifacts by URL and render images as ! and other files as download links.
  • Add agent_artifact_test.go with a regression test that simulates a CodeExec-style tool response carrying an image artifact and verifies it is collected and formatted.

Verification

  • go test ./internal/agent/component/... -run TestAgent_ReActAgent_CollectsArtifactsFromCodeExecTool passes.
  • go test ./internal/agent/component/... -count=1 compiles; the only failure is an unrelated DNS-pinning timeout test (TestInvoke_ProxyDNSPin).
  • gofmt clean for modified files.

Related

Fixes the behavior shown in the screenshot where the Go agent ignored the CodeExec-generated PNG artifact.

Use react.WithMessageFuture() so the Go AgentComponent can inspect every
tool response produced during the ReAct loop. Collect entries from the
_ARTIFACTS JSON envelope returned by the CodeExec tool and append the
artifact markdown to the final content, matching the Python backend
behavior.

- Add context-based artifact collector around the MessageFuture.
- Parse _ARTIFACTS from tool message Content or UserInputMultiContent.
- De-duplicate artifacts by URL and render images as ![](url).
- Add regression test covering artifact collection from CodeExec-style
tool responses.

Fixes: agent ignored CodeExec artifacts and returned plain text only.
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 3, 2026
@euvre euvre added the ci Continue Integration label Jul 3, 2026
@coderabbitai

coderabbitai Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The Agent component's ReAct execution now captures a react.MessageFuture per invocation, storing it in context for later use. After generation, tool-call messages are drained, parsed for a _ARTIFACTS JSON envelope, and de-duplicated into artifact entries used to populate output and markdown. A test suite validates this flow end-to-end using scripted models and tools.

Changes

Artifact Collection Feature

Layer / File(s) Summary
MessageFuture wiring in ReAct invocation
internal/agent/component/agent.go
Registers a MessageFuture via react.WithMessageFuture(), stores it in context, passes it into agent.Generate, and threads ctx into collectArtifactsFromToolCalls.
Artifact extraction and de-duplication logic
internal/agent/component/agent.go
Adds context-key helpers and collectArtifactsFromToolCalls, extractArtifactsFromToolMessage, and toolMessageTextContent to parse _ARTIFACTS JSON and build de-duplicated artifactEntry results.
Artifact collection test harness
internal/agent/component/agent_artifact_test.go
Adds scripted model/tool stubs, a replayable slice-backed MessageFuture, and a test verifying artifact extraction, naming, URL, and markdown output.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Invoke as AgentComponent.Invoke
  participant Run as runEinoReActAgent
  participant Generate as agent.Generate
  participant Future as MessageFuture
  participant Collector as collectArtifactsFromToolCalls

  Invoke->>Run: start ReAct run
  Run->>Future: react.WithMessageFuture()
  Run->>Generate: Generate(ctx, input, futureOption)
  Generate-->>Future: emits tool call messages
  Invoke->>Collector: collectArtifactsFromToolCalls(ctx, msg)
  Collector->>Future: drain tool-role messages
  Future-->>Collector: tool response JSON content
  Collector-->>Invoke: de-duplicated artifactEntry list
Loading

Poem

A rabbit hops through tool call trails,
Gathering artifacts, JSON tales, 🥕
Futures drained, entries de-duped clean,
Markdown links now brightly seen,
Hop, hop, hooray for tests that pass! 🐇✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: collecting CodeExec artifacts from ReAct tool responses.
Description check ✅ Passed The description includes the required Summary section and adds relevant context, changes, verification, and related notes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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: 2

🤖 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 164-166: The future is only stored in the local child context
inside runEinoReActAgent, so Invoke still sees a ctx without an artifact
collector and collection is skipped. Move the future holder setup into Invoke
before calling agentRunner(ctx, p), and update getArtifactCollector to read the
future from that shared holder instead of relying on the local context copy.
Keep the existing react.WithMessageFuture flow, but ensure the future is visible
to both Invoke and runEinoReActAgent through the shared context path.
- Around line 742-746: extractArtifactsFromToolMessage currently stops after the
first non-empty text source, so it can miss artifacts when msg.Content has text
and _ARTIFACTS appears later in UserInputMultiContent. Update this logic to
inspect all available text payloads in order—starting with Content, then each
text part from UserInputMultiContent, using toolMessageTextContent or
equivalent—until an artifact envelope is found. Apply the same multi-source scan
behavior in the related artifact parsing path around the referenced extraction
helpers so both locations detect artifacts consistently.
🪄 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

Run ID: 19e70479-7a37-415e-a775-008016992e55

📥 Commits

Reviewing files that changed from the base of the PR and between 1880e65 and 1a1c77c.

📒 Files selected for processing (2)
  • internal/agent/component/agent.go
  • internal/agent/component/agent_artifact_test.go

Comment on lines +164 to +166
opt, future := react.WithMessageFuture()
ctx = setArtifactCollector(ctx, future)
msg, err := agent.Generate(ctx, input, opt)

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Propagate the future through a context visible to Invoke.

Line 165 stores the future in a child context local to runEinoReActAgent; the caller’s ctx at Line 540 is unchanged, so getArtifactCollector(ctx) returns nil and production artifact collection is skipped.

Possible fix direction
+type artifactCollector struct {
+	future react.MessageFuture
+}
+
+func withArtifactCollector(ctx context.Context) context.Context {
+	return context.WithValue(ctx, artifactCollectorKey{}, &artifactCollector{})
+}
+
 func runEinoReActAgent(ctx context.Context, p AgentParam) (*schema.Message, error) {
 	...
 	opt, future := react.WithMessageFuture()
-	ctx = setArtifactCollector(ctx, future)
+	setArtifactCollector(ctx, future)
 	msg, err := agent.Generate(ctx, input, opt)
 	...
 }

Then initialize the holder in Invoke before agentRunner(ctx, p) and have getArtifactCollector read holder.future.

Also applies to: 540-540

🤖 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 164 - 166, The future is only
stored in the local child context inside runEinoReActAgent, so Invoke still sees
a ctx without an artifact collector and collection is skipped. Move the future
holder setup into Invoke before calling agentRunner(ctx, p), and update
getArtifactCollector to read the future from that shared holder instead of
relying on the local context copy. Keep the existing react.WithMessageFuture
flow, but ensure the future is visible to both Invoke and runEinoReActAgent
through the shared context path.

Comment on lines +742 to +746
func extractArtifactsFromToolMessage(msg *schema.Message) []artifactEntry {
payload := msg.Content
if payload == "" && len(msg.UserInputMultiContent) > 0 {
payload = toolMessageTextContent(msg)
}

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Try all text payload sources, not only the first non-empty one.

If msg.Content contains non-artifact text while _ARTIFACTS is in UserInputMultiContent, this returns no artifacts. Parse Content plus every text part until an envelope is found.

Suggested adjustment
 func extractArtifactsFromToolMessage(msg *schema.Message) []artifactEntry {
-	payload := msg.Content
-	if payload == "" && len(msg.UserInputMultiContent) > 0 {
-		payload = toolMessageTextContent(msg)
-	}
-	if payload == "" {
-		return nil
-	}
-
-	var envelope map[string]any
-	if err := json.Unmarshal([]byte(payload), &envelope); err != nil {
-		return nil
-	}
+	for _, payload := range toolMessageTextPayloads(msg) {
+		var envelope map[string]any
+		if err := json.Unmarshal([]byte(payload), &envelope); err != nil {
+			continue
+		}
 
-	raw, ok := envelope["_ARTIFACTS"].([]any)
-	if !ok {
-		return nil
-	}
+		raw, ok := envelope["_ARTIFACTS"].([]any)
+		if !ok {
+			continue
+		}
 
-	out := make([]artifactEntry, 0, len(raw))
-	for _, item := range raw {
-		m, ok := item.(map[string]any)
-		if !ok {
-			continue
-		}
-		name, _ := m["name"].(string)
-		url, _ := m["url"].(string)
-		if name == "" || url == "" {
-			continue
+		out := make([]artifactEntry, 0, len(raw))
+		for _, item := range raw {
+			m, ok := item.(map[string]any)
+			if !ok {
+				continue
+			}
+			name, _ := m["name"].(string)
+			url, _ := m["url"].(string)
+			if name == "" || url == "" {
+				continue
+			}
+			out = append(out, artifactEntry{Name: name, URL: url})
 		}
-		out = append(out, artifactEntry{Name: name, URL: url})
+		return out
 	}
-	return out
+	return nil
 }
 
-func toolMessageTextContent(msg *schema.Message) string {
+func toolMessageTextPayloads(msg *schema.Message) []string {
+	var payloads []string
+	if msg.Content != "" {
+		payloads = append(payloads, msg.Content)
+	}
 	for i := range msg.UserInputMultiContent {
 		part := &msg.UserInputMultiContent[i]
 		if part.Type == schema.ChatMessagePartTypeText && part.Text != "" {
-			return part.Text
+			payloads = append(payloads, part.Text)
 		}
 	}
-	return ""
+	return payloads
 }

Also applies to: 779-785

🤖 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 742 - 746,
extractArtifactsFromToolMessage currently stops after the first non-empty text
source, so it can miss artifacts when msg.Content has text and _ARTIFACTS
appears later in UserInputMultiContent. Update this logic to inspect all
available text payloads in order—starting with Content, then each text part from
UserInputMultiContent, using toolMessageTextContent or equivalent—until an
artifact envelope is found. Apply the same multi-source scan behavior in the
related artifact parsing path around the referenced extraction helpers so both
locations detect artifacts consistently.

@yuzhichang
yuzhichang merged commit 8b065d3 into infiniflow:main Jul 5, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants