refactor: make AI workflows agent-centric

This commit is contained in:
mlogclub
2026-06-22 10:08:51 +08:00
parent 14f50e064f
commit 32ab43e7c2
18 changed files with 436 additions and 400 deletions
+4 -6
View File
@@ -214,6 +214,10 @@ func registerDashboardAgentTeamScheduleRoutes(group *gin.RouterGroup) {
} }
func registerDashboardAIAgentRoutes(group *gin.RouterGroup) { func registerDashboardAIAgentRoutes(group *gin.RouterGroup) {
group.GET("/:id/workflow", dashboard.AIWorkflowGetByAgent)
group.POST("/workflow/save", dashboard.AIWorkflowPostSaveAgent)
group.POST("/workflow/validate", dashboard.AIWorkflowPostValidate)
group.POST("/workflow/publish", dashboard.AIWorkflowPostPublishAgent)
group.GET("/:id", dashboard.AIAgentGetBy) group.GET("/:id", dashboard.AIAgentGetBy)
group.POST("/create", dashboard.AIAgentPostCreate) group.POST("/create", dashboard.AIAgentPostCreate)
group.POST("/delete", dashboard.AIAgentPostDelete) group.POST("/delete", dashboard.AIAgentPostDelete)
@@ -225,16 +229,10 @@ func registerDashboardAIAgentRoutes(group *gin.RouterGroup) {
} }
func registerDashboardAIWorkflowRoutes(group *gin.RouterGroup) { func registerDashboardAIWorkflowRoutes(group *gin.RouterGroup) {
group.Any("/list", dashboard.AIWorkflowAnyList)
group.POST("/create", dashboard.AIWorkflowPostCreate)
group.POST("/update", dashboard.AIWorkflowPostUpdate)
group.POST("/delete", dashboard.AIWorkflowPostDelete)
group.GET("/node-spec/list", dashboard.AIWorkflowGetNodeSpecList) group.GET("/node-spec/list", dashboard.AIWorkflowGetNodeSpecList)
group.POST("/validate", dashboard.AIWorkflowPostValidate) group.POST("/validate", dashboard.AIWorkflowPostValidate)
group.POST("/publish", dashboard.AIWorkflowPostPublish)
group.Any("/version/list", dashboard.AIWorkflowAnyVersionList) group.Any("/version/list", dashboard.AIWorkflowAnyVersionList)
group.GET("/version/:id", dashboard.AIWorkflowGetVersionBy) group.GET("/version/:id", dashboard.AIWorkflowGetVersionBy)
group.GET("/:id", dashboard.AIWorkflowGetBy)
} }
func registerDashboardAIConfigRoutes(group *gin.RouterGroup) { func registerDashboardAIConfigRoutes(group *gin.RouterGroup) {
+1 -2
View File
@@ -17,8 +17,7 @@ func BuildAIWorkflow(item *models.AIWorkflow) response.AIWorkflowResponse {
ID: item.ID, ID: item.ID,
Name: item.Name, Name: item.Name,
Description: item.Description, Description: item.Description,
OwnerType: item.OwnerType, AgentID: item.AgentID,
OwnerID: item.OwnerID,
Status: item.Status, Status: item.Status,
DraftDefinition: parseWorkflowDefinition(item.DraftDefinition), DraftDefinition: parseWorkflowDefinition(item.DraftDefinition),
PublishedVersionID: item.PublishedVersionID, PublishedVersionID: item.PublishedVersionID,
@@ -21,8 +21,7 @@ func AIWorkflowAnyList(ctx *gin.Context) {
cnd := params.NewPagedSqlCnd(ctx, cnd := params.NewPagedSqlCnd(ctx,
params.QueryFilter{ParamName: "status"}, params.QueryFilter{ParamName: "status"},
params.QueryFilter{ParamName: "name", Op: params.Like}, params.QueryFilter{ParamName: "name", Op: params.Like},
params.QueryFilter{ParamName: "ownerType"}, params.QueryFilter{ParamName: "agentId"},
params.QueryFilter{ParamName: "ownerId"},
).Desc("id") ).Desc("id")
list, paging := services.AIWorkflowService.FindPageByCnd(cnd) list, paging := services.AIWorkflowService.FindPageByCnd(cnd)
httpx.WriteJSON(ctx, &web.PageResult{Results: builders.BuildAIWorkflowList(list), Page: paging}) httpx.WriteJSON(ctx, &web.PageResult{Results: builders.BuildAIWorkflowList(list), Page: paging})
@@ -144,6 +143,62 @@ func AIWorkflowPostPublish(ctx *gin.Context) {
httpx.WriteJSON(ctx, builders.BuildAIWorkflowVersion(item)) httpx.WriteJSON(ctx, builders.BuildAIWorkflowVersion(item))
} }
func AIWorkflowGetByAgent(ctx *gin.Context) {
agentID, ok := httpx.GetPathInt64(ctx, "id")
if !ok {
return
}
operator, err := services.AuthService.RequirePermission(ctx, constants.PermissionAIAgentView)
if err != nil {
httpx.WriteJSON(ctx, err)
return
}
item, err := services.AIWorkflowService.GetOrCreateAgentWorkflow(agentID, operator)
if err != nil {
httpx.WriteJSON(ctx, err)
return
}
httpx.WriteJSON(ctx, builders.BuildAIWorkflow(item))
}
func AIWorkflowPostSaveAgent(ctx *gin.Context) {
operator, err := services.AuthService.RequirePermission(ctx, constants.PermissionAIAgentUpdate)
if err != nil {
httpx.WriteJSON(ctx, err)
return
}
req := request.SaveAIWorkflowRequest{}
if err := params.ReadJSON(ctx, &req); err != nil {
httpx.WriteJSON(ctx, err)
return
}
item, err := services.AIWorkflowService.SaveAgentWorkflow(req, operator)
if err != nil {
httpx.WriteJSON(ctx, err)
return
}
httpx.WriteJSON(ctx, builders.BuildAIWorkflow(item))
}
func AIWorkflowPostPublishAgent(ctx *gin.Context) {
operator, err := services.AuthService.RequirePermission(ctx, constants.PermissionAIAgentUpdate)
if err != nil {
httpx.WriteJSON(ctx, err)
return
}
req := request.PublishAIWorkflowRequest{}
if err := params.ReadJSON(ctx, &req); err != nil {
httpx.WriteJSON(ctx, err)
return
}
item, err := services.AIWorkflowService.PublishAgentWorkflow(req, operator)
if err != nil {
httpx.WriteJSON(ctx, err)
return
}
httpx.WriteJSON(ctx, builders.BuildAIWorkflowVersion(item))
}
func AIWorkflowAnyVersionList(ctx *gin.Context) { func AIWorkflowAnyVersionList(ctx *gin.Context) {
if _, err := services.AuthService.RequirePermission(ctx, constants.PermissionAIAgentView); err != nil { if _, err := services.AuthService.RequirePermission(ctx, constants.PermissionAIAgentView); err != nil {
httpx.WriteJSON(ctx, err) httpx.WriteJSON(ctx, err)
+1 -2
View File
@@ -538,8 +538,7 @@ type AIWorkflow struct {
ID int64 `gorm:"primaryKey;autoIncrement"` ID int64 `gorm:"primaryKey;autoIncrement"`
Name string `gorm:"type:varchar(100);not null;default:'';index"` Name string `gorm:"type:varchar(100);not null;default:'';index"`
Description string `gorm:"type:text"` Description string `gorm:"type:text"`
OwnerType string `gorm:"type:varchar(30);not null;default:'';index"` AgentID int64 `gorm:"type:bigint;not null;default:0;index"`
OwnerID int64 `gorm:"type:bigint;not null;default:0;index"`
Status enums.Status `gorm:"type:int;not null;default:0;index"` Status enums.Status `gorm:"type:int;not null;default:0;index"`
DraftDefinition string `gorm:"type:longtext"` DraftDefinition string `gorm:"type:longtext"`
PublishedVersionID int64 `gorm:"type:bigint;not null;default:0;index"` PublishedVersionID int64 `gorm:"type:bigint;not null;default:0;index"`
-2
View File
@@ -58,8 +58,6 @@ type CreateAIAgentRequest struct {
SkillIDs []int64 `json:"skillIds"` SkillIDs []int64 `json:"skillIds"`
DirectTools []AIAgentMCPToolRequest `json:"directTools"` DirectTools []AIAgentMCPToolRequest `json:"directTools"`
GraphTools []string `json:"graphTools"` GraphTools []string `json:"graphTools"`
RuntimeMode enums.AIAgentRuntimeMode `json:"runtimeMode"`
WorkflowVersionID int64 `json:"workflowVersionId"`
} }
type UpdateAIAgentRequest struct { type UpdateAIAgentRequest struct {
@@ -5,11 +5,12 @@ import "agent-desk/internal/ai/workflow/dsl"
type CreateAIWorkflowRequest struct { type CreateAIWorkflowRequest struct {
Name string `json:"name"` Name string `json:"name"`
Description string `json:"description"` Description string `json:"description"`
OwnerType string `json:"ownerType"` AgentID int64 `json:"agentId"`
OwnerID int64 `json:"ownerId"`
Definition dsl.Definition `json:"definition"` Definition dsl.Definition `json:"definition"`
} }
type SaveAIWorkflowRequest = CreateAIWorkflowRequest
type UpdateAIWorkflowRequest struct { type UpdateAIWorkflowRequest struct {
ID int64 `json:"id"` ID int64 `json:"id"`
CreateAIWorkflowRequest CreateAIWorkflowRequest
@@ -25,6 +26,7 @@ type ValidateAIWorkflowRequest struct {
type PublishAIWorkflowRequest struct { type PublishAIWorkflowRequest struct {
WorkflowID int64 `json:"workflowId"` WorkflowID int64 `json:"workflowId"`
AgentID int64 `json:"agentId"`
Definition dsl.Definition `json:"definition"` Definition dsl.Definition `json:"definition"`
} }
@@ -11,8 +11,7 @@ type AIWorkflowResponse struct {
ID int64 `json:"id"` ID int64 `json:"id"`
Name string `json:"name"` Name string `json:"name"`
Description string `json:"description"` Description string `json:"description"`
OwnerType string `json:"ownerType"` AgentID int64 `json:"agentId"`
OwnerID int64 `json:"ownerId"`
Status enums.Status `json:"status"` Status enums.Status `json:"status"`
DraftDefinition dsl.Definition `json:"draftDefinition"` DraftDefinition dsl.Definition `json:"draftDefinition"`
PublishedVersionID int64 `json:"publishedVersionId"` PublishedVersionID int64 `json:"publishedVersionId"`
+9 -9
View File
@@ -75,7 +75,13 @@ func (s *aIAgentService) CreateAIAgent(req request.CreateAIAgentRequest, operato
item.Status = enums.StatusOk item.Status = enums.StatusOk
item.SortNo = 0 item.SortNo = 0
item.AuditFields = utils.BuildAuditFields(operator) item.AuditFields = utils.BuildAuditFields(operator)
if err := repositories.AIAgentRepository.Create(sqls.DB(), item); err != nil { if err := sqls.WithTransaction(func(ctx *sqls.TxContext) error {
if err := repositories.AIAgentRepository.Create(ctx.Tx, item); err != nil {
return err
}
_, err := AIWorkflowService.createDefaultAgentWorkflow(ctx.Tx, item, operator)
return err
}); err != nil {
return nil, err return nil, err
} }
return item, nil return item, nil
@@ -108,8 +114,6 @@ func (s *aIAgentService) UpdateAIAgent(req request.UpdateAIAgentRequest, operato
"skill_ids": item.SkillIDs, "skill_ids": item.SkillIDs,
"allowed_mcp_tools": item.AllowedMCPTools, "allowed_mcp_tools": item.AllowedMCPTools,
"allowed_graph_tools": item.AllowedGraphTools, "allowed_graph_tools": item.AllowedGraphTools,
"runtime_mode": item.RuntimeMode,
"workflow_version_id": item.WorkflowVersionID,
"update_user_id": operator.UserID, "update_user_id": operator.UserID,
"update_user_name": operator.Username, "update_user_name": operator.Username,
"updated_at": time.Now(), "updated_at": time.Now(),
@@ -193,10 +197,6 @@ func (s *aIAgentService) buildAIAgentModel(id int64, req request.CreateAIAgentRe
if err != nil { if err != nil {
return nil, err return nil, err
} }
runtimeMode, workflowVersionID, err := s.normalizeRuntimeMode(req.RuntimeMode, req.WorkflowVersionID)
if err != nil {
return nil, err
}
directToolsJSON := "" directToolsJSON := ""
if len(directTools) > 0 { if len(directTools) > 0 {
buf, marshalErr := json.Marshal(directTools) buf, marshalErr := json.Marshal(directTools)
@@ -229,8 +229,8 @@ func (s *aIAgentService) buildAIAgentModel(id int64, req request.CreateAIAgentRe
SkillIDs: utils.JoinInt64s(skillIDs), SkillIDs: utils.JoinInt64s(skillIDs),
AllowedMCPTools: directToolsJSON, AllowedMCPTools: directToolsJSON,
AllowedGraphTools: graphToolsJSON, AllowedGraphTools: graphToolsJSON,
RuntimeMode: runtimeMode, RuntimeMode: enums.AIAgentRuntimeModeBuiltinGraph,
WorkflowVersionID: workflowVersionID, WorkflowVersionID: 0,
}, nil }, nil
} }
@@ -1,8 +1,10 @@
package services package services
import ( import (
"encoding/json"
"testing" "testing"
"agent-desk/internal/ai/workflow/dsl"
"agent-desk/internal/models" "agent-desk/internal/models"
"agent-desk/internal/pkg/dto" "agent-desk/internal/pkg/dto"
"agent-desk/internal/pkg/dto/request" "agent-desk/internal/pkg/dto/request"
@@ -13,52 +15,89 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
func TestAIAgentServiceSavesWorkflowBinding(t *testing.T) { func TestAIAgentServiceCreatesDefaultWorkflow(t *testing.T) {
setupAIAgentWorkflowTestDB(t) setupAIAgentWorkflowTestDB(t)
operator := aiAgentWorkflowTestOperator() operator := aiAgentWorkflowTestOperator()
aiConfigID := createAIAgentWorkflowTestConfig(t) aiConfigID := createAIAgentWorkflowTestConfig(t)
knowledgeID := createAIAgentWorkflowTestKnowledgeBase(t) knowledgeID := createAIAgentWorkflowTestKnowledgeBase(t)
versionID := createAIAgentWorkflowVersion(t)
item, err := AIAgentService.CreateAIAgent(request.CreateAIAgentRequest{ item, err := AIAgentService.CreateAIAgent(request.CreateAIAgentRequest{
Name: "workflow agent", Name: "workflow agent",
AIConfigID: aiConfigID, AIConfigID: aiConfigID,
ServiceMode: enums.IMConversationServiceModeAIOnly, ServiceMode: enums.IMConversationServiceModeAIOnly,
HandoffMode: enums.AIAgentHandoffModeWaitPool, HandoffMode: enums.AIAgentHandoffModeWaitPool,
FallbackMode: enums.AIAgentFallbackModeNoAnswer, FallbackMode: enums.AIAgentFallbackModeNoAnswer,
KnowledgeIDs: []int64{knowledgeID}, KnowledgeIDs: []int64{knowledgeID},
RuntimeMode: enums.AIAgentRuntimeModeWorkflow,
WorkflowVersionID: versionID,
}, operator) }, operator)
if err != nil { if err != nil {
t.Fatalf("CreateAIAgent() error = %v", err) t.Fatalf("CreateAIAgent() error = %v", err)
} }
if item.RuntimeMode != enums.AIAgentRuntimeModeWorkflow { workflow, err := AIWorkflowService.GetOrCreateAgentWorkflow(item.ID, operator)
t.Fatalf("expected workflow runtime mode, got %d", item.RuntimeMode) if err != nil {
t.Fatalf("GetOrCreateAgentWorkflow() error = %v", err)
} }
if item.WorkflowVersionID != versionID { if workflow.AgentID != item.ID {
t.Fatalf("expected workflow version %d, got %d", versionID, item.WorkflowVersionID) t.Fatalf("expected workflow agent id %d, got %d", item.ID, workflow.AgentID)
}
if workflow.Name != item.Name+" 会话流程" {
t.Fatalf("unexpected workflow name: %s", workflow.Name)
}
var stored dsl.Definition
if err := json.Unmarshal([]byte(workflow.DraftDefinition), &stored); err != nil {
t.Fatalf("unmarshal draft definition: %v", err)
}
if stored.EntryNodeID == "" {
t.Fatalf("expected default draft definition")
} }
} }
func TestAIAgentServiceRejectsWorkflowModeWithoutVersion(t *testing.T) { func TestAIWorkflowServicePublishAgentWorkflowBindsAgentVersion(t *testing.T) {
setupAIAgentWorkflowTestDB(t) setupAIAgentWorkflowTestDB(t)
operator := aiAgentWorkflowTestOperator() operator := aiAgentWorkflowTestOperator()
aiConfigID := createAIAgentWorkflowTestConfig(t) aiConfigID := createAIAgentWorkflowTestConfig(t)
knowledgeID := createAIAgentWorkflowTestKnowledgeBase(t) knowledgeID := createAIAgentWorkflowTestKnowledgeBase(t)
_, err := AIAgentService.CreateAIAgent(request.CreateAIAgentRequest{ agent, err := AIAgentService.CreateAIAgent(request.CreateAIAgentRequest{
Name: "workflow agent without version", Name: "workflow agent without version",
AIConfigID: aiConfigID, AIConfigID: aiConfigID,
ServiceMode: enums.IMConversationServiceModeAIOnly, ServiceMode: enums.IMConversationServiceModeAIOnly,
HandoffMode: enums.AIAgentHandoffModeWaitPool, HandoffMode: enums.AIAgentHandoffModeWaitPool,
FallbackMode: enums.AIAgentFallbackModeNoAnswer, FallbackMode: enums.AIAgentFallbackModeNoAnswer,
KnowledgeIDs: []int64{knowledgeID}, KnowledgeIDs: []int64{knowledgeID},
RuntimeMode: enums.AIAgentRuntimeModeWorkflow,
}, operator) }, operator)
if err == nil { if err != nil {
t.Fatalf("expected workflow runtime without version to fail") t.Fatalf("CreateAIAgent() error = %v", err)
}
workflow, err := AIWorkflowService.SaveAgentWorkflow(request.SaveAIWorkflowRequest{
AgentID: agent.ID,
Name: "After sales flow",
Description: "Support workflow",
Definition: validAIWorkflowDefinition(),
}, operator)
if err != nil {
t.Fatalf("SaveAgentWorkflow() error = %v", err)
}
version, err := AIWorkflowService.PublishAgentWorkflow(request.PublishAIWorkflowRequest{
AgentID: agent.ID,
Definition: validAIWorkflowDefinition(),
}, operator)
if err != nil {
t.Fatalf("PublishAgentWorkflow() error = %v", err)
}
if version.WorkflowID != workflow.ID {
t.Fatalf("expected version workflow id %d, got %d", workflow.ID, version.WorkflowID)
}
storedAgent := AIAgentService.Get(agent.ID)
if storedAgent == nil {
t.Fatalf("expected stored agent")
}
if storedAgent.RuntimeMode != enums.AIAgentRuntimeModeWorkflow {
t.Fatalf("expected agent runtime workflow, got %d", storedAgent.RuntimeMode)
}
if storedAgent.WorkflowVersionID != version.ID {
t.Fatalf("expected agent workflow version %d, got %d", version.ID, storedAgent.WorkflowVersionID)
} }
} }
@@ -105,10 +144,9 @@ func createAIAgentWorkflowTestKnowledgeBase(t *testing.T) int64 {
func createAIAgentWorkflowVersion(t *testing.T) int64 { func createAIAgentWorkflowVersion(t *testing.T) int64 {
t.Helper() t.Helper()
workflow := &models.AIWorkflow{ workflow := &models.AIWorkflow{
Name: "workflow-test", Name: "workflow-test",
OwnerType: "ai_agent", AgentID: 1,
OwnerID: 1, Status: enums.StatusOk,
Status: enums.StatusOk,
} }
if err := sqls.DB().Create(workflow).Error; err != nil { if err := sqls.DB().Create(workflow).Error; err != nil {
t.Fatalf("create workflow: %v", err) t.Fatalf("create workflow: %v", err)
+183 -36
View File
@@ -20,6 +20,7 @@ import (
"agent-desk/internal/repositories" "agent-desk/internal/repositories"
"github.com/mlogclub/simple/sqls" "github.com/mlogclub/simple/sqls"
"gorm.io/gorm"
) )
var AIWorkflowService = newAIWorkflowService() var AIWorkflowService = newAIWorkflowService()
@@ -56,6 +57,49 @@ func (s *aiWorkflowService) FindVersionPageByParams(params *params.QueryParams)
return repositories.AIWorkflowVersionRepository.FindPageByParams(sqls.DB(), params) return repositories.AIWorkflowVersionRepository.FindPageByParams(sqls.DB(), params)
} }
func (s *aiWorkflowService) GetByAgentID(agentID int64) *models.AIWorkflow {
if agentID <= 0 {
return nil
}
return repositories.AIWorkflowRepository.Take(sqls.DB(), "agent_id = ? AND status <> ?", agentID, enums.StatusDeleted)
}
func (s *aiWorkflowService) GetOrCreateAgentWorkflow(agentID int64, operator *dto.AuthPrincipal) (*models.AIWorkflow, error) {
if operator == nil {
return nil, errorsx.UnauthorizedI18n("error.auth.expired")
}
if agentID <= 0 {
return nil, errorsx.InvalidParam("agent id is required")
}
if agent := AIAgentService.Get(agentID); agent == nil || agent.Status == enums.StatusDeleted {
return nil, errorsx.InvalidParamI18n("error.e0002")
}
if item := s.GetByAgentID(agentID); item != nil {
return item, nil
}
var item *models.AIWorkflow
err := sqls.WithTransaction(func(ctx *sqls.TxContext) error {
if current := repositories.AIWorkflowRepository.Take(ctx.Tx, "agent_id = ? AND status <> ?", agentID, enums.StatusDeleted); current != nil {
item = current
return nil
}
agent := repositories.AIAgentRepository.Get(ctx.Tx, agentID)
if agent == nil || agent.Status == enums.StatusDeleted {
return errorsx.InvalidParamI18n("error.e0002")
}
created, err := s.createDefaultAgentWorkflow(ctx.Tx, agent, operator)
if err != nil {
return err
}
item = created
return nil
})
if err != nil {
return nil, err
}
return item, nil
}
func (s *aiWorkflowService) ListNodeSpecs() []workflowregistry.NodeSpec { func (s *aiWorkflowService) ListNodeSpecs() []workflowregistry.NodeSpec {
return s.registry.List() return s.registry.List()
} }
@@ -65,37 +109,52 @@ func (s *aiWorkflowService) ValidateDefinition(def dsl.Definition) workflowvalid
} }
func (s *aiWorkflowService) CreateWorkflow(req request.CreateAIWorkflowRequest, operator *dto.AuthPrincipal) (*models.AIWorkflow, error) { func (s *aiWorkflowService) CreateWorkflow(req request.CreateAIWorkflowRequest, operator *dto.AuthPrincipal) (*models.AIWorkflow, error) {
return s.SaveAgentWorkflow(req, operator)
}
func (s *aiWorkflowService) SaveAgentWorkflow(req request.SaveAIWorkflowRequest, operator *dto.AuthPrincipal) (*models.AIWorkflow, error) {
if operator == nil { if operator == nil {
return nil, errorsx.UnauthorizedI18n("error.auth.expired") return nil, errorsx.UnauthorizedI18n("error.auth.expired")
} }
agent := AIAgentService.Get(req.AgentID)
if agent == nil || agent.Status == enums.StatusDeleted {
return nil, errorsx.InvalidParamI18n("error.e0002")
}
name := strings.TrimSpace(req.Name) name := strings.TrimSpace(req.Name)
if name == "" { if name == "" {
return nil, errorsx.InvalidParam("workflow name is required") name = defaultAgentWorkflowName(agent.Name)
}
ownerType := normalizeWorkflowOwnerType(req.OwnerType)
if ownerType == "" {
return nil, errorsx.InvalidParam("workflow owner type is required")
}
if req.OwnerID <= 0 {
return nil, errorsx.InvalidParam("workflow owner id is required")
} }
definition, err := marshalDefinition(req.Definition) definition, err := marshalDefinition(req.Definition)
if err != nil { if err != nil {
return nil, err return nil, err
} }
item := &models.AIWorkflow{ current := s.GetByAgentID(req.AgentID)
Name: name, if current == nil {
Description: strings.TrimSpace(req.Description), item := &models.AIWorkflow{
OwnerType: ownerType, Name: name,
OwnerID: req.OwnerID, Description: strings.TrimSpace(req.Description),
Status: enums.StatusOk, AgentID: req.AgentID,
DraftDefinition: definition, Status: enums.StatusOk,
AuditFields: utils.BuildAuditFields(operator), DraftDefinition: definition,
AuditFields: utils.BuildAuditFields(operator),
}
if err := repositories.AIWorkflowRepository.Create(sqls.DB(), item); err != nil {
return nil, err
}
return item, nil
} }
if err := repositories.AIWorkflowRepository.Create(sqls.DB(), item); err != nil { if err := repositories.AIWorkflowRepository.Updates(sqls.DB(), current.ID, map[string]interface{}{
"name": name,
"description": strings.TrimSpace(req.Description),
"agent_id": req.AgentID,
"draft_definition": definition,
"update_user_id": operator.UserID,
"update_user_name": operator.Username,
"updated_at": time.Now(),
}); err != nil {
return nil, err return nil, err
} }
return item, nil return s.Get(current.ID), nil
} }
func (s *aiWorkflowService) UpdateWorkflow(req request.UpdateAIWorkflowRequest, operator *dto.AuthPrincipal) error { func (s *aiWorkflowService) UpdateWorkflow(req request.UpdateAIWorkflowRequest, operator *dto.AuthPrincipal) error {
@@ -109,12 +168,8 @@ func (s *aiWorkflowService) UpdateWorkflow(req request.UpdateAIWorkflowRequest,
if name == "" { if name == "" {
return errorsx.InvalidParam("workflow name is required") return errorsx.InvalidParam("workflow name is required")
} }
ownerType := normalizeWorkflowOwnerType(req.OwnerType) if req.AgentID <= 0 {
if ownerType == "" { return errorsx.InvalidParam("agent id is required")
return errorsx.InvalidParam("workflow owner type is required")
}
if req.OwnerID <= 0 {
return errorsx.InvalidParam("workflow owner id is required")
} }
definition, err := marshalDefinition(req.Definition) definition, err := marshalDefinition(req.Definition)
if err != nil { if err != nil {
@@ -123,8 +178,7 @@ func (s *aiWorkflowService) UpdateWorkflow(req request.UpdateAIWorkflowRequest,
return repositories.AIWorkflowRepository.Updates(sqls.DB(), req.ID, map[string]interface{}{ return repositories.AIWorkflowRepository.Updates(sqls.DB(), req.ID, map[string]interface{}{
"name": name, "name": name,
"description": strings.TrimSpace(req.Description), "description": strings.TrimSpace(req.Description),
"owner_type": ownerType, "agent_id": req.AgentID,
"owner_id": req.OwnerID,
"draft_definition": definition, "draft_definition": definition,
"update_user_id": operator.UserID, "update_user_id": operator.UserID,
"update_user_name": operator.Username, "update_user_name": operator.Username,
@@ -148,6 +202,9 @@ func (s *aiWorkflowService) DeleteWorkflow(id int64, operator *dto.AuthPrincipal
} }
func (s *aiWorkflowService) PublishWorkflow(req request.PublishAIWorkflowRequest, operator *dto.AuthPrincipal) (*models.AIWorkflowVersion, error) { func (s *aiWorkflowService) PublishWorkflow(req request.PublishAIWorkflowRequest, operator *dto.AuthPrincipal) (*models.AIWorkflowVersion, error) {
if req.AgentID > 0 {
return s.PublishAgentWorkflow(req, operator)
}
if operator == nil { if operator == nil {
return nil, errorsx.UnauthorizedI18n("error.auth.expired") return nil, errorsx.UnauthorizedI18n("error.auth.expired")
} }
@@ -195,6 +252,106 @@ func (s *aiWorkflowService) PublishWorkflow(req request.PublishAIWorkflowRequest
return version, nil return version, nil
} }
func (s *aiWorkflowService) PublishAgentWorkflow(req request.PublishAIWorkflowRequest, operator *dto.AuthPrincipal) (*models.AIWorkflowVersion, error) {
if operator == nil {
return nil, errorsx.UnauthorizedI18n("error.auth.expired")
}
workflow, err := s.GetOrCreateAgentWorkflow(req.AgentID, operator)
if err != nil {
return nil, err
}
req.WorkflowID = workflow.ID
result := s.ValidateDefinition(req.Definition)
if !result.Valid {
return nil, errorsx.InvalidParam("workflow definition is invalid")
}
definition, err := marshalDefinition(req.Definition)
if err != nil {
return nil, err
}
now := time.Now()
var version *models.AIWorkflowVersion
err = sqls.WithTransaction(func(ctx *sqls.TxContext) error {
current := repositories.AIWorkflowRepository.Get(ctx.Tx, workflow.ID)
if current == nil || current.AgentID != req.AgentID || current.Status == enums.StatusDeleted {
return errorsx.InvalidParamI18n("error.e0002")
}
nextVersion := repositories.AIWorkflowVersionRepository.MaxVersionByWorkflowID(ctx.Tx, current.ID) + 1
version = &models.AIWorkflowVersion{
WorkflowID: current.ID,
Version: nextVersion,
Status: enums.StatusOk,
Definition: definition,
DefinitionHash: hashDefinition(definition),
PublishedAt: &now,
PublishedByID: operator.UserID,
PublishedByName: operator.Username,
AuditFields: utils.BuildAuditFields(operator),
}
if err := repositories.AIWorkflowVersionRepository.Create(ctx.Tx, version); err != nil {
return err
}
if err := repositories.AIWorkflowRepository.Updates(ctx.Tx, current.ID, map[string]interface{}{
"draft_definition": definition,
"published_version_id": version.ID,
"update_user_id": operator.UserID,
"update_user_name": operator.Username,
"updated_at": now,
}); err != nil {
return err
}
return repositories.AIAgentRepository.Updates(ctx.Tx, req.AgentID, map[string]any{
"runtime_mode": enums.AIAgentRuntimeModeWorkflow,
"workflow_version_id": version.ID,
"update_user_id": operator.UserID,
"update_user_name": operator.Username,
"updated_at": now,
})
})
if err != nil {
return nil, err
}
return version, nil
}
func (s *aiWorkflowService) createDefaultAgentWorkflow(db *gorm.DB, agent *models.AIAgent, operator *dto.AuthPrincipal) (*models.AIWorkflow, error) {
definition, err := marshalDefinition(defaultAgentWorkflowDefinition())
if err != nil {
return nil, err
}
item := &models.AIWorkflow{
Name: defaultAgentWorkflowName(agent.Name),
AgentID: agent.ID,
Status: enums.StatusOk,
DraftDefinition: definition,
AuditFields: utils.BuildAuditFields(operator),
}
if err := repositories.AIWorkflowRepository.Create(db, item); err != nil {
return nil, err
}
return item, nil
}
func defaultAgentWorkflowDefinition() dsl.Definition {
return dsl.Definition{
SchemaVersion: 1,
EntryNodeID: "start_1",
Nodes: []dsl.Node{
{ID: "start_1", Type: workflowregistry.NodeTypeStart, Name: "Start", Position: dsl.Position{X: 0, Y: 80}},
{ID: "end_1", Type: workflowregistry.NodeTypeEnd, Name: "End", Position: dsl.Position{X: 360, Y: 80}},
},
Edges: []dsl.Edge{{ID: "edge_start_end", Source: "start_1", Target: "end_1"}},
}
}
func defaultAgentWorkflowName(agentName string) string {
agentName = strings.TrimSpace(agentName)
if agentName == "" {
return "会话流程"
}
return agentName + " 会话流程"
}
func marshalDefinition(def dsl.Definition) (string, error) { func marshalDefinition(def dsl.Definition) (string, error) {
buf, err := json.Marshal(def) buf, err := json.Marshal(def)
if err != nil { if err != nil {
@@ -207,13 +364,3 @@ func hashDefinition(definition string) string {
sum := sha256.Sum256([]byte(definition)) sum := sha256.Sum256([]byte(definition))
return hex.EncodeToString(sum[:]) return hex.EncodeToString(sum[:])
} }
func normalizeWorkflowOwnerType(ownerType string) string {
ownerType = strings.TrimSpace(ownerType)
switch ownerType {
case "ai_agent", "workspace":
return ownerType
default:
return ""
}
}
+10 -7
View File
@@ -8,6 +8,7 @@ import (
"agent-desk/internal/models" "agent-desk/internal/models"
"agent-desk/internal/pkg/dto" "agent-desk/internal/pkg/dto"
"agent-desk/internal/pkg/dto/request" "agent-desk/internal/pkg/dto/request"
"agent-desk/internal/pkg/enums"
"agent-desk/internal/repositories" "agent-desk/internal/repositories"
"github.com/glebarez/sqlite" "github.com/glebarez/sqlite"
@@ -45,8 +46,7 @@ func TestAIWorkflowServicePublishCreatesImmutableVersion(t *testing.T) {
workflow, err := AIWorkflowService.CreateWorkflow(request.CreateAIWorkflowRequest{ workflow, err := AIWorkflowService.CreateWorkflow(request.CreateAIWorkflowRequest{
Name: "support flow", Name: "support flow",
Description: "customer service flow", Description: "customer service flow",
OwnerType: "ai_agent", AgentID: 12,
OwnerID: 12,
Definition: validAIWorkflowDefinition(), Definition: validAIWorkflowDefinition(),
}, operator) }, operator)
if err != nil { if err != nil {
@@ -88,8 +88,7 @@ func TestAIWorkflowServicePublishIncrementsVersion(t *testing.T) {
operator := aiWorkflowTestOperator() operator := aiWorkflowTestOperator()
workflow, err := AIWorkflowService.CreateWorkflow(request.CreateAIWorkflowRequest{ workflow, err := AIWorkflowService.CreateWorkflow(request.CreateAIWorkflowRequest{
Name: "support flow versions", Name: "support flow versions",
OwnerType: "ai_agent", AgentID: 99,
OwnerID: 99,
Definition: validAIWorkflowDefinition(), Definition: validAIWorkflowDefinition(),
}, operator) }, operator)
if err != nil { if err != nil {
@@ -121,8 +120,7 @@ func TestAIWorkflowServicePublishRejectsInvalidDSL(t *testing.T) {
operator := aiWorkflowTestOperator() operator := aiWorkflowTestOperator()
workflow, err := AIWorkflowService.CreateWorkflow(request.CreateAIWorkflowRequest{ workflow, err := AIWorkflowService.CreateWorkflow(request.CreateAIWorkflowRequest{
Name: "invalid publish flow", Name: "invalid publish flow",
OwnerType: "ai_agent", AgentID: 23,
OwnerID: 23,
Definition: validAIWorkflowDefinition(), Definition: validAIWorkflowDefinition(),
}, operator) }, operator)
if err != nil { if err != nil {
@@ -159,10 +157,15 @@ func setupAIWorkflowTestDB(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("open sqlite db: %v", err) t.Fatalf("open sqlite db: %v", err)
} }
if err := db.AutoMigrate(&models.AIWorkflow{}, &models.AIWorkflowVersion{}, &models.AIWorkflowRun{}, &models.AIWorkflowNodeRun{}); err != nil { if err := db.AutoMigrate(&models.AIAgent{}, &models.AIWorkflow{}, &models.AIWorkflowVersion{}, &models.AIWorkflowRun{}, &models.AIWorkflowNodeRun{}); err != nil {
t.Fatalf("auto migrate: %v", err) t.Fatalf("auto migrate: %v", err)
} }
sqls.SetDB(db) sqls.SetDB(db)
for _, id := range []int64{12, 23, 99} {
if err := sqls.DB().Create(&models.AIAgent{ID: id, Name: "agent", Status: enums.StatusOk}).Error; err != nil {
t.Fatalf("create ai agent: %v", err)
}
}
} }
func validAIWorkflowDefinition() dsl.Definition { func validAIWorkflowDefinition() dsl.Definition {
@@ -41,14 +41,12 @@ import { Textarea } from "@/components/ui/textarea";
import { import {
fetchAIAgent, fetchAIAgent,
fetchAIConfigsAll, fetchAIConfigsAll,
fetchAIWorkflowVersions,
fetchAgentTeamsAll, fetchAgentTeamsAll,
fetchKnowledgeBasesAll, fetchKnowledgeBasesAll,
fetchMCPCatalog, fetchMCPCatalog,
fetchSkillDefinitionsAll, fetchSkillDefinitionsAll,
type AIAgent, type AIAgent,
type AIConfig, type AIConfig,
type AIWorkflowVersion,
type AdminAgentTeam, type AdminAgentTeam,
type CreateAIAgentPayload, type CreateAIAgentPayload,
type KnowledgeBase, type KnowledgeBase,
@@ -96,8 +94,6 @@ type EditForm = {
description: string; description: string;
aiConfigId: string; aiConfigId: string;
serviceMode: string; serviceMode: string;
runtimeMode: string;
workflowVersionId: string;
systemPrompt: string; systemPrompt: string;
welcomeMessage: string; welcomeMessage: string;
replyTimeoutSeconds: number; replyTimeoutSeconds: number;
@@ -106,9 +102,6 @@ type EditForm = {
fallbackMessage: string; fallbackMessage: string;
}; };
const AI_AGENT_RUNTIME_MODE_BUILTIN_GRAPH = 1;
const AI_AGENT_RUNTIME_MODE_WORKFLOW = 2;
function getServiceModeOptions(t: TFunction) { function getServiceModeOptions(t: TFunction) {
return [ return [
{ value: String(IMConversationServiceMode.AIOnly), label: t("aiAgent.serviceAiOnly") }, { value: String(IMConversationServiceMode.AIOnly), label: t("aiAgent.serviceAiOnly") },
@@ -139,8 +132,6 @@ function buildForm(item: AIAgent | null): EditForm {
description: "", description: "",
aiConfigId: "", aiConfigId: "",
serviceMode: String(IMConversationServiceMode.AIFirst), serviceMode: String(IMConversationServiceMode.AIFirst),
runtimeMode: String(AI_AGENT_RUNTIME_MODE_BUILTIN_GRAPH),
workflowVersionId: "",
systemPrompt: "", systemPrompt: "",
welcomeMessage: "", welcomeMessage: "",
replyTimeoutSeconds: 180, replyTimeoutSeconds: 180,
@@ -154,8 +145,6 @@ function buildForm(item: AIAgent | null): EditForm {
description: item.description || "", description: item.description || "",
aiConfigId: item.aiConfigId > 0 ? String(item.aiConfigId) : "", aiConfigId: item.aiConfigId > 0 ? String(item.aiConfigId) : "",
serviceMode: String(item.serviceMode), serviceMode: String(item.serviceMode),
runtimeMode: String(item.runtimeMode || AI_AGENT_RUNTIME_MODE_BUILTIN_GRAPH),
workflowVersionId: item.workflowVersionId > 0 ? String(item.workflowVersionId) : "",
systemPrompt: item.systemPrompt || "", systemPrompt: item.systemPrompt || "",
welcomeMessage: item.welcomeMessage || "", welcomeMessage: item.welcomeMessage || "",
replyTimeoutSeconds: item.replyTimeoutSeconds ?? 180, replyTimeoutSeconds: item.replyTimeoutSeconds ?? 180,
@@ -178,11 +167,6 @@ function buildPayload(
description: form.description.trim(), description: form.description.trim(),
aiConfigId: Number(form.aiConfigId), aiConfigId: Number(form.aiConfigId),
serviceMode: Number(form.serviceMode), serviceMode: Number(form.serviceMode),
runtimeMode: Number(form.runtimeMode),
workflowVersionId:
Number(form.runtimeMode) === AI_AGENT_RUNTIME_MODE_WORKFLOW
? Number(form.workflowVersionId)
: 0,
systemPrompt: form.systemPrompt.trim(), systemPrompt: form.systemPrompt.trim(),
welcomeMessage: form.welcomeMessage.trim(), welcomeMessage: form.welcomeMessage.trim(),
replyTimeoutSeconds: Number(form.replyTimeoutSeconds), replyTimeoutSeconds: Number(form.replyTimeoutSeconds),
@@ -236,8 +220,6 @@ function EditDialogBody({
description: z.string().trim(), description: z.string().trim(),
aiConfigId: z.string().trim().regex(/^\d+$/, t("aiAgent.aiConfigRequired")), aiConfigId: z.string().trim().regex(/^\d+$/, t("aiAgent.aiConfigRequired")),
serviceMode: z.string().trim().min(1, t("aiAgent.serviceModeRequired")), serviceMode: z.string().trim().min(1, t("aiAgent.serviceModeRequired")),
runtimeMode: z.string().trim().min(1, t("aiAgent.runtimeModeRequired")),
workflowVersionId: z.string().trim(),
systemPrompt: z.string().trim(), systemPrompt: z.string().trim(),
welcomeMessage: z.string().trim(), welcomeMessage: z.string().trim(),
replyTimeoutSeconds: z replyTimeoutSeconds: z
@@ -246,18 +228,6 @@ function EditDialogBody({
handoffMode: z.string().trim().min(1, t("aiAgent.handoffModeRequired")), handoffMode: z.string().trim().min(1, t("aiAgent.handoffModeRequired")),
fallbackMode: z.string().trim().min(1, t("aiAgent.fallbackModeRequired")), fallbackMode: z.string().trim().min(1, t("aiAgent.fallbackModeRequired")),
fallbackMessage: z.string().trim(), fallbackMessage: z.string().trim(),
}).check((ctx) => {
if (
ctx.value.runtimeMode === String(AI_AGENT_RUNTIME_MODE_WORKFLOW) &&
!/^\d+$/.test(ctx.value.workflowVersionId)
) {
ctx.issues.push({
code: "custom",
input: ctx.value.workflowVersionId,
message: t("aiAgent.workflowVersionRequired"),
path: ["workflowVersionId"],
});
}
}), }),
[t], [t],
); );
@@ -266,19 +236,6 @@ function EditDialogBody({
[schema], [schema],
); );
const serviceModeOptions = useMemo(() => getServiceModeOptions(t), [t]); const serviceModeOptions = useMemo(() => getServiceModeOptions(t), [t]);
const runtimeModeOptions = useMemo(
() => [
{
value: String(AI_AGENT_RUNTIME_MODE_BUILTIN_GRAPH),
label: t("aiAgent.runtimeBuiltinGraph"),
},
{
value: String(AI_AGENT_RUNTIME_MODE_WORKFLOW),
label: t("aiAgent.runtimeWorkflow"),
},
],
[t],
);
const handoffModeOptions = useMemo(() => getHandoffModeOptions(t), [t]); const handoffModeOptions = useMemo(() => getHandoffModeOptions(t), [t]);
const fallbackModeOptions = useMemo(() => getFallbackModeOptions(t), [t]); const fallbackModeOptions = useMemo(() => getFallbackModeOptions(t), [t]);
const form = useForm<EditForm>({ const form = useForm<EditForm>({
@@ -305,7 +262,6 @@ function EditDialogBody({
const [directToolToAdd, setDirectToolToAdd] = useState(""); const [directToolToAdd, setDirectToolToAdd] = useState("");
const [graphToolToAdd, setGraphToolToAdd] = useState(""); const [graphToolToAdd, setGraphToolToAdd] = useState("");
const [aiConfigs, setAIConfigs] = useState<AIConfig[]>([]); const [aiConfigs, setAIConfigs] = useState<AIConfig[]>([]);
const [workflowVersions, setWorkflowVersions] = useState<AIWorkflowVersion[]>([]);
const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]); const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);
const [agentTeams, setAgentTeams] = useState<AdminAgentTeam[]>([]); const [agentTeams, setAgentTeams] = useState<AdminAgentTeam[]>([]);
const [skills, setSkills] = useState<SkillDefinition[]>([]); const [skills, setSkills] = useState<SkillDefinition[]>([]);
@@ -390,23 +346,6 @@ function EditDialogBody({
void loadAgentTeams(); void loadAgentTeams();
}, [t]); }, [t]);
useEffect(() => {
async function loadWorkflowVersions() {
try {
const data = await fetchAIWorkflowVersions({
page: 1,
limit: 1000,
});
setWorkflowVersions(data.results ?? []);
} catch (error) {
toast.error(
error instanceof Error ? error.message : t("aiAgent.loadWorkflowVersionsFailed"),
);
}
}
void loadWorkflowVersions();
}, [t]);
useEffect(() => { useEffect(() => {
async function loadKnowledgeBases() { async function loadKnowledgeBases() {
try { try {
@@ -497,15 +436,6 @@ function EditDialogBody({
[agentTeams], [agentTeams],
); );
const workflowVersionOptions = useMemo(
() =>
workflowVersions.map((item) => ({
value: String(item.id),
label: `Workflow #${item.workflowId} · v${item.version}`,
})),
[workflowVersions],
);
const knowledgeOptions = useMemo( const knowledgeOptions = useMemo(
() => () =>
knowledgeBases.map((item) => ({ knowledgeBases.map((item) => ({
@@ -626,7 +556,6 @@ function EditDialogBody({
); );
const handoffMode = watch("handoffMode"); const handoffMode = watch("handoffMode");
const runtimeMode = watch("runtimeMode");
const selectedHandoffModeLabel = const selectedHandoffModeLabel =
handoffModeOptions.find((item) => item.value === handoffMode)?.label ?? handoffModeOptions.find((item) => item.value === handoffMode)?.label ??
t("aiAgent.notSelected"); t("aiAgent.notSelected");
@@ -818,56 +747,6 @@ function EditDialogBody({
</Field> </Field>
</div> </div>
<div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
<Field data-invalid={!!errors.runtimeMode}>
<FieldLabel>{t("aiAgent.runtimeMode")}</FieldLabel>
<FieldContent>
<Controller
control={control}
name="runtimeMode"
render={({ field }) => (
<OptionCombobox
value={field.value}
options={runtimeModeOptions}
placeholder={t("aiAgent.selectRuntimeMode")}
searchPlaceholder={t("aiAgent.searchRuntimeMode")}
emptyText={t("aiAgent.emptyRuntimeMode")}
onChange={field.onChange}
/>
)}
/>
<FieldError errors={[errors.runtimeMode]} />
</FieldContent>
</Field>
<Field
data-invalid={
runtimeMode === String(AI_AGENT_RUNTIME_MODE_WORKFLOW) &&
!!errors.workflowVersionId
}
>
<FieldLabel>{t("aiAgent.workflowVersion")}</FieldLabel>
<FieldContent>
<Controller
control={control}
name="workflowVersionId"
render={({ field }) => (
<OptionCombobox
value={field.value}
options={workflowVersionOptions}
placeholder={t("aiAgent.selectWorkflowVersion")}
searchPlaceholder={t("aiAgent.searchWorkflowVersion")}
emptyText={t("aiAgent.emptyWorkflowVersion")}
disabled={runtimeMode !== String(AI_AGENT_RUNTIME_MODE_WORKFLOW)}
onChange={field.onChange}
/>
)}
/>
<FieldError errors={[errors.workflowVersionId]} />
</FieldContent>
</Field>
</div>
<Field data-invalid={!!errors.description}> <Field data-invalid={!!errors.description}>
<FieldLabel htmlFor="ai-agent-description">{t("aiAgent.description")}</FieldLabel> <FieldLabel htmlFor="ai-agent-description">{t("aiAgent.description")}</FieldLabel>
<FieldContent> <FieldContent>
+11 -1
View File
@@ -1,6 +1,7 @@
"use client"; "use client";
import { BotMessageSquareIcon, PowerIcon } from "lucide-react"; import { BotMessageSquareIcon, GitBranchIcon, PowerIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useMemo } from "react"; import { useMemo } from "react";
import { import {
@@ -62,6 +63,7 @@ function getNextStatus(item: AIAgent) {
export default function DashboardAIAgentsPage() { export default function DashboardAIAgentsPage() {
const t = useI18n(); const t = useI18n();
const router = useRouter();
const statusOptions = useMemo(() => getStatusOptions(t), [t]); const statusOptions = useMemo(() => getStatusOptions(t), [t]);
const filters = useMemo<DashboardCrudFilter[]>( const filters = useMemo<DashboardCrudFilter[]>(
@@ -235,6 +237,14 @@ export default function DashboardAIAgentsPage() {
updateItem={(item, payload) => updateAIAgent({ id: item.id, ...payload })} updateItem={(item, payload) => updateAIAgent({ id: item.id, ...payload })}
deleteItem={(item) => deleteAIAgent(item.id)} deleteItem={(item) => deleteAIAgent(item.id)}
rowActions={[ rowActions={[
{
key: "workflow",
icon: <GitBranchIcon />,
label: t("aiAgent.workflow"),
run: ({ item }) => {
router.push(`/dashboard/ai-agents/workflow?agentId=${item.id}`);
},
},
createDashboardStatusToggleAction<AIAgent, number>({ createDashboardStatusToggleAction<AIAgent, number>({
icon: <PowerIcon />, icon: <PowerIcon />,
label: (item) => label: (item) =>
@@ -1,7 +1,8 @@
"use client" "use client"
import { useCallback, useEffect, useMemo, useState } from "react" import { useCallback, useEffect, useMemo, useState } from "react"
import { CheckCircle2Icon, GitBranchIcon, SaveIcon, SendIcon } from "lucide-react" import { useRouter } from "next/navigation"
import { ArrowLeftIcon, CheckCircle2Icon, GitBranchIcon, SaveIcon, SendIcon } from "lucide-react"
import { toast } from "sonner" import { toast } from "sonner"
import { Badge } from "@/components/ui/badge" import { Badge } from "@/components/ui/badge"
@@ -10,18 +11,19 @@ import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label" import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea" import { Textarea } from "@/components/ui/textarea"
import { import {
createAIWorkflow, fetchAIAgent,
fetchAIAgentWorkflow,
fetchAIWorkflowNodeSpecs, fetchAIWorkflowNodeSpecs,
fetchAIWorkflows, publishAIAgentWorkflow,
publishAIWorkflow, saveAIAgentWorkflow,
updateAIWorkflow,
validateAIWorkflow, validateAIWorkflow,
type AIAgent,
type AIWorkflow, type AIWorkflow,
type AIWorkflowDefinition, type AIWorkflowDefinition,
type AIWorkflowNodeSpec, type AIWorkflowNodeSpec,
type AIWorkflowValidationResult, type AIWorkflowValidationResult,
} from "@/lib/api/admin" } from "@/lib/api/admin"
import { WorkflowEditor } from "./_components/workflow-editor" import { WorkflowEditor } from "../../ai-workflows/_components/workflow-editor"
const emptyDefinition: AIWorkflowDefinition = { const emptyDefinition: AIWorkflowDefinition = {
schemaVersion: 1, schemaVersion: 1,
@@ -45,73 +47,68 @@ const emptyDefinition: AIWorkflowDefinition = {
edges: [{ id: "edge_start_end", source: "start_1", target: "end_1" }], edges: [{ id: "edge_start_end", source: "start_1", target: "end_1" }],
} }
export default function DashboardAIWorkflowsPage() { function readAgentIdFromLocation() {
const [workflows, setWorkflows] = useState<AIWorkflow[]>([]) if (typeof window === "undefined") {
return 0
}
return Number(new URLSearchParams(window.location.search).get("agentId"))
}
export default function DashboardAIAgentWorkflowPage() {
const router = useRouter()
const [agentId] = useState(() => readAgentIdFromLocation())
const [agent, setAgent] = useState<AIAgent | null>(null)
const [workflow, setWorkflow] = useState<AIWorkflow | null>(null)
const [nodeSpecs, setNodeSpecs] = useState<AIWorkflowNodeSpec[]>([]) const [nodeSpecs, setNodeSpecs] = useState<AIWorkflowNodeSpec[]>([])
const [selected, setSelected] = useState<AIWorkflow | null>(null) const [name, setName] = useState("")
const [name, setName] = useState("Customer support flow")
const [description, setDescription] = useState("") const [description, setDescription] = useState("")
const [ownerId, setOwnerId] = useState("1")
const [definition, setDefinition] = useState<AIWorkflowDefinition>(emptyDefinition) const [definition, setDefinition] = useState<AIWorkflowDefinition>(emptyDefinition)
const [validation, setValidation] = useState<AIWorkflowValidationResult | null>(null) const [validation, setValidation] = useState<AIWorkflowValidationResult | null>(null)
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const editorKey = useMemo( const editorKey = useMemo(
() => `${selected?.id ?? "new"}-${selected?.updatedAt ?? ""}`, () => `${workflow?.id ?? "new"}-${workflow?.updatedAt ?? ""}`,
[selected?.id, selected?.updatedAt] [workflow?.id, workflow?.updatedAt]
) )
const loadData = useCallback(async () => { const loadData = useCallback(async () => {
const [workflowPage, specs] = await Promise.all([ if (!Number.isFinite(agentId) || agentId <= 0) {
fetchAIWorkflows({ page: 1, limit: 50, status: 0 }), return
}
const [agentDetail, workflowDetail, specs] = await Promise.all([
fetchAIAgent(agentId),
fetchAIAgentWorkflow(agentId),
fetchAIWorkflowNodeSpecs(), fetchAIWorkflowNodeSpecs(),
]) ])
setWorkflows(workflowPage?.results ?? []) setAgent(agentDetail)
setWorkflow(workflowDetail)
setNodeSpecs(specs ?? []) setNodeSpecs(specs ?? [])
}, []) setName(workflowDetail.name || `${agentDetail.name} 会话流程`)
setDescription(workflowDetail.description || "")
setDefinition(workflowDetail.draftDefinition ?? emptyDefinition)
setValidation(null)
}, [agentId])
useEffect(() => { useEffect(() => {
void loadData().catch((error) => { void loadData().catch((error) => {
toast.error(error instanceof Error ? error.message : "Failed to load workflows") toast.error(error instanceof Error ? error.message : "Failed to load workflow")
}) })
}, [loadData]) }, [loadData])
const selectWorkflow = (workflow: AIWorkflow) => {
setSelected(workflow)
setName(workflow.name)
setDescription(workflow.description)
setOwnerId(String(workflow.ownerId || 1))
setDefinition(workflow.draftDefinition ?? emptyDefinition)
setValidation(null)
}
const createNew = () => {
setSelected(null)
setName("Customer support flow")
setDescription("")
setOwnerId("1")
setDefinition(emptyDefinition)
setValidation(null)
}
const saveDraft = async () => { const saveDraft = async () => {
if (!Number.isFinite(agentId) || agentId <= 0) {
toast.error("Invalid AI Agent.")
return
}
setLoading(true) setLoading(true)
try { try {
const payload = { const saved = await saveAIAgentWorkflow({
agentId,
name, name,
description, description,
ownerType: "ai_agent",
ownerId: Number(ownerId) || 0,
definition, definition,
} })
if (selected) { setWorkflow(saved)
await updateAIWorkflow({ id: selected.id, ...payload }) toast.success("Draft saved")
toast.success("Draft saved")
} else {
const created = await createAIWorkflow(payload)
setSelected(created)
toast.success("Workflow created")
}
await loadData()
} catch (error) { } catch (error) {
toast.error(error instanceof Error ? error.message : "Failed to save workflow") toast.error(error instanceof Error ? error.message : "Failed to save workflow")
} finally { } finally {
@@ -135,13 +132,20 @@ export default function DashboardAIWorkflowsPage() {
} }
const publish = async () => { const publish = async () => {
if (!selected) { if (!Number.isFinite(agentId) || agentId <= 0) {
toast.error("Save the workflow before publishing.") toast.error("Invalid AI Agent.")
return return
} }
setLoading(true) setLoading(true)
try { try {
const version = await publishAIWorkflow(selected.id, definition) const saved = await saveAIAgentWorkflow({
agentId,
name,
description,
definition,
})
setWorkflow(saved)
const version = await publishAIAgentWorkflow(agentId, definition)
toast.success(`Published version ${version.version}`) toast.success(`Published version ${version.version}`)
await loadData() await loadData()
} catch (error) { } catch (error) {
@@ -154,16 +158,20 @@ export default function DashboardAIWorkflowsPage() {
return ( return (
<div className="flex h-[calc(100vh-var(--header-height))] min-h-0 flex-col overflow-hidden"> <div className="flex h-[calc(100vh-var(--header-height))] min-h-0 flex-col overflow-hidden">
<div className="flex shrink-0 items-center justify-between border-b px-5 py-3"> <div className="flex shrink-0 items-center justify-between border-b px-5 py-3">
<div className="min-w-0"> <div className="flex min-w-0 items-center gap-3">
<h1 className="truncate text-base font-semibold">AI Workflows</h1> <Button variant="outline" size="icon-sm" onClick={() => router.push("/dashboard/ai-agents")}>
<p className="mt-1 text-sm text-muted-foreground"> <ArrowLeftIcon />
Edit and publish customer-service conversation flows. </Button>
</p> <div className="min-w-0">
<h1 className="truncate text-base font-semibold">
{agent ? `${agent.name} · 会话流程` : "AI Agent Workflow"}
</h1>
<p className="mt-1 text-sm text-muted-foreground">
Edit and publish this Agent&apos;s customer-service conversation flow.
</p>
</div>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Button variant="outline" onClick={createNew}>
New
</Button>
<Button variant="outline" disabled={loading} onClick={runValidation}> <Button variant="outline" disabled={loading} onClick={runValidation}>
<CheckCircle2Icon className="size-4" /> <CheckCircle2Icon className="size-4" />
Validate Validate
@@ -172,7 +180,7 @@ export default function DashboardAIWorkflowsPage() {
<SaveIcon className="size-4" /> <SaveIcon className="size-4" />
Save draft Save draft
</Button> </Button>
<Button disabled={loading || !selected} onClick={publish}> <Button disabled={loading} onClick={publish}>
<SendIcon className="size-4" /> <SendIcon className="size-4" />
Publish Publish
</Button> </Button>
@@ -189,16 +197,6 @@ export default function DashboardAIWorkflowsPage() {
onChange={(event) => setName(event.target.value)} onChange={(event) => setName(event.target.value)}
/> />
</div> </div>
<div className="space-y-2">
<Label htmlFor="workflow-owner">AI Agent ID</Label>
<Input
id="workflow-owner"
type="number"
min={1}
value={ownerId}
onChange={(event) => setOwnerId(event.target.value)}
/>
</div>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="workflow-description">Description</Label> <Label htmlFor="workflow-description">Description</Label>
<Textarea <Textarea
@@ -209,41 +207,25 @@ export default function DashboardAIWorkflowsPage() {
/> />
</div> </div>
</div> </div>
<div className="p-3"> <div className="space-y-3 p-4 text-sm">
<div className="mb-2 text-sm font-medium">Workflows</div> <div className="flex items-center justify-between gap-3">
<div className="space-y-2"> <span className="text-muted-foreground">Agent</span>
{workflows.map((workflow) => ( <span className="truncate font-medium">{agent?.name ?? `#${agentId || "-"}`}</span>
<button </div>
key={workflow.id} <div className="flex items-center justify-between gap-3">
type="button" <span className="text-muted-foreground">Published</span>
onClick={() => selectWorkflow(workflow)} {workflow?.publishedVersionId ? (
className={`w-full rounded-md border px-3 py-2 text-left text-sm hover:bg-muted ${ <Badge variant="secondary">Version linked</Badge>
selected?.id === workflow.id ? "border-primary bg-primary/5" : "bg-background" ) : (
}`} <span className="text-muted-foreground">Not published</span>
> )}
<div className="flex items-center justify-between gap-2">
<span className="truncate font-medium">{workflow.name}</span>
{workflow.publishedVersionId ? (
<Badge variant="secondary">Published</Badge>
) : null}
</div>
<div className="mt-1 truncate text-xs text-muted-foreground">
Agent #{workflow.ownerId}
</div>
</button>
))}
{workflows.length === 0 ? (
<div className="rounded-md border border-dashed p-4 text-sm text-muted-foreground">
No workflows yet.
</div>
) : null}
</div> </div>
</div> </div>
</aside> </aside>
<main className="flex min-h-0 flex-col overflow-hidden"> <main className="flex min-h-0 flex-col overflow-hidden">
<div className="flex shrink-0 items-center gap-2 border-b px-4 py-2 text-sm"> <div className="flex shrink-0 items-center gap-2 border-b px-4 py-2 text-sm">
<GitBranchIcon className="size-4 text-muted-foreground" /> <GitBranchIcon className="size-4 text-muted-foreground" />
<span className="font-medium">{selected ? selected.name : "Unsaved workflow"}</span> <span className="font-medium">{name || "Conversation workflow"}</span>
{validation ? ( {validation ? (
<Badge variant={validation.valid ? "default" : "destructive"}> <Badge variant={validation.valid ? "default" : "destructive"}>
{validation.valid ? "Backend valid" : `${validation.errors.length} backend errors`} {validation.valid ? "Backend valid" : `${validation.errors.length} backend errors`}
+10 -52
View File
@@ -275,8 +275,6 @@ export type CreateAIAgentPayload = {
arguments?: Record<string, string> arguments?: Record<string, string>
}[] }[]
graphTools: string[] graphTools: string[]
runtimeMode: number
workflowVersionId: number
} }
export type UpdateAIAgentPayload = CreateAIAgentPayload & { export type UpdateAIAgentPayload = CreateAIAgentPayload & {
@@ -312,8 +310,7 @@ export type AIWorkflow = {
id: number id: number
name: string name: string
description: string description: string
ownerType: string agentId: number
ownerId: number
status: number status: number
draftDefinition: AIWorkflowDefinition draftDefinition: AIWorkflowDefinition
publishedVersionId: number publishedVersionId: number
@@ -358,15 +355,10 @@ export type AIWorkflowValidationResult = {
export type CreateAIWorkflowPayload = { export type CreateAIWorkflowPayload = {
name: string name: string
description: string description: string
ownerType: string agentId: number
ownerId: number
definition: AIWorkflowDefinition definition: AIWorkflowDefinition
} }
export type UpdateAIWorkflowPayload = CreateAIWorkflowPayload & {
id: number
}
export type CreateAdminQuickReplyPayload = { export type CreateAdminQuickReplyPayload = {
groupName: string groupName: string
title: string title: string
@@ -781,69 +773,35 @@ export function updateAIAgentStatus(id: number, status: number) {
}) })
} }
export function fetchAIWorkflows( export function fetchAIAgentWorkflow(agentId: number) {
query?: Record<string, string | number | undefined> return request<AIWorkflow>(`/api/dashboard/ai-agent/${agentId}/workflow`)
) {
return request<PageResult<AIWorkflow>>(
`/api/dashboard/ai-workflow/list${toQueryString(query)}`
)
} }
export function fetchAIWorkflow(id: number) { export function saveAIAgentWorkflow(payload: CreateAIWorkflowPayload) {
return request<AIWorkflow>(`/api/dashboard/ai-workflow/${id}`) return request<AIWorkflow>("/api/dashboard/ai-agent/workflow/save", {
}
export function createAIWorkflow(payload: CreateAIWorkflowPayload) {
return request<AIWorkflow>("/api/dashboard/ai-workflow/create", {
method: "POST", method: "POST",
body: JSON.stringify(payload), body: JSON.stringify(payload),
}) })
} }
export function updateAIWorkflow(payload: UpdateAIWorkflowPayload) {
return request<void>("/api/dashboard/ai-workflow/update", {
method: "POST",
body: JSON.stringify(payload),
})
}
export function deleteAIWorkflow(id: number) {
return request<void>("/api/dashboard/ai-workflow/delete", {
method: "POST",
body: JSON.stringify({ id }),
})
}
export function fetchAIWorkflowNodeSpecs() { export function fetchAIWorkflowNodeSpecs() {
return request<AIWorkflowNodeSpec[]>("/api/dashboard/ai-workflow/node-spec/list") return request<AIWorkflowNodeSpec[]>("/api/dashboard/ai-workflow/node-spec/list")
} }
export function validateAIWorkflow(definition: AIWorkflowDefinition) { export function validateAIWorkflow(definition: AIWorkflowDefinition) {
return request<AIWorkflowValidationResult>("/api/dashboard/ai-workflow/validate", { return request<AIWorkflowValidationResult>("/api/dashboard/ai-agent/workflow/validate", {
method: "POST", method: "POST",
body: JSON.stringify({ definition }), body: JSON.stringify({ definition }),
}) })
} }
export function publishAIWorkflow(workflowId: number, definition: AIWorkflowDefinition) { export function publishAIAgentWorkflow(agentId: number, definition: AIWorkflowDefinition) {
return request<AIWorkflowVersion>("/api/dashboard/ai-workflow/publish", { return request<AIWorkflowVersion>("/api/dashboard/ai-agent/workflow/publish", {
method: "POST", method: "POST",
body: JSON.stringify({ workflowId, definition }), body: JSON.stringify({ agentId, definition }),
}) })
} }
export function fetchAIWorkflowVersions(
query?: Record<string, string | number | undefined>
) {
return request<PageResult<AIWorkflowVersion>>(
`/api/dashboard/ai-workflow/version/list${toQueryString(query)}`
)
}
export function fetchAIWorkflowVersion(id: number) {
return request<AIWorkflowVersion>(`/api/dashboard/ai-workflow/version/${id}`)
}
export function fetchUsers(query?: Record<string, string | number | undefined>) { export function fetchUsers(query?: Record<string, string | number | undefined>) {
return request<PageResult<AdminUser>>( return request<PageResult<AdminUser>>(
`/api/dashboard/user/list${toQueryString(query)}` `/api/dashboard/user/list${toQueryString(query)}`
-7
View File
@@ -14,7 +14,6 @@ import {
TagsIcon, TagsIcon,
UserCogIcon, UserCogIcon,
UsersIcon, UsersIcon,
WorkflowIcon,
} from "lucide-react"; } from "lucide-react";
import type { ReactNode } from "react"; import type { ReactNode } from "react";
@@ -194,12 +193,6 @@ export const dashboardNavSections: DashboardNavSectionConfig[] = [
icon: <MessageSquareMoreIcon />, icon: <MessageSquareMoreIcon />,
requiredPermission: "aiAgent.view", requiredPermission: "aiAgent.view",
}, },
{
titleKey: "nav.aiWorkflows",
url: "/dashboard/ai-workflows",
icon: <WorkflowIcon />,
requiredPermission: "aiAgent.view",
},
{ {
titleKey: "nav.skillDefinition", titleKey: "nav.skillDefinition",
url: "/dashboard/skill-definition", url: "/dashboard/skill-definition",
+1 -13
View File
@@ -1024,6 +1024,7 @@
"moreActions": "More actions for {name}", "moreActions": "More actions for {name}",
"processing": "Working...", "processing": "Working...",
"stop": "Disable", "stop": "Disable",
"workflow": "Workflow",
"delete": "Delete", "delete": "Delete",
"loadingRows": "Loading AI agents...", "loadingRows": "Loading AI agents...",
"emptyRows": "No AI agents yet", "emptyRows": "No AI agents yet",
@@ -1038,8 +1039,6 @@
"nameRequired": "Enter a name.", "nameRequired": "Enter a name.",
"aiConfigRequired": "Select an AI config.", "aiConfigRequired": "Select an AI config.",
"serviceModeRequired": "Select a service mode.", "serviceModeRequired": "Select a service mode.",
"runtimeModeRequired": "Select a runtime mode.",
"workflowVersionRequired": "Select a published workflow version.",
"replyTimeoutInvalid": "Reply timeout must be an integer greater than or equal to 0.", "replyTimeoutInvalid": "Reply timeout must be an integer greater than or equal to 0.",
"handoffModeRequired": "Select a human handoff mode.", "handoffModeRequired": "Select a human handoff mode.",
"fallbackModeRequired": "Select a fallback strategy.", "fallbackModeRequired": "Select a fallback strategy.",
@@ -1048,7 +1047,6 @@
"loadTeamsFailed": "Could not load support teams.", "loadTeamsFailed": "Could not load support teams.",
"loadKnowledgeFailed": "Could not load knowledge bases.", "loadKnowledgeFailed": "Could not load knowledge bases.",
"loadSkillsFailed": "Could not load skills.", "loadSkillsFailed": "Could not load skills.",
"loadWorkflowVersionsFailed": "Could not load AI workflow versions.",
"loadDirectToolsFailed": "Could not load Direct Tools.", "loadDirectToolsFailed": "Could not load Direct Tools.",
"builtinTools": "Built-in tools", "builtinTools": "Built-in tools",
"ungrouped": "Ungrouped", "ungrouped": "Ungrouped",
@@ -1068,16 +1066,6 @@
"selectServiceMode": "Select service mode", "selectServiceMode": "Select service mode",
"searchServiceMode": "Search service modes", "searchServiceMode": "Search service modes",
"emptyServiceMode": "No service modes found", "emptyServiceMode": "No service modes found",
"runtimeMode": "Runtime Mode",
"runtimeBuiltinGraph": "Built-in Graph Tools",
"runtimeWorkflow": "Published AI Workflow",
"selectRuntimeMode": "Select runtime mode",
"searchRuntimeMode": "Search runtime modes",
"emptyRuntimeMode": "No runtime modes found",
"workflowVersion": "Workflow Version",
"selectWorkflowVersion": "Select published workflow version",
"searchWorkflowVersion": "Search workflow versions",
"emptyWorkflowVersion": "No published workflow versions available",
"description": "Description", "description": "Description",
"welcomeMessage": "Welcome Message", "welcomeMessage": "Welcome Message",
"systemPrompt": "System Prompt", "systemPrompt": "System Prompt",
+1 -13
View File
@@ -1024,6 +1024,7 @@
"moreActions": "更多操作 {name}", "moreActions": "更多操作 {name}",
"processing": "处理中...", "processing": "处理中...",
"stop": "停用", "stop": "停用",
"workflow": "会话流程",
"delete": "删除", "delete": "删除",
"loadingRows": "正在加载 AI Agent...", "loadingRows": "正在加载 AI Agent...",
"emptyRows": "暂无 AI Agent", "emptyRows": "暂无 AI Agent",
@@ -1038,8 +1039,6 @@
"nameRequired": "名称不能为空", "nameRequired": "名称不能为空",
"aiConfigRequired": "请选择 AI 配置", "aiConfigRequired": "请选择 AI 配置",
"serviceModeRequired": "请选择服务模式", "serviceModeRequired": "请选择服务模式",
"runtimeModeRequired": "请选择运行模式",
"workflowVersionRequired": "请选择已发布的流程版本",
"replyTimeoutInvalid": "回复超时秒数必须是大于等于 0 的整数", "replyTimeoutInvalid": "回复超时秒数必须是大于等于 0 的整数",
"handoffModeRequired": "请选择转人工模式", "handoffModeRequired": "请选择转人工模式",
"fallbackModeRequired": "请选择兜底策略", "fallbackModeRequired": "请选择兜底策略",
@@ -1048,7 +1047,6 @@
"loadTeamsFailed": "加载客服组失败", "loadTeamsFailed": "加载客服组失败",
"loadKnowledgeFailed": "加载知识库失败", "loadKnowledgeFailed": "加载知识库失败",
"loadSkillsFailed": "加载 Skills 失败", "loadSkillsFailed": "加载 Skills 失败",
"loadWorkflowVersionsFailed": "加载 AI 流程版本失败",
"loadDirectToolsFailed": "加载 Direct Tools 失败", "loadDirectToolsFailed": "加载 Direct Tools 失败",
"builtinTools": "内置工具", "builtinTools": "内置工具",
"ungrouped": "未分组", "ungrouped": "未分组",
@@ -1068,16 +1066,6 @@
"selectServiceMode": "请选择服务模式", "selectServiceMode": "请选择服务模式",
"searchServiceMode": "搜索服务模式", "searchServiceMode": "搜索服务模式",
"emptyServiceMode": "未找到服务模式", "emptyServiceMode": "未找到服务模式",
"runtimeMode": "运行模式",
"runtimeBuiltinGraph": "内置流程工具",
"runtimeWorkflow": "已发布 AI 流程",
"selectRuntimeMode": "请选择运行模式",
"searchRuntimeMode": "搜索运行模式",
"emptyRuntimeMode": "未找到运行模式",
"workflowVersion": "流程版本",
"selectWorkflowVersion": "请选择已发布流程版本",
"searchWorkflowVersion": "搜索流程版本",
"emptyWorkflowVersion": "没有可用的已发布流程版本",
"description": "描述", "description": "描述",
"welcomeMessage": "欢迎语", "welcomeMessage": "欢迎语",
"systemPrompt": "系统提示词", "systemPrompt": "系统提示词",