Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

Agent: add apply version and delete by version APIs (#21352)

Wang Qie6ae78c8d3d8
diff --git a/docs/references/http_api_reference.md b/docs/references/http_api_reference.md
index be4f546f01..637971cb94 100644
--- a/docs/references/http_api_reference.md
+++ b/docs/references/http_api_reference.md
@@ -5431,6 +5431,108 @@ Failure:
+### Delete agent version
+
+**DELETE** `/api/v1/agents/{agent_id}/versions/{version_id}`
+
+Deletes one saved version belonging to the specified agent. The current agent
+and its other saved versions remain unchanged. This also allows deleting the
+last saved version.
+
+#### Request
+
+- Method: DELETE
+- URL: `/api/v1/agents/{agent_id}/versions/{version_id}`
+- Headers:
+ - `'Authorization: Bearer <YOUR_API_KEY>'`
+- Body: none.
+
+##### Request example
+
+```bash
+curl --request DELETE \
+ --url http://{address}/api/v1/agents/{agent_id}/versions/{version_id} \
+ --header 'Authorization: Bearer <YOUR_API_KEY>'
+```
+
+##### Path parameters
+
+- `agent_id`: `string`, required. The agent whose history contains the version.
+- `version_id`: `string`, required. The saved version to delete.
+
+#### Response
+
+Success:
+
+```json
+{
+ "code": 0,
+ "data": true,
+ "message": "success"
+}
+```
+
+The caller must have permission to edit the agent. A missing or inaccessible
+agent, a missing version, or a version belonging to a different agent returns
+business code `103` with the message `"Make sure you have permission to access the agent."`.
+
+---
+
+### Apply agent version
+
+**POST** `/api/v1/agents/{agent_id}/versions/{version_id}/apply`
+
+Restores the saved version's workflow DSL into the current agent as an unpublished
+draft. The agent's title, description, ownership, sharing, and other metadata are
+preserved. The source version and existing history are retained. The restored DSL
+passes the same validation and normalization as an ordinary agent update.
+
+Applying saves the restored workflow to version history using the normal save
+behavior: it creates a new draft version when the latest DSL differs or the
+latest version is published, and refreshes an identical latest draft. Publish
+the agent separately when the restored workflow is ready for release.
+
+#### Request
+
+- Method: POST
+- URL: `/api/v1/agents/{agent_id}/versions/{version_id}/apply`
+- Headers:
+ - `'Authorization: Bearer <YOUR_API_KEY>'`
+- Body: none.
+
+##### Request example
+
+```bash
+curl --request POST \
+ --url http://{address}/api/v1/agents/{agent_id}/versions/{version_id}/apply \
+ --header 'Authorization: Bearer <YOUR_API_KEY>'
+```
+
+##### Path parameters
+
+- `agent_id`: `string`, required. The agent to update.
+- `version_id`: `string`, required. A saved version belonging to that agent.
+
+#### Response
+
+Success:
+
+```json
+{
+ "code": 0,
+ "data": true,
+ "message": "success"
+}
+```
+
+The caller must have permission to edit the agent. A missing or inaccessible
+agent, a missing version, or a version belonging to a different agent returns
+business code `103` with the message `"Make sure you have permission to access the agent."`.
+A version without a DSL or a workflow that fails validation returns business
+code `102`; the current agent and its history remain unchanged.
+
+---
+
## MEMORY MANAGEMENT
### Create Memory
diff --git a/internal/handler/agent.go b/internal/handler/agent.go
index ddb04e9301..6073ad9a51 100644
--- a/internal/handler/agent.go
+++ b/internal/handler/agent.go
@@ -822,6 +822,30 @@ func (h *AgentHandler) DeleteVersion(c *gin.Context) {
common.SuccessWithData(c, true, "success")
}
+// ApplyVersion restores a saved workflow as the current agent draft.
+// @Summary Apply Agent Version
+// @Tags agents
+// @Produce json
+// @Param canvas_id path string true "canvas id"
+// @Param version_id path string true "version id"
+// @Success 200 {object} map[string]interface{}
+// @Router /api/v1/agents/{canvas_id}/versions/{version_id}/apply [post]
+func (h *AgentHandler) ApplyVersion(c *gin.Context) {
+ user, code, msg := GetUser(c)
+ if code != common.CodeSuccess {
+ common.ResponseWithCodeData(c, code, nil, msg)
+ return
+ }
+ canvasID := c.Param("canvas_id")
+ versionID := c.Param("version_id")
+ if err := h.agentService.ApplyVersion(c.Request.Context(), user.ID, canvasID, versionID); err != nil {
+ ec, em := mapAgentError(err)
+ common.ResponseWithCodeData(c, ec, nil, em)
+ return
+ }
+ common.SuccessWithData(c, true, "success")
+}
+
// --- PR2: missing routes wired up to the existing service layer ---
// ListAgentTemplates GET /api/v1/agents/templates
diff --git a/internal/handler/agent_version_test.go b/internal/handler/agent_version_test.go
new file mode 100644
index 0000000000..e7d80b4e1f
--- /dev/null
+++ b/internal/handler/agent_version_test.go
@@ -0,0 +1,171 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package handler
+
+import (
+ "encoding/json"
+ "net/http"
+ "reflect"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+
+ "ragflow/internal/common"
+ "ragflow/internal/dao"
+ "ragflow/internal/entity"
+ "ragflow/internal/service"
+)
+
+func TestAgentVersionActions(t *testing.T) {
+ for _, action := range []struct {
+ name string
+ method string
+ run func(*AgentHandler, *gin.Context)
+ }{
+ {"delete", http.MethodDelete, (*AgentHandler).DeleteVersion},
+ {"apply", http.MethodPost, (*AgentHandler).ApplyVersion},
+ } {
+ for _, scenario := range []string{"success", "last_version", "empty_dsl", "draft_version", "missing_agent", "missing_version", "foreign_agent", "foreign_version", "unauthenticated", "nil_dsl"} {
+ t.Run(action.name+"/"+scenario, func(t *testing.T) {
+ path := "/api/v1/agents/canvas-1/versions/version-1"
+ if action.name == "apply" {
+ path += "/apply"
+ }
+ c, w, db := setupGinContextWithUserAndDB(t, action.method, path)
+ c.Params = gin.Params{{Key: "canvas_id", Value: "canvas-1"}, {Key: "version_id", Value: "version-1"}}
+ if err := db.Create(&entity.User{ID: "user-1", Nickname: "owner", Email: "[email protected]"}).Error; err != nil {
+ t.Fatal(err)
+ }
+ current := entity.UserCanvas{
+ ID: "canvas-1", UserID: "user-1", Title: sptr("Current Agent"),
+ Description: sptr("Current description"), Tags: "keep", Release: true,
+ DSL: entity.JSONMap{"components": map[string]interface{}{}, "revision": "current"},
+ }
+ if scenario == "foreign_agent" {
+ current.UserID = "user-2"
+ }
+ if err := db.Create(&current).Error; err != nil {
+ t.Fatal(err)
+ }
+ createdAt := int64(1)
+ version := entity.UserCanvasVersion{
+ ID: "version-1", UserCanvasID: current.ID, Title: sptr("Historical version title"),
+ Release: true, DSL: entity.JSONMap{"components": map[string]interface{}{}, "revision": "old"},
+ BaseModel: entity.BaseModel{CreateTime: &createdAt},
+ }
+ wantCode := common.CodeSuccess
+ switch scenario {
+ case "empty_dsl":
+ version.DSL = entity.JSONMap{}
+ case "draft_version":
+ version.Release = false
+ case "missing_agent":
+ c.Params[0].Value = "missing"
+ wantCode = common.CodeOperatingError
+ case "missing_version":
+ c.Params[1].Value = "missing"
+ wantCode = common.CodeOperatingError
+ case "foreign_agent":
+ wantCode = common.CodeOperatingError
+ case "foreign_version":
+ version.UserCanvasID = "canvas-2"
+ wantCode = common.CodeOperatingError
+ case "unauthenticated":
+ delete(c.Keys, "user")
+ wantCode = common.CodeUnauthorized
+ case "nil_dsl":
+ version.DSL = nil
+ if action.name == "apply" {
+ wantCode = common.CodeDataError
+ }
+ }
+ if err := db.Create(&version).Error; err != nil {
+ t.Fatal(err)
+ }
+ initialCount := int64(1)
+ if scenario != "last_version" {
+ latestCreatedAt := int64(2)
+ if err := db.Create(&entity.UserCanvasVersion{
+ ID: "version-2", UserCanvasID: current.ID, Release: true, DSL: current.DSL,
+ BaseModel: entity.BaseModel{CreateTime: &latestCreatedAt},
+ }).Error; err != nil {
+ t.Fatal(err)
+ }
+ initialCount++
+ }
+
+ action.run(NewAgentHandler(t.Context(), service.NewAgentService(), nil), c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, body: %s", w.Code, w.Body.String())
+ }
+ var response struct {
+ Code common.ErrorCode `json:"code"`
+ Data interface{} `json:"data"`
+ Message string `json:"message"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
+ t.Fatal(err)
+ }
+ if response.Code != wantCode || response.Message == "" {
+ t.Fatalf("unexpected response: %s", w.Body.String())
+ }
+ if wantCode == common.CodeSuccess && response.Data != true {
+ t.Fatalf("success data = %v, want true", response.Data)
+ }
+ persisted, err := dao.NewUserCanvasDAO().GetByID(t.Context(), db, current.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantDSL, wantRelease, wantCount := current.DSL, current.Release, initialCount
+ if wantCode == common.CodeSuccess {
+ if action.name == "apply" {
+ wantDSL, wantRelease, wantCount = version.DSL, false, initialCount+1
+ } else {
+ wantCount--
+ }
+ }
+ if !reflect.DeepEqual(persisted.DSL, wantDSL) || persisted.Release != wantRelease {
+ t.Fatalf("unexpected current agent: dsl=%v release=%v", persisted.DSL, persisted.Release)
+ }
+ if *persisted.Title != *current.Title || *persisted.Description != *current.Description || persisted.Tags != current.Tags || persisted.UserID != current.UserID {
+ t.Fatal("agent metadata changed")
+ }
+ var count int64
+ if err := db.Model(&entity.UserCanvasVersion{}).Count(&count).Error; err != nil {
+ t.Fatal(err)
+ }
+ if count != wantCount {
+ t.Fatalf("version count = %d, want %d", count, wantCount)
+ }
+ if scenario != "last_version" {
+ if _, err := dao.NewUserCanvasVersionDAO().GetByID(t.Context(), db, "version-2"); err != nil {
+ t.Fatalf("latest version was removed: %v", err)
+ }
+ }
+ if action.name == "apply" || wantCode != common.CodeSuccess {
+ retained, err := dao.NewUserCanvasVersionDAO().GetByID(t.Context(), db, version.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(retained.DSL, version.DSL) || retained.Release != version.Release || *retained.Title != *version.Title {
+ t.Fatal("source version changed")
+ }
+ }
+ })
+ }
+ }
+}
diff --git a/internal/router/agent_routes.go b/internal/router/agent_routes.go
index f37dbbb32b..e9bf5c4c03 100644
--- a/internal/router/agent_routes.go
+++ b/internal/router/agent_routes.go
@@ -67,6 +67,7 @@ func RegisterAgentRoutes(g *gin.RouterGroup, h *handler.AgentHandler) {
g.GET("/:canvas_id/versions", h.ListVersions)
g.GET("/:canvas_id/versions/:version_id", h.GetVersion)
g.DELETE("/:canvas_id/versions/:version_id", h.DeleteVersion)
+ g.POST("/:canvas_id/versions/:version_id/apply", h.ApplyVersion)
// Sessions.
g.GET("/:canvas_id/sessions", h.ListAgentSessions)
diff --git a/internal/router/agent_routes_test.go b/internal/router/agent_routes_test.go
index 7af24df403..ed6e56ab66 100644
--- a/internal/router/agent_routes_test.go
+++ b/internal/router/agent_routes_test.go
@@ -55,10 +55,11 @@ func TestAgentRoutesRegistered(t *testing.T) {
{http.MethodGet, "/api/v1/agents/abc/versions"},
{http.MethodGet, "/api/v1/agents/abc/versions/v1"},
{http.MethodDelete, "/api/v1/agents/abc/versions/v1"},
+ {http.MethodPost, "/api/v1/agents/abc/versions/v1/apply"},
{http.MethodPost, "/api/v1/agents/abc/reset"},
}
- if len(cases) != 11 {
- t.Fatalf("expected 11 routes, listed %d", len(cases))
+ if len(cases) != 12 {
+ t.Fatalf("expected 12 routes, listed %d", len(cases))
}
for _, c := range cases {
w := httptest.NewRecorder()
diff --git a/internal/service/agent.go b/internal/service/agent.go
index fa5a287128..adbc0f0484 100644
--- a/internal/service/agent.go
+++ b/internal/service/agent.go
@@ -1421,6 +1421,22 @@ func (s *AgentService) DeleteVersion(ctx context.Context, userID, canvasID, vers
})
}
+// ApplyVersion restores a saved version's DSL through the normal draft-save
+// path, preserving the agent's metadata and version history.
+func (s *AgentService) ApplyVersion(ctx context.Context, userID, canvasID, versionID string) error {
+ version, err := s.GetVersion(ctx, userID, canvasID, versionID)
+ if err != nil {
+ if errors.Is(err, dao.ErrUserCanvasNotFound) || errors.Is(err, dao.ErrUserCanvasVersionNotFound) {
+ return err
+ }
+ return fmt.Errorf("load agent version: %w: %w", err, ErrAgentStorageError)
+ }
+ if version.DSL == nil {
+ return errors.New("agent version has no DSL to apply")
+ }
+ return s.UpdateAgent(ctx, userID, canvasID, map[string]interface{}{"dsl": version.DSL})
+}
+
// RunAgent starts a run for the given canvas and returns a channel of
// orchestrator events the HTTP layer streams back as SSE. The driver owns
// the wait-for-user cycle (eino interrupt, gap-analysis §11.6.4): the
diff --git a/internal/service/agent_version_test.go b/internal/service/agent_version_test.go
new file mode 100644
index 0000000000..5450c9b5d4
--- /dev/null
+++ b/internal/service/agent_version_test.go
@@ -0,0 +1,115 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package service
+
+import (
+ "context"
+ "errors"
+ "reflect"
+ "testing"
+
+ "gorm.io/gorm"
+
+ "ragflow/internal/dao"
+ "ragflow/internal/entity"
+)
+
+func TestApplyVersionDraftSave(t *testing.T) {
+ for _, scenario := range []string{"repeat", "version_save_failure", "canceled"} {
+ t.Run(scenario, func(t *testing.T) {
+ setupAgentSessionServiceTest(t)
+ current := entity.UserCanvas{
+ ID: "canvas-1", UserID: "user-1", Release: true,
+ DSL: entity.JSONMap{"components": map[string]interface{}{}, "revision": "current"},
+ }
+ if err := dao.DB.Create(&current).Error; err != nil {
+ t.Fatal(err)
+ }
+ createdAt := int64(1)
+ version := entity.UserCanvasVersion{
+ ID: "version-1", UserCanvasID: current.ID, Release: true,
+ DSL: entity.JSONMap{"components": map[string]interface{}{}, "revision": "old"},
+ BaseModel: entity.BaseModel{CreateTime: &createdAt},
+ }
+ if err := dao.DB.Create(&version).Error; err != nil {
+ t.Fatal(err)
+ }
+ latestCreatedAt := int64(2)
+ if err := dao.DB.Create(&entity.UserCanvasVersion{
+ ID: "version-2", UserCanvasID: current.ID, Release: true, DSL: current.DSL,
+ BaseModel: entity.BaseModel{CreateTime: &latestCreatedAt},
+ }).Error; err != nil {
+ t.Fatal(err)
+ }
+
+ ctx := t.Context()
+ var wantErr error
+ if scenario == "version_save_failure" {
+ wantErr = errors.New("version write failed")
+ if err := dao.DB.Callback().Create().Before("gorm:create").Register("fail_version_save", func(tx *gorm.DB) {
+ if tx.Statement.Table == "user_canvas_version" {
+ tx.AddError(wantErr)
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ } else if scenario == "canceled" {
+ var cancel context.CancelFunc
+ ctx, cancel = context.WithCancel(ctx)
+ cancel()
+ wantErr = context.Canceled
+ }
+ svc := NewAgentService()
+ err := svc.ApplyVersion(ctx, "user-1", current.ID, version.ID)
+ if !errors.Is(err, wantErr) {
+ t.Fatalf("ApplyVersion error = %v, want %v", err, wantErr)
+ }
+ wantDSL, wantRelease, wantCount := current.DSL, true, 2
+ if wantErr == nil {
+ latest, err := dao.NewUserCanvasVersionDAO().GetLatest(ctx, dao.DB, current.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := svc.ApplyVersion(ctx, "user-1", current.ID, version.ID); err != nil {
+ t.Fatalf("repeated ApplyVersion failed: %v", err)
+ }
+ after, err := dao.NewUserCanvasVersionDAO().GetLatest(ctx, dao.DB, current.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if after.ID != latest.ID || after.Release {
+ t.Fatal("repeated apply did not reuse the latest draft")
+ }
+ wantDSL, wantRelease, wantCount = version.DSL, false, 3
+ }
+ persisted, err := dao.NewUserCanvasDAO().GetByID(t.Context(), dao.DB, current.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(persisted.DSL, wantDSL) || persisted.Release != wantRelease {
+ t.Fatalf("unexpected agent after apply: dsl=%v release=%v", persisted.DSL, persisted.Release)
+ }
+ versions, err := dao.NewUserCanvasVersionDAO().ListByCanvasID(t.Context(), dao.DB, current.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(versions) != wantCount {
+ t.Fatalf("version count = %d, want %d", len(versions), wantCount)
+ }
+ })
+ }
+}