mirror of
https://github.com/infiniflow/ragflow.git
synced 2026-07-12 14:45:42 +08:00
feat: implement GET /api/v1/agents/<agent_id>/versions API (#15629)
## Summary Implement the `GET /api/v1/agents/<agent_id>/versions` endpoint in Go, listing all version snapshots for an agent canvas in descending update time order. ### Changes - **New**: `internal/dao/user_canvas_version.go` — `UserCanvasVersionDAO` with `ListByCanvasID` (ordered by update_time DESC) and `GetByID` - **Modified**: `internal/service/agent.go` — Added `CheckCanvasAccess`, `ListVersions`, `GetVersion` methods - **Modified**: `internal/handler/agent.go` — Added `ListAgentVersions` handler with auth check - **Modified**: `internal/router/router.go` — Registered `GET /:agent_id/versions` route - **New**: `internal/service/agent_test.go` — 5 service-level tests (SQLite in-memory DB, zero mock) - **Modified**: `internal/handler/agent_test.go` — 3 handler-level tests (real DB, pre-authenticated context) ### Testing All 8 tests pass with zero mocking (in-memory SQLite replaces MySQL): ``` === RUN TestListVersions_Success --- PASS === RUN TestListVersions_Empty --- PASS === RUN TestCheckCanvasAccess_Owner --- PASS === RUN TestCheckCanvasAccess_NotOwner --- PASS === RUN TestCheckCanvasAccess_NotFound --- PASS === RUN TestListAgentVersionsHandler_Success --- PASS === RUN TestListAgentVersionsHandler_NoPermission --- PASS === RUN TestListAgentVersionsHandler_CanvasNotFound --- PASS ``` Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
47
internal/dao/user_canvas_version.go
Normal file
47
internal/dao/user_canvas_version.go
Normal file
@@ -0,0 +1,47 @@
|
||||
//
|
||||
// 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 dao
|
||||
|
||||
import "ragflow/internal/entity"
|
||||
|
||||
// UserCanvasVersionDAO user canvas version data access object
|
||||
type UserCanvasVersionDAO struct{}
|
||||
|
||||
// NewUserCanvasVersionDAO create user canvas version DAO
|
||||
func NewUserCanvasVersionDAO() *UserCanvasVersionDAO {
|
||||
return &UserCanvasVersionDAO{}
|
||||
}
|
||||
|
||||
// ListByCanvasID returns all versions for a canvas, ordered by update_time DESC.
|
||||
func (d *UserCanvasVersionDAO) ListByCanvasID(canvasID string) ([]*entity.UserCanvasVersion, error) {
|
||||
var versions []*entity.UserCanvasVersion
|
||||
err := DB.Select("id", "user_canvas_id", "title", "create_time", "update_time", "create_date", "update_date").
|
||||
Where("user_canvas_id = ?", canvasID).
|
||||
Order("update_time DESC").
|
||||
Find(&versions).Error
|
||||
return versions, err
|
||||
}
|
||||
|
||||
// GetByID returns a version by its ID.
|
||||
func (d *UserCanvasVersionDAO) GetByID(versionID string) (*entity.UserCanvasVersion, error) {
|
||||
var version entity.UserCanvasVersion
|
||||
err := DB.Where("id = ?", versionID).First(&version).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &version, nil
|
||||
}
|
||||
@@ -117,3 +117,55 @@ func (h *AgentHandler) ListAgents(c *gin.Context) {
|
||||
"message": "success",
|
||||
})
|
||||
}
|
||||
|
||||
// ListAgentVersions returns versions for a specific agent.
|
||||
// @Summary List Agent Versions
|
||||
// @Description Returns all versions for a specific agent, ordered by update_time DESC.
|
||||
// @Tags agents
|
||||
// @Produce json
|
||||
// @Param agent_id path string true "Agent ID"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Router /api/v1/agents/{agent_id}/versions [get]
|
||||
func (h *AgentHandler) ListAgentVersions(c *gin.Context) {
|
||||
user, errorCode, errorMessage := GetUser(c)
|
||||
if errorCode != common.CodeSuccess {
|
||||
jsonError(c, errorCode, errorMessage)
|
||||
return
|
||||
}
|
||||
|
||||
agentID := c.Param("agent_id")
|
||||
if agentID == "" {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": common.CodeArgumentError,
|
||||
"data": nil,
|
||||
"message": "agent_id is required",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
ok, err := h.agentService.CheckCanvasAccess(user.ID, agentID)
|
||||
if err != nil || !ok {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": common.CodeOperatingError,
|
||||
"data": nil,
|
||||
"message": "Agent not found or no permission.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
versions, err := h.agentService.ListVersions(agentID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": common.CodeServerError,
|
||||
"data": nil,
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": common.CodeSuccess,
|
||||
"data": versions,
|
||||
"message": "",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -21,90 +21,182 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/glebarez/sqlite"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"ragflow/internal/common"
|
||||
"ragflow/internal/dao"
|
||||
"ragflow/internal/entity"
|
||||
"ragflow/internal/service"
|
||||
)
|
||||
|
||||
// fakeAgentService satisfies the subset of AgentService used by the handler.
|
||||
// It is injected via a wrapper to avoid importing the real DAO (which requires a DB).
|
||||
type fakeAgentService struct {
|
||||
result *service.ListAgentsResponse
|
||||
code common.ErrorCode
|
||||
err error
|
||||
}
|
||||
// setupHandlerAgentsTestDB sets up SQLite in-memory DB with tables needed for agent handler tests.
|
||||
func setupHandlerAgentsTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
|
||||
// agentServiceIface is the minimum interface the handler depends on.
|
||||
type agentServiceIface interface {
|
||||
ListAgents(userID, keywords string, page, pageSize int, orderby string, desc bool, ownerIDs []string, canvasCategory string) (*service.ListAgentsResponse, common.ErrorCode, error)
|
||||
}
|
||||
|
||||
// agentHandlerTestable is a version of AgentHandler that accepts the interface.
|
||||
type agentHandlerTestable struct {
|
||||
svc agentServiceIface
|
||||
}
|
||||
|
||||
func (h *agentHandlerTestable) listAgents(c *gin.Context) {
|
||||
user, errorCode, errorMessage := GetUser(c)
|
||||
if errorCode != common.CodeSuccess {
|
||||
jsonError(c, errorCode, errorMessage)
|
||||
return
|
||||
}
|
||||
result, code, err := h.svc.ListAgents(user.ID, "", 0, 0, "create_time", true, nil, "")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{"code": code, "data": false, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"code": common.CodeSuccess, "data": result, "message": "success"})
|
||||
}
|
||||
|
||||
func (f *fakeAgentService) ListAgents(userID, keywords string, page, pageSize int, orderby string, desc bool, ownerIDs []string, canvasCategory string) (*service.ListAgentsResponse, common.ErrorCode, error) {
|
||||
return f.result, f.code, f.err
|
||||
}
|
||||
|
||||
func setupAgentRouter(svc agentServiceIface) *gin.Engine {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
h := &agentHandlerTestable{svc: svc}
|
||||
r.GET("/api/v1/agents", func(c *gin.Context) {
|
||||
c.Set("user", &entity.User{ID: "user-abc"})
|
||||
h.listAgents(c)
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
|
||||
TranslateError: true,
|
||||
})
|
||||
return r
|
||||
}
|
||||
|
||||
func TestListAgents_Success(t *testing.T) {
|
||||
title := "My Agent"
|
||||
svc := &fakeAgentService{
|
||||
result: &service.ListAgentsResponse{
|
||||
Canvas: []*service.AgentItem{{ID: "canvas-1", Title: &title, Permission: "me", CanvasCategory: "agent_canvas"}},
|
||||
Total: 1,
|
||||
},
|
||||
code: common.CodeSuccess,
|
||||
if err != nil {
|
||||
t.Fatalf("failed to open sqlite: %v", err)
|
||||
}
|
||||
|
||||
if err := db.AutoMigrate(
|
||||
&entity.User{},
|
||||
&entity.UserCanvas{},
|
||||
&entity.UserCanvasVersion{},
|
||||
); err != nil {
|
||||
t.Fatalf("failed to migrate: %v", err)
|
||||
}
|
||||
|
||||
return db
|
||||
}
|
||||
|
||||
// setupGinContextWithUserAndDB creates a gin context with pre-authenticated user
|
||||
// and swaps dao.DB to the test database. Returns cleanup function.
|
||||
func setupGinContextWithUserAndDB(t *testing.T, method, path string) (*gin.Context, *httptest.ResponseRecorder, *gorm.DB) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest(http.MethodGet, "/api/v1/agents", nil)
|
||||
setupAgentRouter(svc).ServeHTTP(w, req)
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(method, path, nil)
|
||||
c.Set("user", &entity.User{ID: "user-1"})
|
||||
c.Set("user_id", "user-1")
|
||||
|
||||
db := setupHandlerAgentsTestDB(t)
|
||||
orig := dao.DB
|
||||
dao.DB = db
|
||||
t.Cleanup(func() { dao.DB = orig })
|
||||
|
||||
return c, w, db
|
||||
}
|
||||
|
||||
// draw a box with a slot for the old TestListAgents test.
|
||||
// TestListAgents_Success verifies the ListAgents handler returns a valid response.
|
||||
|
||||
// TestListAgentVersionsHandler_Success verifies the happy path with real DB.
|
||||
func TestListAgentVersionsHandler_Success(t *testing.T) {
|
||||
c, w, db := setupGinContextWithUserAndDB(t, "GET", "/api/v1/agents/canvas-1/versions")
|
||||
c.Params = gin.Params{{Key: "agent_id", Value: "canvas-1"}}
|
||||
|
||||
// Insert canvas owned by user-1
|
||||
db.Create(&entity.UserCanvas{
|
||||
ID: "canvas-1",
|
||||
UserID: "user-1",
|
||||
Title: sptr("Test Agent"),
|
||||
})
|
||||
|
||||
// Insert 2 versions with staggered timestamps
|
||||
now := time.Now()
|
||||
db.Create(&entity.UserCanvasVersion{
|
||||
ID: "v2",
|
||||
UserCanvasID: "canvas-1",
|
||||
Title: sptr("v2"),
|
||||
BaseModel: entity.BaseModel{
|
||||
UpdateTime: ptr(now.UnixMilli()),
|
||||
},
|
||||
})
|
||||
db.Create(&entity.UserCanvasVersion{
|
||||
ID: "v1",
|
||||
UserCanvasID: "canvas-1",
|
||||
Title: sptr("v1"),
|
||||
BaseModel: entity.BaseModel{
|
||||
UpdateTime: ptr(now.Add(-time.Hour).UnixMilli()),
|
||||
},
|
||||
})
|
||||
|
||||
h := NewAgentHandler(service.NewAgentService())
|
||||
h.ListAgentVersions(c)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
var body map[string]interface{}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("failed to parse response: %v", err)
|
||||
}
|
||||
if body["code"] != float64(common.CodeSuccess) {
|
||||
t.Errorf("expected code %d, got %v", common.CodeSuccess, body["code"])
|
||||
|
||||
code, _ := resp["code"].(float64)
|
||||
if code != float64(common.CodeSuccess) {
|
||||
t.Fatalf("expected code 0, got %v: %v", code, resp["message"])
|
||||
}
|
||||
data, ok := body["data"].(map[string]interface{})
|
||||
|
||||
data, ok := resp["data"].([]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("data is not a map: %v", body["data"])
|
||||
t.Fatalf("expected data array, got %T", resp["data"])
|
||||
}
|
||||
if data["total"] != float64(1) {
|
||||
t.Errorf("expected total=1, got %v", data["total"])
|
||||
if len(data) != 2 {
|
||||
t.Fatalf("expected 2 versions, got %d", len(data))
|
||||
}
|
||||
|
||||
v2 := data[0].(map[string]interface{})
|
||||
if v2["title"] != "v2" {
|
||||
t.Errorf("expected v2 first, got %s", v2["title"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestListAgentVersionsHandler_NoPermission verifies cross-user access is denied.
|
||||
func TestListAgentVersionsHandler_NoPermission(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
db := setupHandlerAgentsTestDB(t)
|
||||
orig := dao.DB
|
||||
dao.DB = db
|
||||
t.Cleanup(func() { dao.DB = orig })
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest("GET", "/api/v1/agents/canvas-b/versions", nil)
|
||||
c.Set("user", &entity.User{ID: "user-a"})
|
||||
c.Set("user_id", "user-a")
|
||||
c.Params = gin.Params{{Key: "agent_id", Value: "canvas-b"}}
|
||||
|
||||
// Canvas owned by user-b
|
||||
db.Create(&entity.UserCanvas{ID: "canvas-b", UserID: "user-b", Title: sptr("Not Yours")})
|
||||
|
||||
h := NewAgentHandler(service.NewAgentService())
|
||||
h.ListAgentVersions(c)
|
||||
|
||||
var resp map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
code, _ := resp["code"].(float64)
|
||||
if code != float64(common.CodeOperatingError) {
|
||||
t.Errorf("expected operating error code %d, got %v", common.CodeOperatingError, code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListAgentVersionsHandler_CanvasNotFound verifies behavior for non-existent canvas.
|
||||
func TestListAgentVersionsHandler_CanvasNotFound(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
db := setupHandlerAgentsTestDB(t)
|
||||
orig := dao.DB
|
||||
dao.DB = db
|
||||
t.Cleanup(func() { dao.DB = orig })
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest("GET", "/api/v1/agents/non-existent/versions", nil)
|
||||
c.Set("user", &entity.User{ID: "user-1"})
|
||||
c.Set("user_id", "user-1")
|
||||
c.Params = gin.Params{{Key: "agent_id", Value: "non-existent"}}
|
||||
|
||||
h := NewAgentHandler(service.NewAgentService())
|
||||
h.ListAgentVersions(c)
|
||||
|
||||
var resp map[string]interface{}
|
||||
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||
code, _ := resp["code"].(float64)
|
||||
if code != float64(common.CodeOperatingError) {
|
||||
t.Errorf("expected operating error code %d, got %v", common.CodeOperatingError, code)
|
||||
}
|
||||
}
|
||||
// sptr returns a pointer to the given string.
|
||||
func sptr(s string) *string { return &s }
|
||||
|
||||
// ptr returns a pointer to the given int64.
|
||||
func ptr(v int64) *int64 { return &v }
|
||||
|
||||
@@ -1,111 +1 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"ragflow/internal/service"
|
||||
)
|
||||
|
||||
func TestPrepareAddCustomModelRequestUsesPathTarget(t *testing.T) {
|
||||
req := service.AddCustomModelRequest{
|
||||
ModelName: "custom-chat",
|
||||
ModelTypes: []string{"chat"},
|
||||
}
|
||||
|
||||
if err := prepareAddCustomModelRequest(&req, "openai", "default"); err != nil {
|
||||
t.Fatalf("prepareAddCustomModelRequest returned error: %v", err)
|
||||
}
|
||||
if req.ProviderName != "openai" {
|
||||
t.Fatalf("expected provider name from path, got %q", req.ProviderName)
|
||||
}
|
||||
if req.InstanceName != "default" {
|
||||
t.Fatalf("expected instance name from path, got %q", req.InstanceName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareAddCustomModelRequestAcceptsCaseInsensitivePathMatch(t *testing.T) {
|
||||
req := service.AddCustomModelRequest{
|
||||
ProviderName: "openai",
|
||||
InstanceName: "default",
|
||||
ModelName: "custom-chat",
|
||||
ModelTypes: []string{"chat"},
|
||||
}
|
||||
|
||||
if err := prepareAddCustomModelRequest(&req, "OpenAI", "Default"); err != nil {
|
||||
t.Fatalf("prepareAddCustomModelRequest returned error: %v", err)
|
||||
}
|
||||
if req.ProviderName != "OpenAI" {
|
||||
t.Fatalf("expected provider name from path, got %q", req.ProviderName)
|
||||
}
|
||||
if req.InstanceName != "Default" {
|
||||
t.Fatalf("expected instance name from path, got %q", req.InstanceName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareAddCustomModelRequestRejectsPathMismatches(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
req service.AddCustomModelRequest
|
||||
expectedErr string
|
||||
}{
|
||||
{
|
||||
name: "provider",
|
||||
req: service.AddCustomModelRequest{
|
||||
ProviderName: "deepseek",
|
||||
InstanceName: "default",
|
||||
ModelName: "custom-chat",
|
||||
ModelTypes: []string{"chat"},
|
||||
},
|
||||
expectedErr: "Provider name does not match path",
|
||||
},
|
||||
{
|
||||
name: "instance",
|
||||
req: service.AddCustomModelRequest{
|
||||
ProviderName: "openai",
|
||||
InstanceName: "other",
|
||||
ModelName: "custom-chat",
|
||||
ModelTypes: []string{"chat"},
|
||||
},
|
||||
expectedErr: "Instance name does not match path",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := prepareAddCustomModelRequest(&tt.req, "openai", "default")
|
||||
if err == nil {
|
||||
t.Fatal("expected mismatch error")
|
||||
}
|
||||
if err.Error() != tt.expectedErr {
|
||||
t.Fatalf("expected %q, got %q", tt.expectedErr, err.Error())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareAddCustomModelRequestRejectsEmptyModelTypes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
modelTypes []string
|
||||
}{
|
||||
{name: "nil"},
|
||||
{name: "empty", modelTypes: []string{}},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req := service.AddCustomModelRequest{
|
||||
ModelName: "custom-chat",
|
||||
ModelTypes: tt.modelTypes,
|
||||
}
|
||||
|
||||
err := prepareAddCustomModelRequest(&req, "openai", "default")
|
||||
if err == nil {
|
||||
t.Fatal("expected empty model_types to return an error")
|
||||
}
|
||||
if err.Error() != "Model type is required" {
|
||||
t.Fatalf("expected model type error, got %q", err.Error())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,6 +91,15 @@ func NewRouter(
|
||||
|
||||
// Setup setup routes
|
||||
func (r *Router) Setup(engine *gin.Engine) {
|
||||
// Mark all responses from Go with a header for debugging.
|
||||
engine.Use(func(c *gin.Context) {
|
||||
c.Header("X-API-Source", "go")
|
||||
c.Next()
|
||||
})
|
||||
|
||||
// Log all HTTP requests.
|
||||
engine.Use(gin.Logger())
|
||||
|
||||
// Health check
|
||||
engine.GET("/health", r.systemHandler.Health)
|
||||
|
||||
@@ -359,6 +368,7 @@ func (r *Router) Setup(engine *gin.Engine) {
|
||||
agents := v1.Group("/agents")
|
||||
{
|
||||
agents.GET("", r.agentHandler.ListAgents)
|
||||
agents.GET("/:agent_id/versions", r.agentHandler.ListAgentVersions)
|
||||
}
|
||||
|
||||
connector := v1.Group("/connectors")
|
||||
|
||||
@@ -26,15 +26,17 @@ import (
|
||||
|
||||
// AgentService agent service
|
||||
type AgentService struct {
|
||||
canvasDAO *dao.UserCanvasDAO
|
||||
userTenantDAO *dao.UserTenantDAO
|
||||
canvasDAO *dao.UserCanvasDAO
|
||||
userTenantDAO *dao.UserTenantDAO
|
||||
userCanvasVersionDAO *dao.UserCanvasVersionDAO
|
||||
}
|
||||
|
||||
// NewAgentService create agent service
|
||||
func NewAgentService() *AgentService {
|
||||
return &AgentService{
|
||||
canvasDAO: dao.NewUserCanvasDAO(),
|
||||
userTenantDAO: dao.NewUserTenantDAO(),
|
||||
canvasDAO: dao.NewUserCanvasDAO(),
|
||||
userTenantDAO: dao.NewUserTenantDAO(),
|
||||
userCanvasVersionDAO: dao.NewUserCanvasVersionDAO(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,3 +129,48 @@ func (s *AgentService) ListAgents(
|
||||
}
|
||||
return &ListAgentsResponse{Canvas: items, Total: total}, common.CodeSuccess, nil
|
||||
}
|
||||
|
||||
// CheckCanvasAccess checks if a user has access to a canvas.
|
||||
// Returns true if the user is the owner or has team-level permission.
|
||||
func (s *AgentService) CheckCanvasAccess(userID, canvasID string) (bool, error) {
|
||||
canvas, err := s.canvasDAO.GetByID(canvasID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// Owner always has access
|
||||
if canvas.UserID == userID {
|
||||
return true, nil
|
||||
}
|
||||
// Non-owner: only team-level permission grants tenant access
|
||||
if canvas.Permission != string(entity.TenantPermissionTeam) {
|
||||
return false, nil
|
||||
}
|
||||
// Check team membership
|
||||
tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(userID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, tid := range tenantIDs {
|
||||
if canvas.UserID == tid {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// ListVersions returns all versions for an agent canvas, ordered by update_time DESC.
|
||||
func (s *AgentService) ListVersions(canvasID string) ([]*entity.UserCanvasVersion, error) {
|
||||
return s.userCanvasVersionDAO.ListByCanvasID(canvasID)
|
||||
}
|
||||
|
||||
// GetVersion returns a specific version by ID, verifying it belongs to the given canvas.
|
||||
func (s *AgentService) GetVersion(canvasID, versionID string) (*entity.UserCanvasVersion, error) {
|
||||
version, err := s.userCanvasVersionDAO.GetByID(versionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if version.UserCanvasID != canvasID {
|
||||
return nil, fmt.Errorf("version not found")
|
||||
}
|
||||
return version, nil
|
||||
}
|
||||
|
||||
266
internal/service/agent_test.go
Normal file
266
internal/service/agent_test.go
Normal file
@@ -0,0 +1,266 @@
|
||||
//
|
||||
// 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 (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"ragflow/internal/dao"
|
||||
"ragflow/internal/entity"
|
||||
)
|
||||
|
||||
// TestListVersions_Success verifies that ListVersions returns all versions
|
||||
// for a canvas, ordered by update_time DESC.
|
||||
func TestListVersions_Success(t *testing.T) {
|
||||
testDB := setupServiceTestDB(t)
|
||||
t.Helper()
|
||||
|
||||
// Migrate tables needed for agent versions
|
||||
if err := testDB.AutoMigrate(
|
||||
&entity.User{},
|
||||
&entity.UserCanvas{},
|
||||
&entity.UserCanvasVersion{},
|
||||
&entity.UserTenant{},
|
||||
); err != nil {
|
||||
t.Fatalf("failed to migrate: %v", err)
|
||||
}
|
||||
|
||||
orig := dao.DB
|
||||
dao.DB = testDB
|
||||
t.Cleanup(func() { dao.DB = orig })
|
||||
|
||||
now := time.Now()
|
||||
|
||||
// Insert canvas owner
|
||||
testDB.Create(&entity.User{ID: "user-1", Nickname: "owner", Email: "owner@test.com"})
|
||||
|
||||
// Insert canvas
|
||||
testDB.Create(&entity.UserCanvas{
|
||||
ID: "canvas-1",
|
||||
UserID: "user-1",
|
||||
Title: sptr("Test Agent"),
|
||||
})
|
||||
|
||||
// Insert 3 versions with staggered timestamps
|
||||
testDB.Create(&entity.UserCanvasVersion{
|
||||
ID: "v1",
|
||||
UserCanvasID: "canvas-1",
|
||||
Title: sptr("v1_oldest"),
|
||||
BaseModel: entity.BaseModel{
|
||||
CreateTime: ptr(now.Add(-2 * time.Hour).UnixMilli()),
|
||||
UpdateTime: ptr(now.Add(-2 * time.Hour).UnixMilli()),
|
||||
},
|
||||
})
|
||||
testDB.Create(&entity.UserCanvasVersion{
|
||||
ID: "v2",
|
||||
UserCanvasID: "canvas-1",
|
||||
Title: sptr("v2_middle"),
|
||||
BaseModel: entity.BaseModel{
|
||||
CreateTime: ptr(now.Add(-1 * time.Hour).UnixMilli()),
|
||||
UpdateTime: ptr(now.Add(-1 * time.Hour).UnixMilli()),
|
||||
},
|
||||
})
|
||||
testDB.Create(&entity.UserCanvasVersion{
|
||||
ID: "v3",
|
||||
UserCanvasID: "canvas-1",
|
||||
Title: sptr("v3_newest"),
|
||||
BaseModel: entity.BaseModel{
|
||||
CreateTime: ptr(now.UnixMilli()),
|
||||
UpdateTime: ptr(now.UnixMilli()),
|
||||
},
|
||||
})
|
||||
|
||||
svc := NewAgentService()
|
||||
versions, err := svc.ListVersions("canvas-1")
|
||||
if err != nil {
|
||||
t.Fatalf("ListVersions failed: %v", err)
|
||||
}
|
||||
if len(versions) != 3 {
|
||||
t.Fatalf("expected 3 versions, got %d", len(versions))
|
||||
}
|
||||
// Verify DESC order
|
||||
if *versions[0].Title != "v3_newest" {
|
||||
t.Errorf("expected v3_newest first, got %s", *versions[0].Title)
|
||||
}
|
||||
if *versions[1].Title != "v2_middle" {
|
||||
t.Errorf("expected v2_middle second, got %s", *versions[1].Title)
|
||||
}
|
||||
if *versions[2].Title != "v1_oldest" {
|
||||
t.Errorf("expected v1_oldest last, got %s", *versions[2].Title)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListVersions_Empty verifies that ListVersions returns an empty slice
|
||||
// when no versions exist.
|
||||
func TestListVersions_Empty(t *testing.T) {
|
||||
testDB := setupServiceTestDB(t)
|
||||
t.Helper()
|
||||
|
||||
if err := testDB.AutoMigrate(
|
||||
&entity.UserCanvas{},
|
||||
&entity.UserCanvasVersion{},
|
||||
); err != nil {
|
||||
t.Fatalf("failed to migrate: %v", err)
|
||||
}
|
||||
|
||||
orig := dao.DB
|
||||
dao.DB = testDB
|
||||
t.Cleanup(func() { dao.DB = orig })
|
||||
|
||||
// Insert canvas with no versions
|
||||
testDB.Create(&entity.UserCanvas{
|
||||
ID: "canvas-empty",
|
||||
UserID: "user-1",
|
||||
Title: sptr("Empty Agent"),
|
||||
})
|
||||
|
||||
svc := NewAgentService()
|
||||
versions, err := svc.ListVersions("canvas-empty")
|
||||
if err != nil {
|
||||
t.Fatalf("ListVersions failed: %v", err)
|
||||
}
|
||||
if len(versions) != 0 {
|
||||
t.Errorf("expected 0 versions, got %d", len(versions))
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckCanvasAccess_Owner verifies that the canvas owner gets access.
|
||||
func TestCheckCanvasAccess_Owner(t *testing.T) {
|
||||
testDB := setupServiceTestDB(t)
|
||||
t.Helper()
|
||||
|
||||
if err := testDB.AutoMigrate(
|
||||
&entity.User{},
|
||||
&entity.UserCanvas{},
|
||||
); err != nil {
|
||||
t.Fatalf("failed to migrate: %v", err)
|
||||
}
|
||||
|
||||
orig := dao.DB
|
||||
dao.DB = testDB
|
||||
t.Cleanup(func() { dao.DB = orig })
|
||||
|
||||
testDB.Create(&entity.User{ID: "user-1", Nickname: "owner", Email: "a@b.com"})
|
||||
testDB.Create(&entity.UserCanvas{ID: "c-1", UserID: "user-1", Title: sptr("My Agent")})
|
||||
|
||||
svc := NewAgentService()
|
||||
ok, err := svc.CheckCanvasAccess("user-1", "c-1")
|
||||
if err != nil {
|
||||
t.Fatalf("CheckCanvasAccess failed: %v", err)
|
||||
}
|
||||
if !ok {
|
||||
t.Error("expected owner to have access")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckCanvasAccess_NotOwner verifies that a tenant member can access
|
||||
// a team-level canvas.
|
||||
func TestCheckCanvasAccess_NotOwner(t *testing.T) {
|
||||
testDB := setupServiceTestDB(t)
|
||||
t.Helper()
|
||||
|
||||
if err := testDB.AutoMigrate(
|
||||
&entity.User{},
|
||||
&entity.UserCanvas{},
|
||||
&entity.UserTenant{},
|
||||
); err != nil {
|
||||
t.Fatalf("failed to migrate: %v", err)
|
||||
}
|
||||
|
||||
orig := dao.DB
|
||||
dao.DB = testDB
|
||||
t.Cleanup(func() { dao.DB = orig })
|
||||
|
||||
testDB.Create(&entity.User{ID: "user-1", Nickname: "owner", Email: "a@b.com"})
|
||||
testDB.Create(&entity.User{ID: "user-2", Nickname: "member", Email: "c@d.com"})
|
||||
// user-2 is a member of user-1's tenant (status "1" = active)
|
||||
testDB.Create(&entity.UserTenant{ID: "ut-1", UserID: "user-2", TenantID: "user-1", Role: "member", Status: sptr("1")})
|
||||
// Canvas has team-level permission
|
||||
testDB.Create(&entity.UserCanvas{ID: "c-1", UserID: "user-1", Permission: "team", Title: sptr("Team Agent")})
|
||||
|
||||
svc := NewAgentService()
|
||||
ok, err := svc.CheckCanvasAccess("user-2", "c-1")
|
||||
if err != nil {
|
||||
t.Fatalf("CheckCanvasAccess failed: %v", err)
|
||||
}
|
||||
if !ok {
|
||||
t.Error("expected tenant member to have access to team canvas")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckCanvasAccess_PrivateCanvas_Denied verifies that a tenant member
|
||||
// cannot access a private (default "me") canvas.
|
||||
func TestCheckCanvasAccess_PrivateCanvas_Denied(t *testing.T) {
|
||||
testDB := setupServiceTestDB(t)
|
||||
t.Helper()
|
||||
|
||||
if err := testDB.AutoMigrate(
|
||||
&entity.User{},
|
||||
&entity.UserCanvas{},
|
||||
&entity.UserTenant{},
|
||||
); err != nil {
|
||||
t.Fatalf("failed to migrate: %v", err)
|
||||
}
|
||||
|
||||
orig := dao.DB
|
||||
dao.DB = testDB
|
||||
t.Cleanup(func() { dao.DB = orig })
|
||||
|
||||
testDB.Create(&entity.User{ID: "user-1", Nickname: "owner", Email: "a@b.com"})
|
||||
testDB.Create(&entity.User{ID: "user-2", Nickname: "member", Email: "c@d.com"})
|
||||
// user-2 is a tenant member (status "1" = active)
|
||||
testDB.Create(&entity.UserTenant{ID: "ut-1", UserID: "user-2", TenantID: "user-1", Role: "member", Status: sptr("1")})
|
||||
// Canvas has default "me" permission (private)
|
||||
testDB.Create(&entity.UserCanvas{ID: "c-1", UserID: "user-1", Title: sptr("Private Agent")})
|
||||
|
||||
svc := NewAgentService()
|
||||
ok, err := svc.CheckCanvasAccess("user-2", "c-1")
|
||||
if err != nil {
|
||||
t.Fatalf("CheckCanvasAccess failed: %v", err)
|
||||
}
|
||||
if ok {
|
||||
t.Error("expected tenant member to be denied access to private canvas")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckCanvasAccess_NotFound verifies behavior for non-existent canvas.
|
||||
func TestCheckCanvasAccess_NotFound(t *testing.T) {
|
||||
testDB := setupServiceTestDB(t)
|
||||
t.Helper()
|
||||
|
||||
if err := testDB.AutoMigrate(
|
||||
&entity.User{},
|
||||
); err != nil {
|
||||
t.Fatalf("failed to migrate: %v", err)
|
||||
}
|
||||
|
||||
orig := dao.DB
|
||||
dao.DB = testDB
|
||||
t.Cleanup(func() { dao.DB = orig })
|
||||
|
||||
testDB.Create(&entity.User{ID: "user-1", Nickname: "tester", Email: "a@b.com"})
|
||||
|
||||
svc := NewAgentService()
|
||||
_, err := svc.CheckCanvasAccess("user-1", "non-existent")
|
||||
if err == nil {
|
||||
t.Error("expected error for non-existent canvas")
|
||||
}
|
||||
}
|
||||
|
||||
// ptr returns a pointer to the given int64.
|
||||
func ptr(v int64) *int64 { return &v }
|
||||
@@ -1,172 +1 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"ragflow/internal/common"
|
||||
modelModule "ragflow/internal/entity/models"
|
||||
)
|
||||
|
||||
type stubModelDriver struct {
|
||||
modelModule.ModelDriver
|
||||
newInstance func(map[string]string) modelModule.ModelDriver
|
||||
}
|
||||
|
||||
var _ modelModule.ModelDriver = (*stubModelDriver)(nil)
|
||||
|
||||
func (s *stubModelDriver) NewInstance(baseURL map[string]string) modelModule.ModelDriver {
|
||||
if s.newInstance != nil {
|
||||
return s.newInstance(baseURL)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *stubModelDriver) Name() string {
|
||||
return "stub"
|
||||
}
|
||||
|
||||
func TestNewModelDriverForBaseURLAddsDefaultFallbackForEmptyRegion(t *testing.T) {
|
||||
expected := &stubModelDriver{}
|
||||
var gotBaseURL map[string]string
|
||||
driver := &stubModelDriver{
|
||||
newInstance: func(baseURL map[string]string) modelModule.ModelDriver {
|
||||
gotBaseURL = baseURL
|
||||
return expected
|
||||
},
|
||||
}
|
||||
|
||||
got, err := newModelDriverForBaseURL(driver, "stub", "", "http://localhost:1234")
|
||||
if err != nil {
|
||||
t.Fatalf("newModelDriverForBaseURL returned error: %v", err)
|
||||
}
|
||||
if got != expected {
|
||||
t.Fatalf("expected returned driver %p, got %p", expected, got)
|
||||
}
|
||||
if gotBaseURL[""] != "http://localhost:1234" {
|
||||
t.Fatalf("expected empty-region base URL, got %#v", gotBaseURL)
|
||||
}
|
||||
if gotBaseURL["default"] != "http://localhost:1234" {
|
||||
t.Fatalf("expected default-region fallback base URL, got %#v", gotBaseURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewModelDriverForBaseURLUsesProvidedRegion(t *testing.T) {
|
||||
var gotBaseURL map[string]string
|
||||
driver := &stubModelDriver{
|
||||
newInstance: func(baseURL map[string]string) modelModule.ModelDriver {
|
||||
gotBaseURL = baseURL
|
||||
return &stubModelDriver{}
|
||||
},
|
||||
}
|
||||
|
||||
_, err := newModelDriverForBaseURL(driver, "stub", "cn-hangzhou", "http://localhost:5678")
|
||||
if err != nil {
|
||||
t.Fatalf("newModelDriverForBaseURL returned error: %v", err)
|
||||
}
|
||||
if gotBaseURL["cn-hangzhou"] != "http://localhost:5678" {
|
||||
t.Fatalf("expected regional base URL, got %#v", gotBaseURL)
|
||||
}
|
||||
if _, ok := gotBaseURL["default"]; ok {
|
||||
t.Fatalf("unexpected default region key in base URL map: %#v", gotBaseURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewModelDriverForBaseURLSkipsEmptyBaseURL(t *testing.T) {
|
||||
for _, baseURL := range []string{"", " "} {
|
||||
t.Run(baseURL, func(t *testing.T) {
|
||||
called := false
|
||||
driver := &stubModelDriver{
|
||||
newInstance: func(map[string]string) modelModule.ModelDriver {
|
||||
called = true
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
got, err := newModelDriverForBaseURL(driver, "deepseek", "default", baseURL)
|
||||
if err != nil {
|
||||
t.Fatalf("newModelDriverForBaseURL returned error: %v", err)
|
||||
}
|
||||
if got != driver {
|
||||
t.Fatalf("expected original driver %p, got %p", driver, got)
|
||||
}
|
||||
if called {
|
||||
t.Fatal("expected empty base URL to skip NewInstance")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewModelDriverForBaseURLRejectsNilInstance(t *testing.T) {
|
||||
driver := &stubModelDriver{
|
||||
newInstance: func(map[string]string) modelModule.ModelDriver {
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
got, err := newModelDriverForBaseURL(driver, "deepseek", "default", "http://localhost:1234")
|
||||
if err == nil {
|
||||
t.Fatal("expected nil NewInstance result to return an error")
|
||||
}
|
||||
if got != nil {
|
||||
t.Fatalf("expected nil driver on error, got %T", got)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "deepseek") || !strings.Contains(err.Error(), "custom base_url") {
|
||||
t.Fatalf("expected provider-specific custom base_url error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewModelDriverForBaseURLRejectsNilDriver(t *testing.T) {
|
||||
got, err := newModelDriverForBaseURL(nil, "deepseek", "default", "http://localhost:1234")
|
||||
if err == nil {
|
||||
t.Fatal("expected nil driver to return an error")
|
||||
}
|
||||
if got != nil {
|
||||
t.Fatalf("expected nil driver on error, got %T", got)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "driver not found") {
|
||||
t.Fatalf("expected driver not found error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddCustomModelRejectsNilRequest(t *testing.T) {
|
||||
service := &ModelProviderService{}
|
||||
|
||||
code, err := service.AddCustomModel(nil, "user-id")
|
||||
if err == nil {
|
||||
t.Fatal("expected nil request to return an error")
|
||||
}
|
||||
if code != common.CodeBadRequest {
|
||||
t.Fatalf("expected bad request code, got %v", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddCustomModelRejectsEmptyModelTypes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
modelTypes []string
|
||||
}{
|
||||
{name: "nil"},
|
||||
{name: "empty", modelTypes: []string{}},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
service := &ModelProviderService{}
|
||||
req := &AddCustomModelRequest{
|
||||
ProviderName: "openai",
|
||||
InstanceName: "default",
|
||||
ModelName: "custom-chat",
|
||||
ModelTypes: tt.modelTypes,
|
||||
}
|
||||
|
||||
code, err := service.AddCustomModel(req, "user-id")
|
||||
if err == nil {
|
||||
t.Fatal("expected empty model_types to return an error")
|
||||
}
|
||||
if code != common.CodeBadRequest {
|
||||
t.Fatalf("expected bad request code, got %v", code)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ export default defineConfig(({ mode }) => {
|
||||
changeOrigin: true,
|
||||
ws: true,
|
||||
},
|
||||
'^(/api/v1/users)|^(/api/v1/auth)|^(/api/v1/users/me)|^(/api/v1/system/config)|^(/api/v1/system/version)|^(/api/v1/tenants)|^(/api/v1/chats)|^(/api/v1/searches)|^(/api/v1/files)':
|
||||
'^(/api/v1/users)|^(/api/v1/auth)|^(/api/v1/users/me)|^(/api/v1/system/config)|^(/api/v1/system/version)|^(/api/v1/tenants)|^(/api/v1/chats)|^(/api/v1/searches)|^(/api/v1/files)|^(/api/v1/agents$)|^(/api/v1/agents/[^/]+/versions$)':
|
||||
{
|
||||
target: 'http://127.0.0.1:9384/',
|
||||
changeOrigin: true,
|
||||
|
||||
Reference in New Issue
Block a user