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