Skip to content

fix(go-agent): preserve canvas system state across turns - #17010

Merged
yuzhichang merged 12 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:fix/agent-sys-files
Jul 17, 2026
Merged

yuzhichang merged 12 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:fix/agent-sys-files

Conversation

@Harry-Hz-Zhang

@Harry-Hz-Zhang Harry-Hz-Zhang commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Preserve request-scoped system variables such as files and user IDs during Canvas execution.
  • Persist conversation history, turn counts, and tool memory in the session DSL across turns.
  • Parse agent uploads into sys.files and align system variable rendering with Python.

Testing

  • bash build.sh --test ./internal/agent/...
  • bash build.sh --test ./internal/service/...
image

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

coderabbitai Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3ff9c91d-b8de-454d-9978-d4b8e4e011fa

📥 Commits

Reviewing files that changed from the base of the PR and between 2228bad and 7675b5a.

📒 Files selected for processing (1)
  • internal/service/agent_run_e2e_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/service/agent_run_e2e_test.go

📝 Walkthrough

Walkthrough

Changes

Agent and agentbot requests now accept structured file descriptors and pass them into RunAgent. Uploads are resolved from storage and stored in CanvasState.Sys["files"]. Runtime history, memory, session persistence, LLM history windows, and message rendering were updated with unit and end-to-end coverage.

Agent runtime state and file handling

Layer / File(s) Summary
Request contracts and upload resolution
internal/handler/agent.go, internal/service/bot.go, internal/service/file.go, internal/handler/*_test.go, internal/service/file_test.go
Handlers and services accept structured file descriptors, forward them to RunAgent, and resolve uploads from storage with ownership and format validation.
Canvas history, memory, and DSL state
internal/agent/runtime/state.go, internal/agent/canvas/{canvas.go,decode.go,scheduler.go}, internal/agent/runtime/*_test.go, internal/agent/canvas/*_test.go
Canvas state and DSL representations support conversation history, tool memory, sys-history, defensive snapshots, encoding, decoding, and synchronization.
Run execution and session persistence
internal/service/agent.go, internal/service/agent_run_e2e_test.go, internal/service/agent_test.go, internal/service/document_test.go
Agent runs initialize runtime state, parse files into sys.files, manage sessions, persist history and DSL values, and cover resume, interruption, authorization, file errors, and no-file execution.
Component state consumption and rendering
internal/agent/component/*, internal/agent/runtime/template.go
LLM and agent components use prior history and separate memory, collect files from state.Sys["files"], always expose downloads, and render non-string template values as JSON.

Estimated code review effort: 5 (Critical) | ~90 minutes

Possibly related PRs

Suggested labels: 💞 feature, 🧪 test, go, agent

Suggested reviewers: yuzhichang

Poem

A bunny sends files through canvas bright,
History hops in, memory stays light.
Text and images join the flow,
Sessions remember what they know.
JSON carrots render neat—
Tests tap their tiny feet.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 46.15% 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 summarizes the main change: preserving canvas system state across turns.
Description check ✅ Passed The description includes the required Summary section and relevant testing context, so it is mostly complete.
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: 1

🧹 Nitpick comments (1)
internal/service/agent_run_e2e_test.go (1)

172-172: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consolidate the no-files coverage into one meaningful test.

The existing test contains an unobserved stale value, while the new test duplicates the nil-files success path.

  • internal/service/agent_run_e2e_test.go#L172-L172: consume sys.files and assert the stale global value is ignored.
  • internal/service/agent_run_e2e_test.go#L1636-L1711: delete the duplicate compatibility-only test.

As per coding guidelines, remove stale and duplicate tests and compatibility-only surfaces.

🤖 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/service/agent_run_e2e_test.go` at line 172, Update the existing
no-files test in internal/service/agent_run_e2e_test.go:172-172 to consume
sys.files and assert that the stale global value is ignored. Delete the
duplicate compatibility-only test at
internal/service/agent_run_e2e_test.go:1636-1711, leaving one meaningful
no-files coverage path.

Source: Coding guidelines

🤖 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/service/file.go`:
- Around line 1182-1188: Update the file-processing flow around ParseWithResult
to handle audio uploads before constructing sys.files: either reject audio
inputs explicitly or invoke the transcription result path so content is
populated before the existing text handling. Ensure audio files never proceed
with an empty res.Text value.

---

Nitpick comments:
In `@internal/service/agent_run_e2e_test.go`:
- Line 172: Update the existing no-files test in
internal/service/agent_run_e2e_test.go:172-172 to consume sys.files and assert
that the stale global value is ignored. Delete the duplicate compatibility-only
test at internal/service/agent_run_e2e_test.go:1636-1711, leaving one meaningful
no-files coverage path.
🪄 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: 577862b7-bb5b-49ae-b563-b2d04f7580f4

📥 Commits

Reviewing files that changed from the base of the PR and between 101155b and 85ecdc7.

📒 Files selected for processing (12)
  • internal/agent/component/llm.go
  • internal/agent/component/vision_test.go
  • internal/handler/agent.go
  • internal/handler/agent_test.go
  • internal/handler/agent_wait_for_user_test.go
  • internal/handler/bot_test.go
  • internal/service/agent.go
  • internal/service/agent_run_e2e_test.go
  • internal/service/agent_test.go
  • internal/service/bot.go
  • internal/service/file.go
  • internal/service/file_test.go

Comment thread internal/service/file.go Resolved
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 17, 2026
@Harry-Hz-Zhang Harry-Hz-Zhang changed the title fix(go-agent): fix sys.files fix(go-agent): preserve canvas system state across turns Jul 17, 2026

@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: 4

Caution

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

⚠️ Outside diff range comments (4)
internal/service/agent.go (2)

1359-1388: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Make the session read-modify-write atomic.

Two concurrent turns can load the same Message/DSL, append independently, and then overwrite each other through whole-row Save; the last update silently loses a conversation turn. Use a transaction with row locking or optimistic versioning around the load and update.

🤖 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/service/agent.go` around lines 1359 - 1388, Make the session
read-modify-write flow in the agent run update block atomic by wrapping the
GetBySessionID, message/reference/DSL mutations, and Update operation in a
transaction with row-level locking or optimistic version validation. Ensure
concurrent turns cannot overwrite each other’s appended session data, and
preserve the existing user/session validation and warning behavior.

709-816: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Create a session when the supplied ID does not exist.

newSession only tracks whether the input ID was empty. A caller-provided, previously unseen session ID therefore runs normally but is never created, and all later history persistence becomes a no-op.

Base creation on the lookup result (session == nil), not on whether the server generated the ID, and cover an explicit-new-ID second-turn test.

🤖 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/service/agent.go` around lines 709 - 816, Update the session
creation condition in the RunAgent flow to create a session whenever the lookup
result is nil, including caller-supplied IDs that do not yet exist. Use the
existing session variable from api4ConversationDAO.GetBySessionID rather than
newSession, preserve the existing ownership and DSL handling, and add a
second-turn test covering an explicit previously unseen session ID.
internal/agent/component/llm.go (1)

809-829: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Read sys.files through GetVar instead of state.Sys["files"]. Direct map access bypasses CanvasState’s lock and can race with concurrent state updates. Normalize the GetVar("sys.files") result here.

🤖 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/llm.go` around lines 809 - 829, Update
collectSysFiles to obtain sys.files via the CanvasState GetVar method using the
"sys.files" path, rather than directly reading state.Sys["files"]. Normalize the
returned value into the existing []string handling before processing text parts
and image URIs, while preserving the current behavior for missing or unsupported
values.
internal/agent/canvas/scheduler.go (1)

154-191: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Keep request-scoped namespaces authoritative
statePre copies state.Sys/Env/Globals into ctxState before any merge, so a resumed checkpoint can clobber request values like sys.files or sys.user_id (internal/agent/canvas/scheduler.go:165-174). Merge checkpoint-only keys into the request state first, then mirror the merged namespaces back to state.

🤖 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/canvas/scheduler.go` around lines 154 - 191, Update the
namespace merge logic in the scheduler block using SnapshotNamespaces so
request-scoped ctxState.Sys, ctxState.Env, and ctxState.Globals remain
authoritative. Merge only checkpoint keys absent from the request state into
ctxState first, then mirror the resulting merged namespaces back to state; do
not copy state namespaces into ctxState before this merge.
🧹 Nitpick comments (1)
internal/agent/runtime/state.go (1)

332-333: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove compatibility-oriented wording from the new runtime documentation.

Describe each behavior through the current Go runtime contract rather than its Python predecessor.

  • internal/agent/runtime/state.go#L332-L333: describe payload preservation and LLM-facing content directly.
  • internal/agent/runtime/state.go#L376-L378: explain exclusion of the in-flight turn without migration history.
  • internal/agent/component/message.go#L227-L229: document the always-present downloads output contract directly.
  • internal/agent/runtime/template.go#L140-L143: retain the serialization example but remove the Python reference.

As per coding guidelines, “do not add compatibility wording to comments or documentation.”

🤖 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/runtime/state.go` around lines 332 - 333, Remove
compatibility-oriented wording from the documentation comments at
internal/agent/runtime/state.go:332-333,
internal/agent/runtime/state.go:376-378,
internal/agent/component/message.go:227-229, and
internal/agent/runtime/template.go:140-143. Describe payload/content behavior,
in-flight turn exclusion, and the always-present downloads contract directly in
current Go runtime terms; retain the serialization example in template.go while
removing its Python reference.

Source: Coding guidelines

🤖 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/canvas/decode.go`:
- Around line 127-150: Update the map[string]any branch in decodeMemory to
validate that the user, assistant, and summary keys are all present before
appending a memory record; skip empty or partially populated maps like malformed
list entries. Add a test covering malformed map-shaped memory and confirming no
nil-valued record is produced.

In `@internal/agent/runtime/state.go`:
- Around line 528-555: Update cloneJSONValue to deep-copy arbitrary map and
slice types, not only map[string]any, []any, and []string; recursively clone
nested elements while preserving nil containers and converting typed composites
such as []map[string]any, map[string]string, and []DownloadInfo into independent
canonical JSON-compatible values. Add focused tests covering typed maps, nested
typed slices, nil containers, and mutation of cloned snapshots.
- Around line 207-208: Update the state checkpoint serialization around
activeHistoryIndex so restoring a checkpoint preserves the in-flight history
marker instead of resetting it to -1; use a nullable marker or equivalent turn
identity and ensure SnapshotPriorHistory does not duplicate the current prompt
after restore. Add a marshal/unmarshal regression test covering a checkpoint
taken after AppendCurrentUser.

In `@internal/service/agent.go`:
- Around line 1386-1388: Update persistAgentRunSession to return the error from
api4ConversationDAO.Update instead of only warning and continuing. At its
caller, handle the returned error before emitting the successful agent-run
result, ensuring failed session persistence propagates and prevents success from
being reported.

---

Outside diff comments:
In `@internal/agent/canvas/scheduler.go`:
- Around line 154-191: Update the namespace merge logic in the scheduler block
using SnapshotNamespaces so request-scoped ctxState.Sys, ctxState.Env, and
ctxState.Globals remain authoritative. Merge only checkpoint keys absent from
the request state into ctxState first, then mirror the resulting merged
namespaces back to state; do not copy state namespaces into ctxState before this
merge.

In `@internal/agent/component/llm.go`:
- Around line 809-829: Update collectSysFiles to obtain sys.files via the
CanvasState GetVar method using the "sys.files" path, rather than directly
reading state.Sys["files"]. Normalize the returned value into the existing
[]string handling before processing text parts and image URIs, while preserving
the current behavior for missing or unsupported values.

In `@internal/service/agent.go`:
- Around line 1359-1388: Make the session read-modify-write flow in the agent
run update block atomic by wrapping the GetBySessionID, message/reference/DSL
mutations, and Update operation in a transaction with row-level locking or
optimistic version validation. Ensure concurrent turns cannot overwrite each
other’s appended session data, and preserve the existing user/session validation
and warning behavior.
- Around line 709-816: Update the session creation condition in the RunAgent
flow to create a session whenever the lookup result is nil, including
caller-supplied IDs that do not yet exist. Use the existing session variable
from api4ConversationDAO.GetBySessionID rather than newSession, preserve the
existing ownership and DSL handling, and add a second-turn test covering an
explicit previously unseen session ID.

---

Nitpick comments:
In `@internal/agent/runtime/state.go`:
- Around line 332-333: Remove compatibility-oriented wording from the
documentation comments at internal/agent/runtime/state.go:332-333,
internal/agent/runtime/state.go:376-378,
internal/agent/component/message.go:227-229, and
internal/agent/runtime/template.go:140-143. Describe payload/content behavior,
in-flight turn exclusion, and the always-present downloads contract directly in
current Go runtime terms; retain the serialization example in template.go while
removing its Python reference.
🪄 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: 9dc83a4b-ee42-4660-a798-67fc3399354c

📥 Commits

Reviewing files that changed from the base of the PR and between 85ecdc7 and c976787.

📒 Files selected for processing (18)
  • internal/agent/canvas/canvas.go
  • internal/agent/canvas/canvas_test.go
  • internal/agent/canvas/decode.go
  • internal/agent/canvas/decode_history_test.go
  • internal/agent/canvas/scheduler.go
  • internal/agent/component/agent.go
  • internal/agent/component/history_window_test.go
  • internal/agent/component/llm.go
  • internal/agent/component/message.go
  • internal/agent/component/message_test.go
  • internal/agent/component/tool_call_memory_test.go
  • internal/agent/runtime/state.go
  • internal/agent/runtime/state_test.go
  • internal/agent/runtime/template.go
  • internal/service/agent.go
  • internal/service/agent_run_e2e_test.go
  • internal/service/agent_test.go
  • internal/service/document_test.go

Comment thread internal/agent/canvas/decode.go Resolved
Comment thread internal/agent/runtime/state.go Resolved
Comment thread internal/agent/runtime/state.go Resolved
Comment thread internal/service/agent.go Resolved

@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: 1

🤖 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/message.go`:
- Around line 183-185: Remove migration and compatibility wording from comments
in internal/agent/component/message.go at lines 183-185, 220-222, and 376-378:
update the comment near Message rendering to omit the Python behavior reference,
rephrase “Python’s Message output schema” as “The Message output schema,” and
remove the Python agent_api.py comparison and done-marker explanation, without
changing runtime behavior.
🪄 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: 392682a9-0a5f-46d7-90e6-16385cafe061

📥 Commits

Reviewing files that changed from the base of the PR and between c976787 and 3467cfc.

📒 Files selected for processing (9)
  • internal/agent/component/agent.go
  • internal/agent/component/llm.go
  • internal/agent/component/message.go
  • internal/agent/component/message_test.go
  • internal/handler/agent.go
  • internal/handler/agent_test.go
  • internal/service/agent.go
  • internal/service/agent_run_e2e_test.go
  • internal/service/agent_test.go
🚧 Files skipped from review as they are similar to previous changes (8)
  • internal/agent/component/message_test.go
  • internal/agent/component/agent.go
  • internal/handler/agent_test.go
  • internal/handler/agent.go
  • internal/agent/component/llm.go
  • internal/service/agent_test.go
  • internal/service/agent_run_e2e_test.go
  • internal/service/agent.go

Comment thread internal/agent/component/message.go Resolved
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jul 17, 2026
@Harry-Hz-Zhang Harry-Hz-Zhang added ci Continue Integration and removed ci Continue Integration labels Jul 17, 2026
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as draft July 17, 2026 04:22
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as ready for review July 17, 2026 04:22
@Harry-Hz-Zhang Harry-Hz-Zhang added ci Continue Integration and removed ci Continue Integration labels Jul 17, 2026
@yuzhichang

Copy link
Copy Markdown
Member

LGTM

@yuzhichang
yuzhichang merged commit 1b77e3e into infiniflow:main Jul 17, 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:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants