Skip to content

fix(agent): save draft version on agent update - #16691

Merged
wangq8 merged 4 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:fix/agent-keep
Jul 7, 2026
Merged

wangq8 merged 4 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:fix/agent-keep

Conversation

@Harry-Hz-Zhang

Copy link
Copy Markdown
Contributor

What

  • Save or replace the latest draft user_canvas_version when UpdateAgent receives updated DSL.
  • Preserve released versions by creating a new draft when the latest matching version is already released.
  • Keep version cleanup limited to old unpublished drafts.
  • Move version persistence details into the DAO layer.

Testing

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

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

coderabbitai Bot commented Jul 7, 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

Run ID: 5602383e-38aa-4d45-a9a3-7395ab79f16f

📥 Commits

Reviewing files that changed from the base of the PR and between 8c8f35e and 3640213.

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

📝 Walkthrough

Walkthrough

Adds nickname lookup, transactional canvas version save/replace and cleanup logic, wires UpdateAgent to persist DSL-backed versions, and expands tests for draft replacement and released-version preservation.

Changes

Canvas Version Save/Replace

Layer / File(s) Summary
User nickname lookup DAO method
internal/dao/user.go
Adds context import and GetNicknameByID(ctx, id) returning a user's nickname scanned from entity.User.
UserCanvasVersion save/replace and cleanup logic
internal/entity/canvas.go, internal/dao/user_canvas_version.go, internal/dao/user_canvas_version_test.go
Adds the release field, save-or-replace options, transactional upsert logic, DAO interface updates, and unpublished-version cleanup.
AgentService wiring and UpdateAgent versioning
internal/service/agent.go
Adds userDAO field/init, updates UpdateAgent to capture the loaded canvas and call version helpers when dsl is present, and adjusts ResetAgent comment.
Setup and versioning tests
internal/service/agent_test.go
Extends test setup with single-connection SQLite, extra migrations, and adds tests for draft replacement and released-version preservation.

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

Possibly related PRs

  • infiniflow/ragflow#16495: Both PRs modify UpdateAgent in internal/service/agent.go to handle partial patch updates including conditional dsl handling.

Suggested labels: 🧪 test

Suggested reviewers: yuzhichang, yingfeng

Poem

A hop, a save, a version bloom,
Drafts stay neat and make some room,
Released ones rest, the rest may shift,
The bunny leaves a tiny gift. 🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: saving draft agent versions on update.
Description check ✅ Passed The PR description covers the goal and testing, but it does not follow the requested Summary template section or add much background context.
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: 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/dao/user_canvas_version.go`:
- Around line 151-160: The SaveOrReplaceLatest flow in the UserCanvasVersion
transaction still has a read-then-write race because the latest lookup can be
observed concurrently by multiple writers. Fix this by serializing the
latest-row read in the SaveOrReplaceLatest path, preferably by adding a locking
read on the tx.Where(...).Order(...).First(&latest) lookup in
user_canvas_version.go, or by enforcing the same invariant at the database level
so concurrent requests for the same UserCanvasID cannot both insert a new draft.
Keep the logic around sameDSL/latest unchanged, but ensure the “latest” fetch
cannot race with another transaction.
🪄 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: 47ed5632-ab84-4078-9043-b9457047b223

📥 Commits

Reviewing files that changed from the base of the PR and between 3660b98 and a2763cf.

📒 Files selected for processing (5)
  • internal/dao/user.go
  • internal/dao/user_canvas_version.go
  • internal/dao/user_canvas_version_test.go
  • internal/service/agent.go
  • internal/service/agent_test.go

Comment thread internal/dao/user_canvas_version.go Resolved
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as draft July 7, 2026 06:15
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as ready for review July 7, 2026 06:16
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as draft July 7, 2026 06:19
@Harry-Hz-Zhang
Harry-Hz-Zhang marked this pull request as ready for review July 7, 2026 06:19

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review Summary

This PR adds version-saving on agent updates — when UpdateAgent receives a DSL, it now saves/replaces a draft version row, preserving released snapshots and cleaning up old unpublished drafts. The approach is sound and the tests cover the key scenarios. A few things to address:


🔴 Missing Release field on UserCanvasVersion entity

The internal/entity/canvas.go entity UserCanvasVersion (line 59) does not define a Release field, yet the DAO code writes to release as a column in user_canvas_version:

  • SaveOrReplaceLatest calls Update("release", opts.Release)
  • getReleaseByIDTx selects the backtick-quoted release column
  • deleteAllUnpublishedExcessTx filters by the backtick-quoted release column

Without the entity field, GORM AutoMigrate will not create this column, and the test has to work around it with a raw ALTER TABLE. Either:

  • Add a Release bool field (with gorm tag column:release;not null;default:false;index) to UserCanvasVersion, or
  • If the column already exists via a separate migration, document it clearly.

🟡 Redundant DSL normalization

In UpdateAgent, the DSL is already normalized before being stored in updates["dsl"]:

updates["dsl"] = entity.JSONMap(dslpkg.NormalizeForCanvas(entity.JSONMap(dslMap)))

Then saveOrReplaceVersion normalizes it again:

normalizedDSL := entity.JSONMap(dslpkg.NormalizeForCanvas(dsl))

And then again in the SameDSL callback on line ~625. The result is 3x normalization of the input DSL + 1x for the latest. While NormalizeForCanvas is presumably idempotent, this is unnecessary work on every UpdateAgent call. Consider normalizing once and passing the result through.


🟡 Minor: release column is a SQL reserved word

The backtick quoting is applied in getReleaseByIDTx and deleteAllUnpublishedExcessTx, but Update("release", opts.Release) relies on GORM's internal quoting. On most MySQL configs this works fine, but adding the entity field (which addresses the red issue above) allows GORM to handle quoting uniformly.


✅ What looks good

  • Transaction safety: The parent canvas row is locked (SELECT ... FOR UPDATE) before any version logic, preventing races.
  • Cleanup inside the transaction: deleteAllUnpublishedExcessTx runs in the same txn, so partial failures don't leave garbage.
  • Tests cover both paths: draft replacement (same DSL -> update in place) and released-version preservation (latest is released -> new draft row created).
  • Type assertion guard: The dsl type assertion at ~line 473 returns a proper error instead of panicking.
  • Good SetMaxOpenConns(1) in test: Avoids SQLite database is locked errors during the transaction.
  • No regression on existing behavior: The version saving is gated on updates["dsl"] being present, so settings-only patches skip it.

Summary

Severity Count Items
🔴 Must fix 1 Missing Release field on UserCanvasVersion entity
🟡 Should fix 2 Redundant normalization, inconsistent reserved-word quoting

The logic and test quality are solid. Once the entity definition is updated, this LGTM.

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

Caution

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

⚠️ Outside diff range comments (1)
internal/dao/user_canvas_version.go (1)

165-181: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Update title when replacing an existing version.

The create path stores opts.Title, but the replacement path only refreshes DSL/release/description. Same-DSL draft updates can leave stale version titles after nickname/title changes.

Proposed fix
 				updates := map[string]interface{}{
 					"dsl":     opts.DSL,
 					"release": opts.Release,
 				}
+				if opts.Title != nil {
+					updates["title"] = opts.Title
+				}
 				if opts.Description != nil {
 					updates["description"] = opts.Description
 				}
@@
 				latest.DSL = opts.DSL
 				latest.Release = opts.Release
+				if opts.Title != nil {
+					latest.Title = opts.Title
+				}
 				if opts.Description != nil {
 					latest.Description = opts.Description
 				}
🤖 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/dao/user_canvas_version.go` around lines 165 - 181, The replacement
update path in user canvas version handling is not refreshing the version title,
so it can remain stale when an existing draft is replaced. In the logic that
builds the updates map and applies it through
tx.Model(&entity.UserCanvasVersion{}).Updates, include opts.Title alongside DSL,
release, and description, and also mirror that change onto the
latest.UserCanvasVersion object so the in-memory record stays consistent.
🤖 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.

Outside diff comments:
In `@internal/dao/user_canvas_version.go`:
- Around line 165-181: The replacement update path in user canvas version
handling is not refreshing the version title, so it can remain stale when an
existing draft is replaced. In the logic that builds the updates map and applies
it through tx.Model(&entity.UserCanvasVersion{}).Updates, include opts.Title
alongside DSL, release, and description, and also mirror that change onto the
latest.UserCanvasVersion object so the in-memory record stays consistent.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c5bf9af6-aea8-41c8-8980-9d74da9d8ca7

📥 Commits

Reviewing files that changed from the base of the PR and between e53cb01 and 8c8f35e.

📒 Files selected for processing (4)
  • internal/dao/user_canvas_version.go
  • internal/entity/canvas.go
  • internal/service/agent.go
  • internal/service/agent_test.go
💤 Files with no reviewable changes (1)
  • internal/service/agent_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/service/agent.go

@Harry-Hz-Zhang

Harry-Hz-Zhang commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor Author

Review Summary

This PR adds version-saving on agent updates — when UpdateAgent receives a DSL, it now saves/replaces a draft version row, preserving released snapshots and cleaning up old unpublished drafts. The approach is sound and the tests cover the key scenarios. A few things to address:

🔴 Missing Release field on UserCanvasVersion entity

The internal/entity/canvas.go entity UserCanvasVersion (line 59) does not define a Release field, yet the DAO code writes to release as a column in user_canvas_version:

  • SaveOrReplaceLatest calls Update("release", opts.Release)
  • getReleaseByIDTx selects the backtick-quoted release column
  • deleteAllUnpublishedExcessTx filters by the backtick-quoted release column

Without the entity field, GORM AutoMigrate will not create this column, and the test has to work around it with a raw ALTER TABLE. Either:

  • Add a Release bool field (with gorm tag column:release;not null;default:false;index) to UserCanvasVersion, or
  • If the column already exists via a separate migration, document it clearly.

🟡 Redundant DSL normalization

In UpdateAgent, the DSL is already normalized before being stored in updates["dsl"]:

updates["dsl"] = entity.JSONMap(dslpkg.NormalizeForCanvas(entity.JSONMap(dslMap)))

Then saveOrReplaceVersion normalizes it again:

normalizedDSL := entity.JSONMap(dslpkg.NormalizeForCanvas(dsl))

And then again in the SameDSL callback on line ~625. The result is 3x normalization of the input DSL + 1x for the latest. While NormalizeForCanvas is presumably idempotent, this is unnecessary work on every UpdateAgent call. Consider normalizing once and passing the result through.

🟡 Minor: release column is a SQL reserved word

The backtick quoting is applied in getReleaseByIDTx and deleteAllUnpublishedExcessTx, but Update("release", opts.Release) relies on GORM's internal quoting. On most MySQL configs this works fine, but adding the entity field (which addresses the red issue above) allows GORM to handle quoting uniformly.

✅ What looks good

  • Transaction safety: The parent canvas row is locked (SELECT ... FOR UPDATE) before any version logic, preventing races.
  • Cleanup inside the transaction: deleteAllUnpublishedExcessTx runs in the same txn, so partial failures don't leave garbage.
  • Tests cover both paths: draft replacement (same DSL -> update in place) and released-version preservation (latest is released -> new draft row created).
  • Type assertion guard: The dsl type assertion at ~line 473 returns a proper error instead of panicking.
  • Good SetMaxOpenConns(1) in test: Avoids SQLite database is locked errors during the transaction.
  • No regression on existing behavior: The version saving is gated on updates["dsl"] being present, so settings-only patches skip it.

Summary

Severity Count Items
🔴 Must fix 1 Missing Release field on UserCanvasVersion entity
🟡 Should fix 2 Redundant normalization, inconsistent reserved-word quoting
The logic and test quality are solid. Once the entity definition is updated, this LGTM.

@wangq8 Fixed, could u review my code again? ?

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-review: fix(agent): save draft version on agent update (#16691)

Good PR overall — the logic is sound, test quality is solid, and the two prior review findings that mattered most (entity Release field + redundant normalization) have already been addressed in commit 8c8f35e. A couple things still need attention.


🔴 Stale version title in replacement path (still open)

In SaveOrReplaceLatest, when the same-DSL replacement path is taken:

updates := map[string]interface{}{
    "dsl":     opts.DSL,
    "release": opts.Release,
}

title is not included. The caller builds a fresh buildVersionTitle(nickname, title, time.Now()) every time and passes it as opts.Title, but this fresh title is silently ignored during an in-place update. The consequence: the version title timestamp stays frozen at the first save time, even if the user clicks "save" again hours later.

Fix: add title to the updates map (mirroring the existing description handling), and update the in-memory latest.Title accordingly.


🟡 Backtick quoting in deleteAllUnpublishedExcessTx

.Where("user_canvas_id = ? AND (release = ? OR release IS NULL)", canvasID, false)

With the Release bool entity field now properly defined (gorm tag: not null;default:false), the raw backtick quoting is fragile — it works in MySQL but is non-portable, and since Release is NOT NULL DEFAULT false, the IS NULL clause is dead code. This can be simplified to:

.Where("user_canvas_id = ? AND release = ?", canvasID, false)

GORM will handle dialect-appropriate quoting automatically.


🟡 Missing user seed in TestUpdateAgentDSLDoesNotOverwriteLatestReleasedVersion

The test creates a UserCanvas with UserID: "user-1" but does not seed a corresponding User row. saveOrReplaceVersion calls GetNicknameByID("user-1") — gets a not-found error — falls back to "user-1" as the nickname. The resulting version title becomes user-1_Released Agent_... instead of a proper nickname. Minor, and the test still validates the correct behavior, but inconsistent with TestUpdateAgentDSLCreatesAndReplacesDraftVersion which does seed a user.


✅ What still looks good

  • Transaction safety: Parent canvas row locked with FOR UPDATE, all version/cleanup ops inside one transaction.
  • Race mitigation: The FOR UPDATE lock on the canvas row serializes per-canvas access, making the version read-then-write safe in practice.
  • Cleanup in same txn: Partial failures roll back version rows too.
  • Settings-only patches skip versioning: Gated on updates["dsl"] — correct.
  • Tests cover both paths: Draft replacement + released-preservation.
  • Type assertion guard: Proper error return instead of panic.
  • Default 20 unpublished versions: Sensible cap.

Summary

Severity Count Items
🔴 Fix 1 Stale version title on replacement
🟡 Improve 2 Backtick quoting, missing user seed in 2nd test

Once the title-update fix lands, LGTM.

@Harry-Hz-Zhang

Copy link
Copy Markdown
Contributor Author

Re-review: fix(agent): save draft version on agent update (#16691)

Good PR overall — the logic is sound, test quality is solid, and the two prior review findings that mattered most (entity Release field + redundant normalization) have already been addressed in commit 8c8f35e. A couple things still need attention.

🔴 Stale version title in replacement path (still open)

In SaveOrReplaceLatest, when the same-DSL replacement path is taken:

updates := map[string]interface{}{
    "dsl":     opts.DSL,
    "release": opts.Release,
}

title is not included. The caller builds a fresh buildVersionTitle(nickname, title, time.Now()) every time and passes it as opts.Title, but this fresh title is silently ignored during an in-place update. The consequence: the version title timestamp stays frozen at the first save time, even if the user clicks "save" again hours later.

Fix: add title to the updates map (mirroring the existing description handling), and update the in-memory latest.Title accordingly.

🟡 Backtick quoting in deleteAllUnpublishedExcessTx

.Where("user_canvas_id = ? AND (release = ? OR release IS NULL)", canvasID, false)

With the Release bool entity field now properly defined (gorm tag: not null;default:false), the raw backtick quoting is fragile — it works in MySQL but is non-portable, and since Release is NOT NULL DEFAULT false, the IS NULL clause is dead code. This can be simplified to:

.Where("user_canvas_id = ? AND release = ?", canvasID, false)

GORM will handle dialect-appropriate quoting automatically.

🟡 Missing user seed in TestUpdateAgentDSLDoesNotOverwriteLatestReleasedVersion

The test creates a UserCanvas with UserID: "user-1" but does not seed a corresponding User row. saveOrReplaceVersion calls GetNicknameByID("user-1") — gets a not-found error — falls back to "user-1" as the nickname. The resulting version title becomes user-1_Released Agent_... instead of a proper nickname. Minor, and the test still validates the correct behavior, but inconsistent with TestUpdateAgentDSLCreatesAndReplacesDraftVersion which does seed a user.

✅ What still looks good

  • Transaction safety: Parent canvas row locked with FOR UPDATE, all version/cleanup ops inside one transaction.
  • Race mitigation: The FOR UPDATE lock on the canvas row serializes per-canvas access, making the version read-then-write safe in practice.
  • Cleanup in same txn: Partial failures roll back version rows too.
  • Settings-only patches skip versioning: Gated on updates["dsl"] — correct.
  • Tests cover both paths: Draft replacement + released-preservation.
  • Type assertion guard: Proper error return instead of panic.
  • Default 20 unpublished versions: Sensible cap.

Summary

Severity Count Items
🔴 Fix 1 Stale version title on replacement
🟡 Improve 2 Backtick quoting, missing user seed in 2nd test
Once the title-update fix lands, LGTM.

@wangq8, Fixed, could u review again plz ?

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review: fix(agent): save draft version on agent update (#16691)

Author: Hz-186 | Base: main | +332 / -14 | 6 files

What the PR Does

When UpdateAgent receives updated DSL, it now automatically saves/replaces a draft user_canvas_version row. If the latest matching version is already released, a new draft row is created to preserve the released snapshot. Old unpublished drafts exceeding the cap (20) are cleaned up.

Previous Reviews Status ✅

All issues from wangq8's two review rounds have been resolved in the current diff:

Issue Round Status
Missing Release field on entity R1 ✅ Added to UserCanvasVersion
Redundant DSL normalization R1 ✅ Normalized once in UpdateAgent
Backtick quoting on release R1 ✅ Replaced with GORM map syntax
Stale version title on replacement R2 ✅ title added to updates map
Missing user seed in 2nd test R2 ✅ User row seeded
Backtick quoting in cleanup query R2 ✅ Using map[string]interface{}

✅ What Looks Good

  • Transaction safety: Parent canvas row locked with FOR UPDATE, serializing per-canvas access
  • Atomic cleanup: deleteAllUnpublishedExcessTx runs in the same txn as save/replace
  • Comment accuracy: ResetAgent docstring updated to reflect new behavior
  • Settings-only patches unaffected: Version save gated on updates["dsl"] being present
  • Type safety: Proper error return instead of panic on type assertion
  • Test coverage: Two solid tests covering draft-in-place replacement and released-version preservation
  • CI all green: preflight, tests (infinity + ES), CodeRabbit all pass

🟡 Minor Suggestion (future consideration)

The canvas update (UpdateFields) and version save are two separate DB operations. If the version save fails after the canvas update succeeds, the canvas has new DSL but no version row. Wrapping both in a single transaction would be ideal but is scope creep for this PR.

Summary

Well-structured PR. All prior review feedback has been addressed, tests are meaningful, and CI is green. I have no blocking findings.

Verdict: LGTM 🟢

@wangq8
wangq8 merged commit 332d34c into infiniflow:main Jul 7, 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: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