feat: enhance condition node functionality with branches and validation
- Introduced WorkflowConditionBranch and WorkflowNodeConfig types to manage condition branches in nodes. - Updated NodeConfigPanel and ConditionNodePanel components to support adding, editing, and deleting branches. - Implemented validation for condition nodes to ensure at least one branch exists and that default branches are correctly configured. - Modified workflow-utils to handle condition branches and updated toApiDefinition and fromApiDefinition functions to maintain branch integrity during serialization. - Removed edge condition handling from WorkflowEditor and related components, simplifying edge management. - Added tests to ensure condition branches are preserved in API definitions.
This commit is contained in:
@@ -86,6 +86,8 @@ type workflowCheckPoint struct {
|
|||||||
|
|
||||||
type branchDecision struct {
|
type branchDecision struct {
|
||||||
SelectedEdgeID string `json:"selectedEdgeId,omitempty"`
|
SelectedEdgeID string `json:"selectedEdgeId,omitempty"`
|
||||||
|
SelectedBranchID string `json:"selectedBranchId,omitempty"`
|
||||||
|
SelectedBranchName string `json:"selectedBranchName,omitempty"`
|
||||||
SelectedTargetNodeID string `json:"selectedTargetNodeId,omitempty"`
|
SelectedTargetNodeID string `json:"selectedTargetNodeId,omitempty"`
|
||||||
Reason string `json:"reason"`
|
Reason string `json:"reason"`
|
||||||
Evaluations []conditionEvaluation `json:"evaluations,omitempty"`
|
Evaluations []conditionEvaluation `json:"evaluations,omitempty"`
|
||||||
@@ -93,6 +95,8 @@ type branchDecision struct {
|
|||||||
|
|
||||||
type conditionEvaluation struct {
|
type conditionEvaluation struct {
|
||||||
EdgeID string `json:"edgeId"`
|
EdgeID string `json:"edgeId"`
|
||||||
|
BranchID string `json:"branchId,omitempty"`
|
||||||
|
BranchName string `json:"branchName,omitempty"`
|
||||||
TargetNodeID string `json:"targetNodeId"`
|
TargetNodeID string `json:"targetNodeId"`
|
||||||
SourceNodeID string `json:"sourceNodeId,omitempty"`
|
SourceNodeID string `json:"sourceNodeId,omitempty"`
|
||||||
SourceField string `json:"sourceField,omitempty"`
|
SourceField string `json:"sourceField,omitempty"`
|
||||||
@@ -588,53 +592,69 @@ func (s *runState) nextNodeID(sourceNodeID string) (string, bool, error) {
|
|||||||
if len(edges) == 0 {
|
if len(edges) == 0 {
|
||||||
return "", false, nil
|
return "", false, nil
|
||||||
}
|
}
|
||||||
|
node := s.nodesByID[sourceNodeID]
|
||||||
|
if strings.TrimSpace(node.Type) != workflowregistry.NodeTypeCondition {
|
||||||
|
return strings.TrimSpace(edges[0].Target), true, nil
|
||||||
|
}
|
||||||
|
config := dsl.ConditionConfig{}
|
||||||
|
if len(node.Config) > 0 {
|
||||||
|
if err := json.Unmarshal(node.Config, &config); err != nil {
|
||||||
|
return "", false, fmt.Errorf("invalid condition node config: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
evaluations := make([]conditionEvaluation, 0)
|
evaluations := make([]conditionEvaluation, 0)
|
||||||
for _, edge := range edges {
|
for _, branch := range config.Branches {
|
||||||
if edge.Condition == nil {
|
if branch.Default {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
matched, evaluation, err := s.evaluateCondition(edge)
|
matched, evaluation, err := s.evaluateConditionBranch(sourceNodeID, branch)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", false, err
|
return "", false, err
|
||||||
}
|
}
|
||||||
evaluations = append(evaluations, evaluation)
|
evaluations = append(evaluations, evaluation)
|
||||||
if matched {
|
if matched {
|
||||||
|
targetNodeID := strings.TrimSpace(branch.TargetNodeID)
|
||||||
s.branchDecisions[sourceNodeID] = branchDecision{
|
s.branchDecisions[sourceNodeID] = branchDecision{
|
||||||
SelectedEdgeID: strings.TrimSpace(edge.ID),
|
SelectedEdgeID: s.edgeIDForTarget(sourceNodeID, targetNodeID),
|
||||||
SelectedTargetNodeID: strings.TrimSpace(edge.Target),
|
SelectedBranchID: strings.TrimSpace(branch.ID),
|
||||||
Reason: "conditional edge matched",
|
SelectedBranchName: strings.TrimSpace(branch.Name),
|
||||||
|
SelectedTargetNodeID: targetNodeID,
|
||||||
|
Reason: "condition branch matched",
|
||||||
Evaluations: evaluations,
|
Evaluations: evaluations,
|
||||||
}
|
}
|
||||||
return strings.TrimSpace(edge.Target), true, nil
|
return targetNodeID, true, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, edge := range edges {
|
for _, branch := range config.Branches {
|
||||||
if edge.Condition == nil {
|
if !branch.Default {
|
||||||
if len(evaluations) > 0 {
|
continue
|
||||||
s.branchDecisions[sourceNodeID] = branchDecision{
|
|
||||||
SelectedEdgeID: strings.TrimSpace(edge.ID),
|
|
||||||
SelectedTargetNodeID: strings.TrimSpace(edge.Target),
|
|
||||||
Reason: "no conditional edge matched; selected default edge",
|
|
||||||
Evaluations: evaluations,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return strings.TrimSpace(edge.Target), true, nil
|
|
||||||
}
|
}
|
||||||
}
|
targetNodeID := strings.TrimSpace(branch.TargetNodeID)
|
||||||
if len(evaluations) > 0 {
|
|
||||||
s.branchDecisions[sourceNodeID] = branchDecision{
|
s.branchDecisions[sourceNodeID] = branchDecision{
|
||||||
Reason: "no conditional edge matched and no default edge exists",
|
SelectedEdgeID: s.edgeIDForTarget(sourceNodeID, targetNodeID),
|
||||||
Evaluations: evaluations,
|
SelectedBranchID: strings.TrimSpace(branch.ID),
|
||||||
|
SelectedBranchName: strings.TrimSpace(branch.Name),
|
||||||
|
SelectedTargetNodeID: targetNodeID,
|
||||||
|
Reason: "no condition branch matched; selected default branch",
|
||||||
|
Evaluations: evaluations,
|
||||||
}
|
}
|
||||||
|
return targetNodeID, true, nil
|
||||||
|
}
|
||||||
|
s.branchDecisions[sourceNodeID] = branchDecision{
|
||||||
|
Reason: "no condition branch matched and no default branch exists",
|
||||||
|
Evaluations: evaluations,
|
||||||
}
|
}
|
||||||
return "", false, nil
|
return "", false, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *runState) evaluateCondition(edge dsl.Edge) (bool, conditionEvaluation, error) {
|
func (s *runState) evaluateConditionBranch(sourceNodeID string, branch dsl.ConditionBranch) (bool, conditionEvaluation, error) {
|
||||||
condition := edge.Condition
|
condition := branch.Condition
|
||||||
|
targetNodeID := strings.TrimSpace(branch.TargetNodeID)
|
||||||
evaluation := conditionEvaluation{
|
evaluation := conditionEvaluation{
|
||||||
EdgeID: strings.TrimSpace(edge.ID),
|
EdgeID: s.edgeIDForTarget(sourceNodeID, targetNodeID),
|
||||||
TargetNodeID: strings.TrimSpace(edge.Target),
|
BranchID: strings.TrimSpace(branch.ID),
|
||||||
|
BranchName: strings.TrimSpace(branch.Name),
|
||||||
|
TargetNodeID: targetNodeID,
|
||||||
}
|
}
|
||||||
if condition == nil {
|
if condition == nil {
|
||||||
evaluation.Matched = true
|
evaluation.Matched = true
|
||||||
@@ -683,6 +703,15 @@ func (s *runState) evaluateCondition(edge dsl.Edge) (bool, conditionEvaluation,
|
|||||||
return matched, evaluation, nil
|
return matched, evaluation, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *runState) edgeIDForTarget(sourceNodeID string, targetNodeID string) string {
|
||||||
|
for _, edge := range s.outgoing[sourceNodeID] {
|
||||||
|
if strings.TrimSpace(edge.Target) == targetNodeID {
|
||||||
|
return strings.TrimSpace(edge.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
func (s *runState) setNodeVars(nodeID string, values map[string]any) {
|
func (s *runState) setNodeVars(nodeID string, values map[string]any) {
|
||||||
s.vars[nodeID] = values
|
s.vars[nodeID] = values
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package workflow
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -18,7 +19,15 @@ import (
|
|||||||
"gorm.io/gorm/schema"
|
"gorm.io/gorm/schema"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestExecutorRoutesByConditionEdge(t *testing.T) {
|
func mustMarshalWorkflowTestConfig(value any) json.RawMessage {
|
||||||
|
raw, err := json.Marshal(value)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return raw
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecutorRoutesByConditionNodeBranch(t *testing.T) {
|
||||||
executor := NewExecutor()
|
executor := NewExecutor()
|
||||||
result, err := executor.Execute(context.Background(), Input{
|
result, err := executor.Execute(context.Background(), Input{
|
||||||
Definition: conditionalReplyDefinition(),
|
Definition: conditionalReplyDefinition(),
|
||||||
@@ -52,6 +61,7 @@ func TestExecutorConditionNodeTraceExplainsMatchedEdge(t *testing.T) {
|
|||||||
}
|
}
|
||||||
for _, want := range []string{
|
for _, want := range []string{
|
||||||
`"selectedEdgeId":"edge_condition_vip"`,
|
`"selectedEdgeId":"edge_condition_vip"`,
|
||||||
|
`"selectedBranchId":"vip"`,
|
||||||
`"selectedTargetNodeId":"vip_reply"`,
|
`"selectedTargetNodeId":"vip_reply"`,
|
||||||
`"operator":"eq"`,
|
`"operator":"eq"`,
|
||||||
`"leftValue":"vip"`,
|
`"leftValue":"vip"`,
|
||||||
@@ -80,8 +90,9 @@ func TestExecutorConditionNodeTraceExplainsDefaultEdge(t *testing.T) {
|
|||||||
}
|
}
|
||||||
for _, want := range []string{
|
for _, want := range []string{
|
||||||
`"selectedEdgeId":"edge_condition_default"`,
|
`"selectedEdgeId":"edge_condition_default"`,
|
||||||
|
`"selectedBranchId":"default"`,
|
||||||
`"selectedTargetNodeId":"normal_reply"`,
|
`"selectedTargetNodeId":"normal_reply"`,
|
||||||
`"reason":"no conditional edge matched; selected default edge"`,
|
`"reason":"no condition branch matched; selected default branch"`,
|
||||||
`"leftValue":"normal"`,
|
`"leftValue":"normal"`,
|
||||||
`"matched":false`,
|
`"matched":false`,
|
||||||
} {
|
} {
|
||||||
@@ -129,7 +140,7 @@ func TestExecutorHandoffToHumanRunsRealDispatchAction(t *testing.T) {
|
|||||||
if strings.TrimSpace(result.ReplyText) != "" {
|
if strings.TrimSpace(result.ReplyText) != "" {
|
||||||
t.Fatalf("expected workflow handoff node to avoid duplicate reply text, got %q", result.ReplyText)
|
t.Fatalf("expected workflow handoff node to avoid duplicate reply text, got %q", result.ReplyText)
|
||||||
}
|
}
|
||||||
assertPath(t, result.NodePath, []string{"start_1", "handoff_1", "assigned_end"})
|
assertPath(t, result.NodePath, []string{"start_1", "handoff_1", "handoff_route_1", "assigned_end"})
|
||||||
|
|
||||||
current := services.ConversationService.Get(conversation.ID)
|
current := services.ConversationService.Get(conversation.ID)
|
||||||
if current.Status != enums.IMConversationStatusActive {
|
if current.Status != enums.IMConversationStatusActive {
|
||||||
@@ -207,7 +218,7 @@ func TestExecutorAnalyzeConversationOutputsBranchVariables(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("execute workflow: %v", err)
|
t.Fatalf("execute workflow: %v", err)
|
||||||
}
|
}
|
||||||
assertPath(t, result.NodePath, []string{"start_1", "analyze_1", "handoff_end"})
|
assertPath(t, result.NodePath, []string{"start_1", "analyze_1", "analyze_route_1", "handoff_end"})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestExecutorPrepareTicketDraftOutputsDraftVariable(t *testing.T) {
|
func TestExecutorPrepareTicketDraftOutputsDraftVariable(t *testing.T) {
|
||||||
@@ -225,7 +236,7 @@ func TestExecutorPrepareTicketDraftOutputsDraftVariable(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("execute workflow: %v", err)
|
t.Fatalf("execute workflow: %v", err)
|
||||||
}
|
}
|
||||||
assertPath(t, result.NodePath, []string{"start_1", "draft_1", "ready_end"})
|
assertPath(t, result.NodePath, []string{"start_1", "draft_1", "draft_route_1", "ready_end"})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestExecutorLLMReplyUsesAgentFallbackWhenDeclaredKnowledgeIsEmpty(t *testing.T) {
|
func TestExecutorLLMReplyUsesAgentFallbackWhenDeclaredKnowledgeIsEmpty(t *testing.T) {
|
||||||
@@ -314,7 +325,7 @@ func TestExecutorResumeHumanConfirmContinuesWithConfirmedVariable(t *testing.T)
|
|||||||
if result.Interrupted {
|
if result.Interrupted {
|
||||||
t.Fatalf("expected workflow resume to complete")
|
t.Fatalf("expected workflow resume to complete")
|
||||||
}
|
}
|
||||||
assertPath(t, result.NodePath, []string{"end_1"})
|
assertPath(t, result.NodePath, []string{"confirm_route_1", "end_1"})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestExecutorResumeCreatesTicketAfterHumanConfirmation(t *testing.T) {
|
func TestExecutorResumeCreatesTicketAfterHumanConfirmation(t *testing.T) {
|
||||||
@@ -349,7 +360,7 @@ func TestExecutorResumeCreatesTicketAfterHumanConfirmation(t *testing.T) {
|
|||||||
if result.Interrupted {
|
if result.Interrupted {
|
||||||
t.Fatalf("expected workflow to complete")
|
t.Fatalf("expected workflow to complete")
|
||||||
}
|
}
|
||||||
assertPath(t, result.NodePath, []string{"create_ticket_1", "end_1"})
|
assertPath(t, result.NodePath, []string{"confirm_route_1", "create_ticket_1", "end_1"})
|
||||||
|
|
||||||
var ticket models.Ticket
|
var ticket models.Ticket
|
||||||
if err := db.First(&ticket, "conversation_id = ?", conversation.ID).Error; err != nil {
|
if err := db.First(&ticket, "conversation_id = ?", conversation.ID).Error; err != nil {
|
||||||
@@ -403,7 +414,14 @@ func conditionalReplyDefinition() dsl.Definition {
|
|||||||
EntryNodeID: "start_1",
|
EntryNodeID: "start_1",
|
||||||
Nodes: []dsl.Node{
|
Nodes: []dsl.Node{
|
||||||
{ID: "start_1", Type: workflowregistry.NodeTypeStart, Name: "Start"},
|
{ID: "start_1", Type: workflowregistry.NodeTypeStart, Name: "Start"},
|
||||||
{ID: "condition_1", Type: workflowregistry.NodeTypeCondition, Name: "Route"},
|
{ID: "condition_1", Type: workflowregistry.NodeTypeCondition, Name: "Route", Config: mustMarshalWorkflowTestConfig(dsl.ConditionConfig{Branches: []dsl.ConditionBranch{
|
||||||
|
{ID: "vip", Name: "VIP", TargetNodeID: "vip_reply", Condition: &dsl.Condition{
|
||||||
|
Left: &dsl.VariableSelector{NodeID: "start_1", Field: "userMessage"},
|
||||||
|
Operator: "eq",
|
||||||
|
Right: "vip",
|
||||||
|
}},
|
||||||
|
{ID: "default", Name: "Default", TargetNodeID: "normal_reply", Default: true},
|
||||||
|
}})},
|
||||||
{ID: "vip_reply", Type: workflowregistry.NodeTypeLLMReply, Name: "VIP", Config: []byte(`{"staticReply":"VIP reply"}`)},
|
{ID: "vip_reply", Type: workflowregistry.NodeTypeLLMReply, Name: "VIP", Config: []byte(`{"staticReply":"VIP reply"}`)},
|
||||||
{ID: "normal_reply", Type: workflowregistry.NodeTypeLLMReply, Name: "Normal", Config: []byte(`{"staticReply":"Normal reply"}`)},
|
{ID: "normal_reply", Type: workflowregistry.NodeTypeLLMReply, Name: "Normal", Config: []byte(`{"staticReply":"Normal reply"}`)},
|
||||||
{ID: "send_vip", Type: workflowregistry.NodeTypeSendReply, Name: "Send VIP", Inputs: map[string]dsl.VariableSelector{
|
{ID: "send_vip", Type: workflowregistry.NodeTypeSendReply, Name: "Send VIP", Inputs: map[string]dsl.VariableSelector{
|
||||||
@@ -416,16 +434,7 @@ func conditionalReplyDefinition() dsl.Definition {
|
|||||||
},
|
},
|
||||||
Edges: []dsl.Edge{
|
Edges: []dsl.Edge{
|
||||||
{ID: "edge_start_condition", Source: "start_1", Target: "condition_1"},
|
{ID: "edge_start_condition", Source: "start_1", Target: "condition_1"},
|
||||||
{
|
{ID: "edge_condition_vip", Source: "condition_1", Target: "vip_reply"},
|
||||||
ID: "edge_condition_vip",
|
|
||||||
Source: "condition_1",
|
|
||||||
Target: "vip_reply",
|
|
||||||
Condition: &dsl.Condition{
|
|
||||||
Left: &dsl.VariableSelector{NodeID: "start_1", Field: "userMessage"},
|
|
||||||
Operator: "eq",
|
|
||||||
Right: "vip",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{ID: "edge_condition_default", Source: "condition_1", Target: "normal_reply"},
|
{ID: "edge_condition_default", Source: "condition_1", Target: "normal_reply"},
|
||||||
{ID: "edge_vip_send", Source: "vip_reply", Target: "send_vip"},
|
{ID: "edge_vip_send", Source: "vip_reply", Target: "send_vip"},
|
||||||
{ID: "edge_normal_send", Source: "normal_reply", Target: "send_normal"},
|
{ID: "edge_normal_send", Source: "normal_reply", Target: "send_normal"},
|
||||||
@@ -448,6 +457,13 @@ func createTicketWorkflowDefinition() dsl.Definition {
|
|||||||
{ID: "confirm_1", Type: workflowregistry.NodeTypeHumanConfirm, Name: "Confirm", Inputs: map[string]dsl.VariableSelector{
|
{ID: "confirm_1", Type: workflowregistry.NodeTypeHumanConfirm, Name: "Confirm", Inputs: map[string]dsl.VariableSelector{
|
||||||
"prompt": {NodeID: "prompt_1", Field: "replyText"},
|
"prompt": {NodeID: "prompt_1", Field: "replyText"},
|
||||||
}},
|
}},
|
||||||
|
{ID: "confirm_route_1", Type: workflowregistry.NodeTypeCondition, Name: "Confirm Route", Config: mustMarshalWorkflowTestConfig(dsl.ConditionConfig{Branches: []dsl.ConditionBranch{
|
||||||
|
{ID: "yes", Name: "Yes", TargetNodeID: "create_ticket_1", Condition: &dsl.Condition{
|
||||||
|
Left: &dsl.VariableSelector{NodeID: "confirm_1", Field: "confirmed"},
|
||||||
|
Operator: "is_true",
|
||||||
|
}},
|
||||||
|
{ID: "default", Name: "Cancel", TargetNodeID: "cancel_end", Default: true},
|
||||||
|
}})},
|
||||||
{ID: "create_ticket_1", Type: workflowregistry.NodeTypeCreateTicket, Name: "Create Ticket", Inputs: map[string]dsl.VariableSelector{
|
{ID: "create_ticket_1", Type: workflowregistry.NodeTypeCreateTicket, Name: "Create Ticket", Inputs: map[string]dsl.VariableSelector{
|
||||||
"ticketDraft": {NodeID: "draft_1", Field: "ticketDraft"},
|
"ticketDraft": {NodeID: "draft_1", Field: "ticketDraft"},
|
||||||
"confirmed": {NodeID: "confirm_1", Field: "confirmed"},
|
"confirmed": {NodeID: "confirm_1", Field: "confirmed"},
|
||||||
@@ -459,16 +475,9 @@ func createTicketWorkflowDefinition() dsl.Definition {
|
|||||||
{ID: "edge_start_draft", Source: "start_1", Target: "draft_1"},
|
{ID: "edge_start_draft", Source: "start_1", Target: "draft_1"},
|
||||||
{ID: "edge_draft_prompt", Source: "draft_1", Target: "prompt_1"},
|
{ID: "edge_draft_prompt", Source: "draft_1", Target: "prompt_1"},
|
||||||
{ID: "edge_prompt_confirm", Source: "prompt_1", Target: "confirm_1"},
|
{ID: "edge_prompt_confirm", Source: "prompt_1", Target: "confirm_1"},
|
||||||
{
|
{ID: "edge_confirm_route", Source: "confirm_1", Target: "confirm_route_1"},
|
||||||
ID: "edge_confirm_create",
|
{ID: "edge_confirm_create", Source: "confirm_route_1", Target: "create_ticket_1"},
|
||||||
Source: "confirm_1",
|
{ID: "edge_confirm_cancel", Source: "confirm_route_1", Target: "cancel_end"},
|
||||||
Target: "create_ticket_1",
|
|
||||||
Condition: &dsl.Condition{
|
|
||||||
Left: &dsl.VariableSelector{NodeID: "confirm_1", Field: "confirmed"},
|
|
||||||
Operator: "is_true",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{ID: "edge_confirm_cancel", Source: "confirm_1", Target: "cancel_end"},
|
|
||||||
{ID: "edge_create_end", Source: "create_ticket_1", Target: "end_1"},
|
{ID: "edge_create_end", Source: "create_ticket_1", Target: "end_1"},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -484,22 +493,22 @@ func humanConfirmWorkflowDefinition() dsl.Definition {
|
|||||||
{ID: "confirm_1", Type: workflowregistry.NodeTypeHumanConfirm, Name: "Confirm", Inputs: map[string]dsl.VariableSelector{
|
{ID: "confirm_1", Type: workflowregistry.NodeTypeHumanConfirm, Name: "Confirm", Inputs: map[string]dsl.VariableSelector{
|
||||||
"prompt": {NodeID: "prompt_1", Field: "replyText"},
|
"prompt": {NodeID: "prompt_1", Field: "replyText"},
|
||||||
}},
|
}},
|
||||||
|
{ID: "confirm_route_1", Type: workflowregistry.NodeTypeCondition, Name: "Confirm Route", Config: mustMarshalWorkflowTestConfig(dsl.ConditionConfig{Branches: []dsl.ConditionBranch{
|
||||||
|
{ID: "yes", Name: "Yes", TargetNodeID: "end_1", Condition: &dsl.Condition{
|
||||||
|
Left: &dsl.VariableSelector{NodeID: "confirm_1", Field: "confirmed"},
|
||||||
|
Operator: "is_true",
|
||||||
|
}},
|
||||||
|
{ID: "default", Name: "Cancel", TargetNodeID: "cancel_end", Default: true},
|
||||||
|
}})},
|
||||||
{ID: "end_1", Type: workflowregistry.NodeTypeEnd, Name: "End"},
|
{ID: "end_1", Type: workflowregistry.NodeTypeEnd, Name: "End"},
|
||||||
{ID: "cancel_end", Type: workflowregistry.NodeTypeEnd, Name: "Cancel"},
|
{ID: "cancel_end", Type: workflowregistry.NodeTypeEnd, Name: "Cancel"},
|
||||||
},
|
},
|
||||||
Edges: []dsl.Edge{
|
Edges: []dsl.Edge{
|
||||||
{ID: "edge_start_prompt", Source: "start_1", Target: "prompt_1"},
|
{ID: "edge_start_prompt", Source: "start_1", Target: "prompt_1"},
|
||||||
{ID: "edge_prompt_confirm", Source: "prompt_1", Target: "confirm_1"},
|
{ID: "edge_prompt_confirm", Source: "prompt_1", Target: "confirm_1"},
|
||||||
{
|
{ID: "edge_confirm_route", Source: "confirm_1", Target: "confirm_route_1"},
|
||||||
ID: "edge_confirm_yes",
|
{ID: "edge_confirm_yes", Source: "confirm_route_1", Target: "end_1"},
|
||||||
Source: "confirm_1",
|
{ID: "edge_confirm_cancel", Source: "confirm_route_1", Target: "cancel_end"},
|
||||||
Target: "end_1",
|
|
||||||
Condition: &dsl.Condition{
|
|
||||||
Left: &dsl.VariableSelector{NodeID: "confirm_1", Field: "confirmed"},
|
|
||||||
Operator: "is_true",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{ID: "edge_confirm_cancel", Source: "confirm_1", Target: "cancel_end"},
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -513,21 +522,21 @@ func prepareTicketDraftWorkflowDefinition() dsl.Definition {
|
|||||||
{ID: "draft_1", Type: workflowregistry.NodeTypePrepareTicketDraft, Name: "Draft", Inputs: map[string]dsl.VariableSelector{
|
{ID: "draft_1", Type: workflowregistry.NodeTypePrepareTicketDraft, Name: "Draft", Inputs: map[string]dsl.VariableSelector{
|
||||||
"issue": {NodeID: "start_1", Field: "userMessage"},
|
"issue": {NodeID: "start_1", Field: "userMessage"},
|
||||||
}},
|
}},
|
||||||
|
{ID: "draft_route_1", Type: workflowregistry.NodeTypeCondition, Name: "Draft Route", Config: mustMarshalWorkflowTestConfig(dsl.ConditionConfig{Branches: []dsl.ConditionBranch{
|
||||||
|
{ID: "ready", Name: "Ready", TargetNodeID: "ready_end", Condition: &dsl.Condition{
|
||||||
|
Left: &dsl.VariableSelector{NodeID: "draft_1", Field: "ticketDraft"},
|
||||||
|
Operator: "exists",
|
||||||
|
}},
|
||||||
|
{ID: "default", Name: "Default", TargetNodeID: "default_end", Default: true},
|
||||||
|
}})},
|
||||||
{ID: "ready_end", Type: workflowregistry.NodeTypeEnd, Name: "Ready"},
|
{ID: "ready_end", Type: workflowregistry.NodeTypeEnd, Name: "Ready"},
|
||||||
{ID: "default_end", Type: workflowregistry.NodeTypeEnd, Name: "Default"},
|
{ID: "default_end", Type: workflowregistry.NodeTypeEnd, Name: "Default"},
|
||||||
},
|
},
|
||||||
Edges: []dsl.Edge{
|
Edges: []dsl.Edge{
|
||||||
{ID: "edge_start_draft", Source: "start_1", Target: "draft_1"},
|
{ID: "edge_start_draft", Source: "start_1", Target: "draft_1"},
|
||||||
{
|
{ID: "edge_draft_route", Source: "draft_1", Target: "draft_route_1"},
|
||||||
ID: "edge_draft_ready",
|
{ID: "edge_draft_ready", Source: "draft_route_1", Target: "ready_end"},
|
||||||
Source: "draft_1",
|
{ID: "edge_draft_default", Source: "draft_route_1", Target: "default_end"},
|
||||||
Target: "ready_end",
|
|
||||||
Condition: &dsl.Condition{
|
|
||||||
Left: &dsl.VariableSelector{NodeID: "draft_1", Field: "ticketDraft"},
|
|
||||||
Operator: "exists",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{ID: "edge_draft_default", Source: "draft_1", Target: "default_end"},
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -541,21 +550,21 @@ func analyzeConversationWorkflowDefinition() dsl.Definition {
|
|||||||
{ID: "analyze_1", Type: workflowregistry.NodeTypeAnalyzeConversation, Name: "Analyze", Inputs: map[string]dsl.VariableSelector{
|
{ID: "analyze_1", Type: workflowregistry.NodeTypeAnalyzeConversation, Name: "Analyze", Inputs: map[string]dsl.VariableSelector{
|
||||||
"userMessage": {NodeID: "start_1", Field: "userMessage"},
|
"userMessage": {NodeID: "start_1", Field: "userMessage"},
|
||||||
}},
|
}},
|
||||||
|
{ID: "analyze_route_1", Type: workflowregistry.NodeTypeCondition, Name: "Analyze Route", Config: mustMarshalWorkflowTestConfig(dsl.ConditionConfig{Branches: []dsl.ConditionBranch{
|
||||||
|
{ID: "handoff", Name: "Handoff", TargetNodeID: "handoff_end", Condition: &dsl.Condition{
|
||||||
|
Left: &dsl.VariableSelector{NodeID: "analyze_1", Field: "needHumanHandoff"},
|
||||||
|
Operator: "is_true",
|
||||||
|
}},
|
||||||
|
{ID: "default", Name: "Default", TargetNodeID: "default_end", Default: true},
|
||||||
|
}})},
|
||||||
{ID: "handoff_end", Type: workflowregistry.NodeTypeEnd, Name: "Handoff"},
|
{ID: "handoff_end", Type: workflowregistry.NodeTypeEnd, Name: "Handoff"},
|
||||||
{ID: "default_end", Type: workflowregistry.NodeTypeEnd, Name: "Default"},
|
{ID: "default_end", Type: workflowregistry.NodeTypeEnd, Name: "Default"},
|
||||||
},
|
},
|
||||||
Edges: []dsl.Edge{
|
Edges: []dsl.Edge{
|
||||||
{ID: "edge_start_analyze", Source: "start_1", Target: "analyze_1"},
|
{ID: "edge_start_analyze", Source: "start_1", Target: "analyze_1"},
|
||||||
{
|
{ID: "edge_analyze_route", Source: "analyze_1", Target: "analyze_route_1"},
|
||||||
ID: "edge_analyze_handoff",
|
{ID: "edge_analyze_handoff", Source: "analyze_route_1", Target: "handoff_end"},
|
||||||
Source: "analyze_1",
|
{ID: "edge_analyze_default", Source: "analyze_route_1", Target: "default_end"},
|
||||||
Target: "handoff_end",
|
|
||||||
Condition: &dsl.Condition{
|
|
||||||
Left: &dsl.VariableSelector{NodeID: "analyze_1", Field: "needHumanHandoff"},
|
|
||||||
Operator: "is_true",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{ID: "edge_analyze_default", Source: "analyze_1", Target: "default_end"},
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -569,22 +578,22 @@ func handoffWorkflowDefinition() dsl.Definition {
|
|||||||
{ID: "handoff_1", Type: workflowregistry.NodeTypeHandoffToHuman, Name: "Handoff", Inputs: map[string]dsl.VariableSelector{
|
{ID: "handoff_1", Type: workflowregistry.NodeTypeHandoffToHuman, Name: "Handoff", Inputs: map[string]dsl.VariableSelector{
|
||||||
"reason": {NodeID: "start_1", Field: "userMessage"},
|
"reason": {NodeID: "start_1", Field: "userMessage"},
|
||||||
}},
|
}},
|
||||||
|
{ID: "handoff_route_1", Type: workflowregistry.NodeTypeCondition, Name: "Handoff Route", Config: mustMarshalWorkflowTestConfig(dsl.ConditionConfig{Branches: []dsl.ConditionBranch{
|
||||||
|
{ID: "assigned", Name: "Assigned", TargetNodeID: "assigned_end", Condition: &dsl.Condition{
|
||||||
|
Left: &dsl.VariableSelector{NodeID: "handoff_1", Field: "decision"},
|
||||||
|
Operator: "eq",
|
||||||
|
Right: string(services.HandoffDecisionAssigned),
|
||||||
|
}},
|
||||||
|
{ID: "default", Name: "Default", TargetNodeID: "default_end", Default: true},
|
||||||
|
}})},
|
||||||
{ID: "assigned_end", Type: workflowregistry.NodeTypeEnd, Name: "Assigned"},
|
{ID: "assigned_end", Type: workflowregistry.NodeTypeEnd, Name: "Assigned"},
|
||||||
{ID: "default_end", Type: workflowregistry.NodeTypeEnd, Name: "Default"},
|
{ID: "default_end", Type: workflowregistry.NodeTypeEnd, Name: "Default"},
|
||||||
},
|
},
|
||||||
Edges: []dsl.Edge{
|
Edges: []dsl.Edge{
|
||||||
{ID: "edge_start_handoff", Source: "start_1", Target: "handoff_1"},
|
{ID: "edge_start_handoff", Source: "start_1", Target: "handoff_1"},
|
||||||
{
|
{ID: "edge_handoff_route", Source: "handoff_1", Target: "handoff_route_1"},
|
||||||
ID: "edge_handoff_assigned",
|
{ID: "edge_handoff_assigned", Source: "handoff_route_1", Target: "assigned_end"},
|
||||||
Source: "handoff_1",
|
{ID: "edge_handoff_default", Source: "handoff_route_1", Target: "default_end"},
|
||||||
Target: "assigned_end",
|
|
||||||
Condition: &dsl.Condition{
|
|
||||||
Left: &dsl.VariableSelector{NodeID: "handoff_1", Field: "decision"},
|
|
||||||
Operator: "eq",
|
|
||||||
Right: string(services.HandoffDecisionAssigned),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{ID: "edge_handoff_default", Source: "handoff_1", Target: "default_end"},
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,10 +24,21 @@ type Position struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Edge struct {
|
type Edge struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Source string `json:"source"`
|
Source string `json:"source"`
|
||||||
Target string `json:"target"`
|
Target string `json:"target"`
|
||||||
Condition *Condition `json:"condition,omitempty"`
|
}
|
||||||
|
|
||||||
|
type ConditionConfig struct {
|
||||||
|
Branches []ConditionBranch `json:"branches,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ConditionBranch struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name,omitempty"`
|
||||||
|
TargetNodeID string `json:"targetNodeId"`
|
||||||
|
Condition *Condition `json:"condition,omitempty"`
|
||||||
|
Default bool `json:"default,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type Condition struct {
|
type Condition struct {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package validator
|
package validator
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -268,31 +269,60 @@ func (v *definitionValidator) validateInputSelector(nodeID string, input registr
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (v *definitionValidator) validateConditions() {
|
func (v *definitionValidator) validateConditions() {
|
||||||
conditionalSources := make(map[string]bool)
|
for index, node := range v.def.Nodes {
|
||||||
defaultSources := make(map[string]bool)
|
if strings.TrimSpace(node.Type) != registry.NodeTypeCondition {
|
||||||
for index, edge := range v.def.Edges {
|
|
||||||
field := fmt.Sprintf("edges[%d].condition", index)
|
|
||||||
sourceID := strings.TrimSpace(edge.Source)
|
|
||||||
if edge.Condition == nil {
|
|
||||||
if sourceID != "" {
|
|
||||||
defaultSources[sourceID] = true
|
|
||||||
}
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if sourceID != "" {
|
field := fmt.Sprintf("nodes[%d].config.branches", index)
|
||||||
conditionalSources[sourceID] = true
|
config := dsl.ConditionConfig{}
|
||||||
|
if len(node.Config) > 0 {
|
||||||
|
if err := json.Unmarshal(node.Config, &config); err != nil {
|
||||||
|
v.addError(field, "condition branches config must be valid JSON")
|
||||||
|
continue
|
||||||
|
}
|
||||||
}
|
}
|
||||||
v.validateCondition(field, sourceID, edge.Condition)
|
if len(config.Branches) == 0 {
|
||||||
}
|
v.addError(field, "condition node must include at least one branch")
|
||||||
for sourceID := range conditionalSources {
|
continue
|
||||||
if !defaultSources[sourceID] {
|
}
|
||||||
v.addError("edges."+sourceID, "conditional branch must include a default edge")
|
defaultCount := 0
|
||||||
|
seenBranchIDs := make(map[string]struct{}, len(config.Branches))
|
||||||
|
for branchIndex, branch := range config.Branches {
|
||||||
|
branchField := fmt.Sprintf("%s[%d]", field, branchIndex)
|
||||||
|
branchID := strings.TrimSpace(branch.ID)
|
||||||
|
if branchID == "" {
|
||||||
|
v.addError(branchField+".id", "condition branch id is required")
|
||||||
|
} else if _, exists := seenBranchIDs[branchID]; exists {
|
||||||
|
v.addError(branchField+".id", "duplicate condition branch id: "+branchID)
|
||||||
|
}
|
||||||
|
seenBranchIDs[branchID] = struct{}{}
|
||||||
|
targetNodeID := strings.TrimSpace(branch.TargetNodeID)
|
||||||
|
if targetNodeID == "" {
|
||||||
|
v.addError(branchField+".targetNodeId", "condition branch target node is required")
|
||||||
|
} else if _, ok := v.nodesByID[targetNodeID]; !ok {
|
||||||
|
v.addError(branchField+".targetNodeId", "condition branch target node does not exist: "+targetNodeID)
|
||||||
|
}
|
||||||
|
if !v.hasEdgeTo(strings.TrimSpace(node.ID), targetNodeID) {
|
||||||
|
v.addError(branchField+".targetNodeId", "condition branch target must have an outgoing edge: "+targetNodeID)
|
||||||
|
}
|
||||||
|
if branch.Default {
|
||||||
|
defaultCount++
|
||||||
|
if branch.Condition != nil {
|
||||||
|
v.addError(branchField+".condition", "default condition branch must not define a condition")
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
v.validateCondition(branchField+".condition", strings.TrimSpace(node.ID), branch.Condition)
|
||||||
|
}
|
||||||
|
if defaultCount != 1 {
|
||||||
|
v.addError(field, "condition node must include exactly one default branch")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *definitionValidator) validateCondition(field string, sourceNodeID string, condition *dsl.Condition) {
|
func (v *definitionValidator) validateCondition(field string, sourceNodeID string, condition *dsl.Condition) {
|
||||||
if condition == nil {
|
if condition == nil {
|
||||||
|
v.addError(field, "condition branch condition is required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
operator := strings.TrimSpace(condition.Operator)
|
operator := strings.TrimSpace(condition.Operator)
|
||||||
@@ -360,6 +390,18 @@ func (v *definitionValidator) hasPath(sourceID string, targetID string, visiting
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (v *definitionValidator) hasEdgeTo(sourceID string, targetID string) bool {
|
||||||
|
if sourceID == "" || targetID == "" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for _, edge := range v.def.Edges {
|
||||||
|
if strings.TrimSpace(edge.Source) == sourceID && strings.TrimSpace(edge.Target) == targetID {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
func findInputSpec(items []registry.VariableSpec, name string) (registry.VariableSpec, bool) {
|
func findInputSpec(items []registry.VariableSpec, name string) (registry.VariableSpec, bool) {
|
||||||
name = strings.TrimSpace(name)
|
name = strings.TrimSpace(name)
|
||||||
for _, item := range items {
|
for _, item := range items {
|
||||||
|
|||||||
@@ -260,7 +260,16 @@ func TestValidateDefinitionAcceptsMappedKnowledgeFlow(t *testing.T) {
|
|||||||
|
|
||||||
func TestValidateDefinitionRejectsUnknownConditionOperator(t *testing.T) {
|
func TestValidateDefinitionRejectsUnknownConditionOperator(t *testing.T) {
|
||||||
def := conditionDefinition()
|
def := conditionDefinition()
|
||||||
def.Edges[1].Condition.Operator = "regex"
|
var config dsl.ConditionConfig
|
||||||
|
if err := json.Unmarshal(def.Nodes[1].Config, &config); err != nil {
|
||||||
|
t.Fatalf("unmarshal condition config: %v", err)
|
||||||
|
}
|
||||||
|
config.Branches[0].Condition.Operator = "regex"
|
||||||
|
raw, err := json.Marshal(config)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal condition config: %v", err)
|
||||||
|
}
|
||||||
|
def.Nodes[1].Config = raw
|
||||||
|
|
||||||
result := validator.ValidateDefinition(def, registry.DefaultRegistry())
|
result := validator.ValidateDefinition(def, registry.DefaultRegistry())
|
||||||
|
|
||||||
@@ -274,7 +283,16 @@ func TestValidateDefinitionRejectsUnknownConditionOperator(t *testing.T) {
|
|||||||
|
|
||||||
func TestValidateDefinitionRejectsUnknownConditionVariable(t *testing.T) {
|
func TestValidateDefinitionRejectsUnknownConditionVariable(t *testing.T) {
|
||||||
def := conditionDefinition()
|
def := conditionDefinition()
|
||||||
def.Edges[1].Condition.Left.Field = "missing"
|
var config dsl.ConditionConfig
|
||||||
|
if err := json.Unmarshal(def.Nodes[1].Config, &config); err != nil {
|
||||||
|
t.Fatalf("unmarshal condition config: %v", err)
|
||||||
|
}
|
||||||
|
config.Branches[0].Condition.Left.Field = "missing"
|
||||||
|
raw, err := json.Marshal(config)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal condition config: %v", err)
|
||||||
|
}
|
||||||
|
def.Nodes[1].Config = raw
|
||||||
|
|
||||||
result := validator.ValidateDefinition(def, registry.DefaultRegistry())
|
result := validator.ValidateDefinition(def, registry.DefaultRegistry())
|
||||||
|
|
||||||
@@ -313,26 +331,37 @@ func mappedReplyDefinition() dsl.Definition {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func conditionDefinition() dsl.Definition {
|
func conditionDefinition() dsl.Definition {
|
||||||
return dsl.Definition{
|
conditionConfig, _ := json.Marshal(dsl.ConditionConfig{
|
||||||
SchemaVersion: 1,
|
Branches: []dsl.ConditionBranch{
|
||||||
EntryNodeID: "start_1",
|
|
||||||
Nodes: []dsl.Node{
|
|
||||||
{ID: "start_1", Type: "start"},
|
|
||||||
{ID: "condition_1", Type: "condition"},
|
|
||||||
{ID: "end_1", Type: "end"},
|
|
||||||
},
|
|
||||||
Edges: []dsl.Edge{
|
|
||||||
{ID: "e1", Source: "start_1", Target: "condition_1"},
|
|
||||||
{
|
{
|
||||||
ID: "e2",
|
ID: "hello",
|
||||||
Source: "condition_1",
|
Name: "Hello",
|
||||||
Target: "end_1",
|
TargetNodeID: "end_1",
|
||||||
Condition: &dsl.Condition{
|
Condition: &dsl.Condition{
|
||||||
Left: &dsl.VariableSelector{NodeID: "start_1", Field: "userMessage"},
|
Left: &dsl.VariableSelector{NodeID: "start_1", Field: "userMessage"},
|
||||||
Operator: "eq",
|
Operator: "eq",
|
||||||
Right: "hello",
|
Right: "hello",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
ID: "default",
|
||||||
|
Name: "Default",
|
||||||
|
TargetNodeID: "end_1",
|
||||||
|
Default: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return dsl.Definition{
|
||||||
|
SchemaVersion: 1,
|
||||||
|
EntryNodeID: "start_1",
|
||||||
|
Nodes: []dsl.Node{
|
||||||
|
{ID: "start_1", Type: "start"},
|
||||||
|
{ID: "condition_1", Type: "condition", Config: conditionConfig},
|
||||||
|
{ID: "end_1", Type: "end"},
|
||||||
|
},
|
||||||
|
Edges: []dsl.Edge{
|
||||||
|
{ID: "e1", Source: "start_1", Target: "condition_1"},
|
||||||
|
{ID: "e2", Source: "condition_1", Target: "end_1"},
|
||||||
{ID: "e3", Source: "condition_1", Target: "end_1"},
|
{ID: "e3", Source: "condition_1", Target: "end_1"},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -73,10 +73,10 @@ func TestAIAgentServiceCreatesDefaultWorkflow(t *testing.T) {
|
|||||||
t.Fatalf("expected default workflow to include %s node: %#v", nodeType, stored.Nodes)
|
t.Fatalf("expected default workflow to include %s node: %#v", nodeType, stored.Nodes)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
assertConditionEdgeToNodeType(t, stored, "route_intent_1", workflowregistry.NodeTypeHandoffToHuman, "contains", "人工")
|
assertConditionBranchToNodeType(t, stored, "route_intent_1", workflowregistry.NodeTypeHandoffToHuman, "contains", "人工")
|
||||||
assertConditionEdgeToNodeType(t, stored, "route_intent_1", workflowregistry.NodeTypePrepareTicketDraft, "contains", "工单")
|
assertConditionBranchToNodeType(t, stored, "route_intent_1", workflowregistry.NodeTypePrepareTicketDraft, "contains", "工单")
|
||||||
assertConditionEdgeToNodeType(t, stored, "answerability_1", workflowregistry.NodeTypeLLMReply, "eq", "answerable")
|
assertConditionBranchToNodeID(t, stored, "answerability_route_1", "reply_1", "eq", "answerable")
|
||||||
assertDefaultEdgeToNodeType(t, stored, "answerability_1", workflowregistry.NodeTypeLLMReply)
|
assertDefaultBranchToNodeID(t, stored, "answerability_route_1", "fallback_reply_1")
|
||||||
if !workflowEdgeExists(stored, "create_ticket_1", "ticket_result_reply_1") {
|
if !workflowEdgeExists(stored, "create_ticket_1", "ticket_result_reply_1") {
|
||||||
t.Fatalf("expected create_ticket to flow into a customer-visible result reply")
|
t.Fatalf("expected create_ticket to flow into a customer-visible result reply")
|
||||||
}
|
}
|
||||||
@@ -235,29 +235,57 @@ func nodeTypeByID(def dsl.Definition, nodeID string) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func assertConditionEdgeToNodeType(t *testing.T, def dsl.Definition, sourceID string, targetType string, operator string, right any) {
|
func assertConditionBranchToNodeType(t *testing.T, def dsl.Definition, sourceID string, targetType string, operator string, right any) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
nodeTypes := workflowNodeTypeMap(def)
|
nodeTypes := workflowNodeTypeMap(def)
|
||||||
for _, edge := range def.Edges {
|
for _, branch := range conditionBranches(t, def, sourceID) {
|
||||||
if edge.Source != sourceID || nodeTypes[edge.Target] != targetType || edge.Condition == nil {
|
if nodeTypes[branch.TargetNodeID] != targetType || branch.Condition == nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if edge.Condition.Operator == operator && edge.Condition.Right == right {
|
if branch.Condition.Operator == operator && branch.Condition.Right == right {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
t.Fatalf("expected %s conditional edge from %s to %s with right=%v, got %#v", operator, sourceID, targetType, right, def.Edges)
|
t.Fatalf("expected %s condition branch from %s to %s with right=%v", operator, sourceID, targetType, right)
|
||||||
}
|
}
|
||||||
|
|
||||||
func assertDefaultEdgeToNodeType(t *testing.T, def dsl.Definition, sourceID string, targetType string) {
|
func assertConditionBranchToNodeID(t *testing.T, def dsl.Definition, sourceID string, targetID string, operator string, right any) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
nodeTypes := workflowNodeTypeMap(def)
|
for _, branch := range conditionBranches(t, def, sourceID) {
|
||||||
for _, edge := range def.Edges {
|
if branch.TargetNodeID != targetID || branch.Condition == nil {
|
||||||
if edge.Source == sourceID && nodeTypes[edge.Target] == targetType && edge.Condition == nil {
|
continue
|
||||||
|
}
|
||||||
|
if branch.Condition.Operator == operator && branch.Condition.Right == right {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
t.Fatalf("expected default edge from %s to %s, got %#v", sourceID, targetType, def.Edges)
|
t.Fatalf("expected %s condition branch from %s to %s with right=%v", operator, sourceID, targetID, right)
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertDefaultBranchToNodeID(t *testing.T, def dsl.Definition, sourceID string, targetID string) {
|
||||||
|
t.Helper()
|
||||||
|
for _, branch := range conditionBranches(t, def, sourceID) {
|
||||||
|
if branch.TargetNodeID == targetID && branch.Default {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatalf("expected default branch from %s to %s", sourceID, targetID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func conditionBranches(t *testing.T, def dsl.Definition, nodeID string) []dsl.ConditionBranch {
|
||||||
|
t.Helper()
|
||||||
|
for _, node := range def.Nodes {
|
||||||
|
if node.ID != nodeID {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var config dsl.ConditionConfig
|
||||||
|
if err := json.Unmarshal(node.Config, &config); err != nil {
|
||||||
|
t.Fatalf("unmarshal condition config for %s: %v", nodeID, err)
|
||||||
|
}
|
||||||
|
return config.Branches
|
||||||
|
}
|
||||||
|
t.Fatalf("condition node not found: %s", nodeID)
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func workflowEdgeExists(def dsl.Definition, sourceID string, targetID string) bool {
|
func workflowEdgeExists(def dsl.Definition, sourceID string, targetID string) bool {
|
||||||
|
|||||||
@@ -427,7 +427,13 @@ func defaultAgentWorkflowDefinition() dsl.Definition {
|
|||||||
EntryNodeID: "start_1",
|
EntryNodeID: "start_1",
|
||||||
Nodes: []dsl.Node{
|
Nodes: []dsl.Node{
|
||||||
{ID: "start_1", Type: workflowregistry.NodeTypeStart, Name: "开始", Position: dsl.Position{X: 0, Y: 260}},
|
{ID: "start_1", Type: workflowregistry.NodeTypeStart, Name: "开始", Position: dsl.Position{X: 0, Y: 260}},
|
||||||
{ID: "route_intent_1", Type: workflowregistry.NodeTypeCondition, Name: "意图分流", Position: dsl.Position{X: 260, Y: 260}},
|
{ID: "route_intent_1", Type: workflowregistry.NodeTypeCondition, Name: "意图分流", Position: dsl.Position{X: 260, Y: 260}, Config: mustMarshalWorkflowConfig(dsl.ConditionConfig{Branches: []dsl.ConditionBranch{
|
||||||
|
{ID: "handoff", Name: "需要转人工", TargetNodeID: "handoff_1", Condition: &dsl.Condition{Left: &dsl.VariableSelector{NodeID: "start_1", Field: "userMessage"}, Operator: "contains", Right: "人工"}},
|
||||||
|
{ID: "ticket", Name: "需要建单", TargetNodeID: "draft_ticket_1", Condition: &dsl.Condition{Left: &dsl.VariableSelector{NodeID: "start_1", Field: "userMessage"}, Operator: "contains", Right: "工单"}},
|
||||||
|
{ID: "complaint", Name: "投诉建单", TargetNodeID: "draft_ticket_1", Condition: &dsl.Condition{Left: &dsl.VariableSelector{NodeID: "start_1", Field: "userMessage"}, Operator: "contains", Right: "投诉"}},
|
||||||
|
{ID: "incident", Name: "报障建单", TargetNodeID: "draft_ticket_1", Condition: &dsl.Condition{Left: &dsl.VariableSelector{NodeID: "start_1", Field: "userMessage"}, Operator: "contains", Right: "报障"}},
|
||||||
|
{ID: "default", Name: "默认知识库回复", TargetNodeID: "retrieve_1", Default: true},
|
||||||
|
}})},
|
||||||
{ID: "handoff_1", Type: workflowregistry.NodeTypeHandoffToHuman, Name: "转人工", Position: dsl.Position{X: 560, Y: 80}, Inputs: map[string]dsl.VariableSelector{
|
{ID: "handoff_1", Type: workflowregistry.NodeTypeHandoffToHuman, Name: "转人工", Position: dsl.Position{X: 560, Y: 80}, Inputs: map[string]dsl.VariableSelector{
|
||||||
"reason": {NodeID: "start_1", Field: "userMessage"},
|
"reason": {NodeID: "start_1", Field: "userMessage"},
|
||||||
}},
|
}},
|
||||||
@@ -441,6 +447,10 @@ func defaultAgentWorkflowDefinition() dsl.Definition {
|
|||||||
{ID: "ticket_confirm_1", Type: workflowregistry.NodeTypeHumanConfirm, Name: "确认建单", Position: dsl.Position{X: 1160, Y: 240}, Inputs: map[string]dsl.VariableSelector{
|
{ID: "ticket_confirm_1", Type: workflowregistry.NodeTypeHumanConfirm, Name: "确认建单", Position: dsl.Position{X: 1160, Y: 240}, Inputs: map[string]dsl.VariableSelector{
|
||||||
"prompt": {NodeID: "ticket_confirm_prompt_1", Field: "replyText"},
|
"prompt": {NodeID: "ticket_confirm_prompt_1", Field: "replyText"},
|
||||||
}},
|
}},
|
||||||
|
{ID: "ticket_confirm_route_1", Type: workflowregistry.NodeTypeCondition, Name: "建单确认分流", Position: dsl.Position{X: 1310, Y: 240}, Config: mustMarshalWorkflowConfig(dsl.ConditionConfig{Branches: []dsl.ConditionBranch{
|
||||||
|
{ID: "confirmed", Name: "已确认", TargetNodeID: "create_ticket_1", Condition: &dsl.Condition{Left: &dsl.VariableSelector{NodeID: "ticket_confirm_1", Field: "confirmed"}, Operator: "is_true"}},
|
||||||
|
{ID: "default", Name: "取消或未确认", TargetNodeID: "ticket_cancel_reply_1", Default: true},
|
||||||
|
}})},
|
||||||
{ID: "create_ticket_1", Type: workflowregistry.NodeTypeCreateTicket, Name: "创建工单", Position: dsl.Position{X: 1460, Y: 180}, Inputs: map[string]dsl.VariableSelector{
|
{ID: "create_ticket_1", Type: workflowregistry.NodeTypeCreateTicket, Name: "创建工单", Position: dsl.Position{X: 1460, Y: 180}, Inputs: map[string]dsl.VariableSelector{
|
||||||
"ticketDraft": {NodeID: "draft_ticket_1", Field: "ticketDraft"},
|
"ticketDraft": {NodeID: "draft_ticket_1", Field: "ticketDraft"},
|
||||||
"confirmed": {NodeID: "ticket_confirm_1", Field: "confirmed"},
|
"confirmed": {NodeID: "ticket_confirm_1", Field: "confirmed"},
|
||||||
@@ -461,6 +471,10 @@ func defaultAgentWorkflowDefinition() dsl.Definition {
|
|||||||
"userMessage": {NodeID: "start_1", Field: "userMessage"},
|
"userMessage": {NodeID: "start_1", Field: "userMessage"},
|
||||||
"knowledgeItems": {NodeID: "retrieve_1", Field: "items"},
|
"knowledgeItems": {NodeID: "retrieve_1", Field: "items"},
|
||||||
}},
|
}},
|
||||||
|
{ID: "answerability_route_1", Type: workflowregistry.NodeTypeCondition, Name: "可回答分流", Position: dsl.Position{X: 1010, Y: 500}, Config: mustMarshalWorkflowConfig(dsl.ConditionConfig{Branches: []dsl.ConditionBranch{
|
||||||
|
{ID: "answerable", Name: "可以回答", TargetNodeID: "reply_1", Condition: &dsl.Condition{Left: &dsl.VariableSelector{NodeID: "answerability_1", Field: "answerability"}, Operator: "eq", Right: "answerable"}},
|
||||||
|
{ID: "default", Name: "兜底追问", TargetNodeID: "fallback_reply_1", Default: true},
|
||||||
|
}})},
|
||||||
{ID: "reply_1", Type: workflowregistry.NodeTypeLLMReply, Name: "AI 回复", Position: dsl.Position{X: 1160, Y: 440}, Inputs: map[string]dsl.VariableSelector{
|
{ID: "reply_1", Type: workflowregistry.NodeTypeLLMReply, Name: "AI 回复", Position: dsl.Position{X: 1160, Y: 440}, Inputs: map[string]dsl.VariableSelector{
|
||||||
"userMessage": {NodeID: "start_1", Field: "userMessage"},
|
"userMessage": {NodeID: "start_1", Field: "userMessage"},
|
||||||
"knowledgeItems": {NodeID: "retrieve_1", Field: "items"},
|
"knowledgeItems": {NodeID: "retrieve_1", Field: "items"},
|
||||||
@@ -479,46 +493,23 @@ func defaultAgentWorkflowDefinition() dsl.Definition {
|
|||||||
},
|
},
|
||||||
Edges: []dsl.Edge{
|
Edges: []dsl.Edge{
|
||||||
{ID: "edge_start_route_intent", Source: "start_1", Target: "route_intent_1"},
|
{ID: "edge_start_route_intent", Source: "start_1", Target: "route_intent_1"},
|
||||||
{ID: "edge_intent_handoff", Source: "route_intent_1", Target: "handoff_1", Condition: &dsl.Condition{
|
{ID: "edge_intent_handoff", Source: "route_intent_1", Target: "handoff_1"},
|
||||||
Left: &dsl.VariableSelector{NodeID: "start_1", Field: "userMessage"},
|
{ID: "edge_intent_ticket", Source: "route_intent_1", Target: "draft_ticket_1"},
|
||||||
Operator: "contains",
|
|
||||||
Right: "人工",
|
|
||||||
}},
|
|
||||||
{ID: "edge_intent_ticket", Source: "route_intent_1", Target: "draft_ticket_1", Condition: &dsl.Condition{
|
|
||||||
Left: &dsl.VariableSelector{NodeID: "start_1", Field: "userMessage"},
|
|
||||||
Operator: "contains",
|
|
||||||
Right: "工单",
|
|
||||||
}},
|
|
||||||
{ID: "edge_intent_complaint", Source: "route_intent_1", Target: "draft_ticket_1", Condition: &dsl.Condition{
|
|
||||||
Left: &dsl.VariableSelector{NodeID: "start_1", Field: "userMessage"},
|
|
||||||
Operator: "contains",
|
|
||||||
Right: "投诉",
|
|
||||||
}},
|
|
||||||
{ID: "edge_intent_incident", Source: "route_intent_1", Target: "draft_ticket_1", Condition: &dsl.Condition{
|
|
||||||
Left: &dsl.VariableSelector{NodeID: "start_1", Field: "userMessage"},
|
|
||||||
Operator: "contains",
|
|
||||||
Right: "报障",
|
|
||||||
}},
|
|
||||||
{ID: "edge_intent_knowledge_default", Source: "route_intent_1", Target: "retrieve_1"},
|
{ID: "edge_intent_knowledge_default", Source: "route_intent_1", Target: "retrieve_1"},
|
||||||
{ID: "edge_handoff_end", Source: "handoff_1", Target: "handoff_end_1"},
|
{ID: "edge_handoff_end", Source: "handoff_1", Target: "handoff_end_1"},
|
||||||
{ID: "edge_draft_ticket_confirm_prompt", Source: "draft_ticket_1", Target: "ticket_confirm_prompt_1"},
|
{ID: "edge_draft_ticket_confirm_prompt", Source: "draft_ticket_1", Target: "ticket_confirm_prompt_1"},
|
||||||
{ID: "edge_ticket_prompt_confirm", Source: "ticket_confirm_prompt_1", Target: "ticket_confirm_1"},
|
{ID: "edge_ticket_prompt_confirm", Source: "ticket_confirm_prompt_1", Target: "ticket_confirm_1"},
|
||||||
{ID: "edge_ticket_confirm_create", Source: "ticket_confirm_1", Target: "create_ticket_1", Condition: &dsl.Condition{
|
{ID: "edge_ticket_confirm_route", Source: "ticket_confirm_1", Target: "ticket_confirm_route_1"},
|
||||||
Left: &dsl.VariableSelector{NodeID: "ticket_confirm_1", Field: "confirmed"},
|
{ID: "edge_ticket_confirm_create", Source: "ticket_confirm_route_1", Target: "create_ticket_1"},
|
||||||
Operator: "is_true",
|
{ID: "edge_ticket_confirm_cancel", Source: "ticket_confirm_route_1", Target: "ticket_cancel_reply_1"},
|
||||||
}},
|
|
||||||
{ID: "edge_ticket_confirm_cancel", Source: "ticket_confirm_1", Target: "ticket_cancel_reply_1"},
|
|
||||||
{ID: "edge_create_ticket_result", Source: "create_ticket_1", Target: "ticket_result_reply_1"},
|
{ID: "edge_create_ticket_result", Source: "create_ticket_1", Target: "ticket_result_reply_1"},
|
||||||
{ID: "edge_ticket_result_end", Source: "ticket_result_reply_1", Target: "end_1"},
|
{ID: "edge_ticket_result_end", Source: "ticket_result_reply_1", Target: "end_1"},
|
||||||
{ID: "edge_ticket_cancel_send", Source: "ticket_cancel_reply_1", Target: "send_ticket_cancel_1"},
|
{ID: "edge_ticket_cancel_send", Source: "ticket_cancel_reply_1", Target: "send_ticket_cancel_1"},
|
||||||
{ID: "edge_ticket_cancel_end", Source: "send_ticket_cancel_1", Target: "end_1"},
|
{ID: "edge_ticket_cancel_end", Source: "send_ticket_cancel_1", Target: "end_1"},
|
||||||
{ID: "edge_retrieve_answerability", Source: "retrieve_1", Target: "answerability_1"},
|
{ID: "edge_retrieve_answerability", Source: "retrieve_1", Target: "answerability_1"},
|
||||||
{ID: "edge_answerability_reply", Source: "answerability_1", Target: "reply_1", Condition: &dsl.Condition{
|
{ID: "edge_answerability_route", Source: "answerability_1", Target: "answerability_route_1"},
|
||||||
Left: &dsl.VariableSelector{NodeID: "answerability_1", Field: "answerability"},
|
{ID: "edge_answerability_reply", Source: "answerability_route_1", Target: "reply_1"},
|
||||||
Operator: "eq",
|
{ID: "edge_answerability_fallback", Source: "answerability_route_1", Target: "fallback_reply_1"},
|
||||||
Right: "answerable",
|
|
||||||
}},
|
|
||||||
{ID: "edge_answerability_fallback", Source: "answerability_1", Target: "fallback_reply_1"},
|
|
||||||
{ID: "edge_reply_send", Source: "reply_1", Target: "send_1"},
|
{ID: "edge_reply_send", Source: "reply_1", Target: "send_1"},
|
||||||
{ID: "edge_fallback_send", Source: "fallback_reply_1", Target: "send_fallback_1"},
|
{ID: "edge_fallback_send", Source: "fallback_reply_1", Target: "send_fallback_1"},
|
||||||
{ID: "edge_send_end", Source: "send_1", Target: "end_1"},
|
{ID: "edge_send_end", Source: "send_1", Target: "end_1"},
|
||||||
@@ -527,6 +518,14 @@ func defaultAgentWorkflowDefinition() dsl.Definition {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func mustMarshalWorkflowConfig(value any) json.RawMessage {
|
||||||
|
raw, err := json.Marshal(value)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return raw
|
||||||
|
}
|
||||||
|
|
||||||
func defaultAgentWorkflowName(agentName string) string {
|
func defaultAgentWorkflowName(agentName string) string {
|
||||||
agentName = strings.TrimSpace(agentName)
|
agentName = strings.TrimSpace(agentName)
|
||||||
if agentName == "" {
|
if agentName == "" {
|
||||||
|
|||||||
@@ -7,9 +7,12 @@ import { Button } from "@/components/ui/button"
|
|||||||
import { Input } from "@/components/ui/input"
|
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 { OptionCombobox } from "@/components/option-combobox"
|
||||||
import { VariableSelector } from "./variable-selector"
|
import { VariableSelector } from "./variable-selector"
|
||||||
import type {
|
import type {
|
||||||
|
WorkflowConditionBranch,
|
||||||
WorkflowNodeSpec,
|
WorkflowNodeSpec,
|
||||||
|
WorkflowNodeConfig,
|
||||||
WorkflowVariableRef,
|
WorkflowVariableRef,
|
||||||
WorkflowVariableSpec,
|
WorkflowVariableSpec,
|
||||||
WorkflowVariableSelector,
|
WorkflowVariableSelector,
|
||||||
@@ -18,28 +21,36 @@ import type {
|
|||||||
type WorkflowNodeData = Record<string, unknown> & {
|
type WorkflowNodeData = Record<string, unknown> & {
|
||||||
nodeType?: string
|
nodeType?: string
|
||||||
name?: string
|
name?: string
|
||||||
config?: Record<string, unknown>
|
config?: WorkflowNodeConfig
|
||||||
inputs?: Record<string, WorkflowVariableSelector>
|
inputs?: Record<string, WorkflowVariableSelector>
|
||||||
}
|
}
|
||||||
|
|
||||||
export type WorkflowBranchSummary = {
|
export type WorkflowBranchSummary = {
|
||||||
edgeId: string
|
branchId: string
|
||||||
|
targetNodeId: string
|
||||||
targetName: string
|
targetName: string
|
||||||
conditionLabel: string
|
conditionLabel: string
|
||||||
isDefault: boolean
|
isDefault: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type WorkflowBranchTargetOption = {
|
||||||
|
value: string
|
||||||
|
label: string
|
||||||
|
}
|
||||||
|
|
||||||
export function NodeConfigPanel({
|
export function NodeConfigPanel({
|
||||||
node,
|
node,
|
||||||
nodeSpec,
|
nodeSpec,
|
||||||
availableVariables,
|
availableVariables,
|
||||||
branchSummaries = [],
|
branchSummaries = [],
|
||||||
|
branchTargetOptions = [],
|
||||||
onChange,
|
onChange,
|
||||||
}: {
|
}: {
|
||||||
node: Node<WorkflowNodeData> | null
|
node: Node<WorkflowNodeData> | null
|
||||||
nodeSpec?: WorkflowNodeSpec
|
nodeSpec?: WorkflowNodeSpec
|
||||||
availableVariables: WorkflowVariableRef[]
|
availableVariables: WorkflowVariableRef[]
|
||||||
branchSummaries?: WorkflowBranchSummary[]
|
branchSummaries?: WorkflowBranchSummary[]
|
||||||
|
branchTargetOptions?: WorkflowBranchTargetOption[]
|
||||||
onChange: (nodeId: string, data: WorkflowNodeData) => void
|
onChange: (nodeId: string, data: WorkflowNodeData) => void
|
||||||
}) {
|
}) {
|
||||||
if (!node) {
|
if (!node) {
|
||||||
@@ -57,6 +68,7 @@ export function NodeConfigPanel({
|
|||||||
nodeSpec={nodeSpec}
|
nodeSpec={nodeSpec}
|
||||||
availableVariables={availableVariables}
|
availableVariables={availableVariables}
|
||||||
branchSummaries={branchSummaries}
|
branchSummaries={branchSummaries}
|
||||||
|
branchTargetOptions={branchTargetOptions}
|
||||||
onChange={onChange}
|
onChange={onChange}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
@@ -67,12 +79,14 @@ function NodeConfigForm({
|
|||||||
nodeSpec,
|
nodeSpec,
|
||||||
availableVariables,
|
availableVariables,
|
||||||
branchSummaries,
|
branchSummaries,
|
||||||
|
branchTargetOptions,
|
||||||
onChange,
|
onChange,
|
||||||
}: {
|
}: {
|
||||||
node: Node<WorkflowNodeData>
|
node: Node<WorkflowNodeData>
|
||||||
nodeSpec?: WorkflowNodeSpec
|
nodeSpec?: WorkflowNodeSpec
|
||||||
availableVariables: WorkflowVariableRef[]
|
availableVariables: WorkflowVariableRef[]
|
||||||
branchSummaries: WorkflowBranchSummary[]
|
branchSummaries: WorkflowBranchSummary[]
|
||||||
|
branchTargetOptions: WorkflowBranchTargetOption[]
|
||||||
onChange: (nodeId: string, data: WorkflowNodeData) => void
|
onChange: (nodeId: string, data: WorkflowNodeData) => void
|
||||||
}) {
|
}) {
|
||||||
const [name, setName] = useState(node.data.name ?? "")
|
const [name, setName] = useState(node.data.name ?? "")
|
||||||
@@ -121,7 +135,14 @@ function NodeConfigForm({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{isConditionNode ? (
|
{isConditionNode ? (
|
||||||
<ConditionNodePanel branchSummaries={branchSummaries} outputSchema={outputSchema} />
|
<ConditionNodePanel
|
||||||
|
branches={node.data.config?.branches ?? []}
|
||||||
|
branchSummaries={branchSummaries}
|
||||||
|
branchTargetOptions={branchTargetOptions}
|
||||||
|
availableVariables={availableVariables}
|
||||||
|
outputSchema={outputSchema}
|
||||||
|
onChange={(branches) => commitChange({ config: { ...(node.data.config ?? {}), branches } })}
|
||||||
|
/>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
{inputSchema.length > 0 ? (
|
{inputSchema.length > 0 ? (
|
||||||
@@ -207,38 +228,161 @@ function NodeConfigForm({
|
|||||||
}
|
}
|
||||||
|
|
||||||
function ConditionNodePanel({
|
function ConditionNodePanel({
|
||||||
|
branches,
|
||||||
branchSummaries,
|
branchSummaries,
|
||||||
|
branchTargetOptions,
|
||||||
|
availableVariables,
|
||||||
outputSchema,
|
outputSchema,
|
||||||
|
onChange,
|
||||||
}: {
|
}: {
|
||||||
|
branches: WorkflowConditionBranch[]
|
||||||
branchSummaries: WorkflowBranchSummary[]
|
branchSummaries: WorkflowBranchSummary[]
|
||||||
|
branchTargetOptions: WorkflowBranchTargetOption[]
|
||||||
|
availableVariables: WorkflowVariableRef[]
|
||||||
outputSchema: WorkflowVariableSpec[]
|
outputSchema: WorkflowVariableSpec[]
|
||||||
|
onChange: (branches: WorkflowConditionBranch[]) => void
|
||||||
}) {
|
}) {
|
||||||
|
const summariesByBranchID = new Map(branchSummaries.map((item) => [item.branchId, item]))
|
||||||
|
const commitBranch = (branchId: string, patch: Partial<WorkflowConditionBranch>) => {
|
||||||
|
onChange(branches.map((branch) => (
|
||||||
|
branch.id === branchId ? normalizeBranch({ ...branch, ...patch }) : branch
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
const addBranch = () => {
|
||||||
|
const index = branches.length + 1
|
||||||
|
onChange([
|
||||||
|
...branches,
|
||||||
|
{
|
||||||
|
id: `branch_${index}`,
|
||||||
|
name: `分支 ${index}`,
|
||||||
|
targetNodeId: branchTargetOptions[0]?.value ?? "",
|
||||||
|
condition: { operator: "eq" },
|
||||||
|
},
|
||||||
|
])
|
||||||
|
}
|
||||||
|
const deleteBranch = (branchId: string) => {
|
||||||
|
onChange(branches.filter((branch) => branch.id !== branchId))
|
||||||
|
}
|
||||||
|
const markDefault = (branchId: string) => {
|
||||||
|
onChange(branches.map((branch) => normalizeBranch({
|
||||||
|
...branch,
|
||||||
|
default: branch.id === branchId,
|
||||||
|
condition: branch.id === branchId ? undefined : branch.condition ?? { operator: "eq" },
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{/* <div className="rounded-md border bg-muted/30 p-3 text-xs text-muted-foreground">
|
|
||||||
条件节点只负责分流;每条出口连线承载自己的判断条件,没有条件的出口会作为默认分支。
|
|
||||||
</div> */}
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<div className="text-sm font-medium">出口分支</div>
|
<div className="flex items-center justify-between gap-2">
|
||||||
{branchSummaries.length > 0 ? (
|
<div className="text-sm font-medium">分支</div>
|
||||||
|
<Button type="button" variant="outline" size="sm" onClick={addBranch}>
|
||||||
|
添加分支
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{branches.length > 0 ? (
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
{branchSummaries.map((branch) => (
|
{branches.map((branch, index) => {
|
||||||
<div key={branch.edgeId} className="rounded-md border bg-background p-2">
|
const summary = summariesByBranchID.get(branch.id)
|
||||||
<div className="flex items-center justify-between gap-2 text-xs">
|
const condition = branch.condition ?? {}
|
||||||
<span className="min-w-0 truncate font-medium">{branch.targetName}</span>
|
const conditionRight = condition.right === undefined || condition.right === null
|
||||||
<span className="shrink-0 rounded-sm bg-muted px-1.5 py-0.5 text-muted-foreground">
|
? ""
|
||||||
{branch.isDefault ? "默认" : "条件"}
|
: String(condition.right)
|
||||||
</span>
|
return (
|
||||||
|
<div key={branch.id} className="space-y-3 rounded-md border bg-background p-3">
|
||||||
|
<div className="flex items-center justify-between gap-2 text-xs">
|
||||||
|
<span className="min-w-0 truncate font-medium">
|
||||||
|
{branch.default ? "ELSE" : index === 0 ? "IF" : "ELSE IF"}
|
||||||
|
</span>
|
||||||
|
<span className="shrink-0 rounded-sm bg-muted px-1.5 py-0.5 text-muted-foreground">
|
||||||
|
{branch.default ? "默认" : "条件"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-xs">分支名称</Label>
|
||||||
|
<Input
|
||||||
|
value={branch.name ?? ""}
|
||||||
|
onChange={(event) => commitBranch(branch.id, { name: event.target.value })}
|
||||||
|
placeholder="例如:需要转人工"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-xs">目标节点</Label>
|
||||||
|
<OptionCombobox
|
||||||
|
value={branch.targetNodeId}
|
||||||
|
options={branchTargetOptions}
|
||||||
|
placeholder="选择目标节点"
|
||||||
|
searchPlaceholder="搜索目标节点"
|
||||||
|
emptyText="请先从条件节点连出下游节点"
|
||||||
|
onChange={(value) => commitBranch(branch.id, { targetNodeId: value })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{branch.default ? (
|
||||||
|
<div className="rounded-md border border-dashed p-2 text-xs text-muted-foreground">
|
||||||
|
未命中上方条件时进入:{summary?.targetName ?? (branch.targetNodeId || "未选择目标节点")}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-3 rounded-md border bg-muted/20 p-2">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-xs">判断变量</Label>
|
||||||
|
<VariableSelector
|
||||||
|
value={condition.left}
|
||||||
|
variables={availableVariables}
|
||||||
|
onChange={(value) => commitBranch(branch.id, {
|
||||||
|
condition: { ...condition, left: value },
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-xs">判断方式</Label>
|
||||||
|
<OptionCombobox
|
||||||
|
value={condition.operator ?? "eq"}
|
||||||
|
options={conditionOperators}
|
||||||
|
placeholder="选择判断方式"
|
||||||
|
searchPlaceholder="搜索判断方式"
|
||||||
|
emptyText="没有可用判断方式"
|
||||||
|
onChange={(value) => commitBranch(branch.id, {
|
||||||
|
condition: { ...condition, operator: value },
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{!conditionOperatorWithoutRight(condition.operator ?? "eq") ? (
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-xs">比较值</Label>
|
||||||
|
<Input
|
||||||
|
value={conditionRight}
|
||||||
|
onChange={(event) => commitBranch(branch.id, {
|
||||||
|
condition: {
|
||||||
|
...condition,
|
||||||
|
right: normalizeConditionRight(event.target.value),
|
||||||
|
},
|
||||||
|
})}
|
||||||
|
placeholder="请输入比较值"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{!branch.default ? (
|
||||||
|
<Button type="button" size="sm" variant="outline" onClick={() => markDefault(branch.id)}>
|
||||||
|
设为默认
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
<Button type="button" size="sm" variant="outline" onClick={() => deleteBranch(branch.id)}>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div className="line-clamp-2 text-xs text-muted-foreground">
|
||||||
|
{summary?.conditionLabel ?? "尚未完成分支配置"}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-1 line-clamp-2 text-xs text-muted-foreground">
|
)
|
||||||
{branch.conditionLabel}
|
})}
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="rounded-md border border-dashed p-2 text-xs text-muted-foreground">
|
<div className="rounded-md border border-dashed p-2 text-xs text-muted-foreground">
|
||||||
当前还没有出口连线。
|
当前还没有分支。
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -263,3 +407,40 @@ function ConditionNodePanel({
|
|||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const conditionOperators = [
|
||||||
|
{ value: "eq", label: "等于" },
|
||||||
|
{ value: "neq", label: "不等于" },
|
||||||
|
{ value: "contains", label: "包含" },
|
||||||
|
{ value: "exists", label: "存在" },
|
||||||
|
{ value: "not_exists", label: "不存在" },
|
||||||
|
{ value: "truthy", label: "为真" },
|
||||||
|
{ value: "falsy", label: "为假" },
|
||||||
|
{ value: "gt", label: "大于" },
|
||||||
|
{ value: "gte", label: "大于等于" },
|
||||||
|
{ value: "lt", label: "小于" },
|
||||||
|
{ value: "lte", label: "小于等于" },
|
||||||
|
]
|
||||||
|
|
||||||
|
function conditionOperatorWithoutRight(operator: string) {
|
||||||
|
return ["exists", "not_exists", "truthy", "falsy"].includes(operator)
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeConditionRight(value: string) {
|
||||||
|
const trimmed = value.trim()
|
||||||
|
if (trimmed === "true") return true
|
||||||
|
if (trimmed === "false") return false
|
||||||
|
if (trimmed !== "" && !Number.isNaN(Number(trimmed))) return Number(trimmed)
|
||||||
|
return trimmed
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeBranch(branch: WorkflowConditionBranch): WorkflowConditionBranch {
|
||||||
|
if (branch.default) {
|
||||||
|
const { condition: _condition, ...rest } = branch
|
||||||
|
return rest
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...branch,
|
||||||
|
condition: branch.condition ?? { operator: "eq" },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import {
|
|||||||
Background,
|
Background,
|
||||||
BaseEdge,
|
BaseEdge,
|
||||||
ConnectionMode,
|
ConnectionMode,
|
||||||
EdgeLabelRenderer,
|
|
||||||
Controls,
|
Controls,
|
||||||
getBezierPath,
|
getBezierPath,
|
||||||
Handle,
|
Handle,
|
||||||
@@ -44,9 +43,6 @@ import {
|
|||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
import { Input } from "@/components/ui/input"
|
|
||||||
import { Label } from "@/components/ui/label"
|
|
||||||
import { OptionCombobox } from "@/components/option-combobox"
|
|
||||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||||
import {
|
import {
|
||||||
Popover,
|
Popover,
|
||||||
@@ -69,20 +65,19 @@ import {
|
|||||||
toApiDefinition,
|
toApiDefinition,
|
||||||
undoWorkflowHistory,
|
undoWorkflowHistory,
|
||||||
validateWorkflowDraft,
|
validateWorkflowDraft,
|
||||||
type WorkflowVariableRef,
|
type WorkflowCondition,
|
||||||
type WorkflowVariableSelector,
|
|
||||||
type WorkflowEditorEdge,
|
|
||||||
type WorkflowEditorNode,
|
type WorkflowEditorNode,
|
||||||
type WorkflowHistory,
|
type WorkflowHistory,
|
||||||
type WorkflowHelperLine,
|
type WorkflowHelperLine,
|
||||||
|
type WorkflowNodeConfig,
|
||||||
} from "./workflow-utils"
|
} from "./workflow-utils"
|
||||||
import { NodeConfigPanel, type WorkflowBranchSummary } from "./node-config-panel"
|
import { NodeConfigPanel, type WorkflowBranchSummary } from "./node-config-panel"
|
||||||
import { VariableSelector } from "./variable-selector"
|
import type { WorkflowBranchTargetOption } from "./node-config-panel"
|
||||||
|
|
||||||
type WorkflowNodeData = Record<string, unknown> & {
|
type WorkflowNodeData = Record<string, unknown> & {
|
||||||
nodeType?: string
|
nodeType?: string
|
||||||
name?: string
|
name?: string
|
||||||
config?: Record<string, unknown>
|
config?: WorkflowNodeConfig
|
||||||
inputs?: Record<string, { nodeId: string; field: string }>
|
inputs?: Record<string, { nodeId: string; field: string }>
|
||||||
nodeSpecs?: AIWorkflowNodeSpec[]
|
nodeSpecs?: AIWorkflowNodeSpec[]
|
||||||
onAddAfter?: (sourceNodeId: string, spec: AIWorkflowNodeSpec) => void
|
onAddAfter?: (sourceNodeId: string, spec: AIWorkflowNodeSpec) => void
|
||||||
@@ -100,10 +95,8 @@ type WorkflowEditorSnapshot = {
|
|||||||
nodes: WorkflowFlowNode[]
|
nodes: WorkflowFlowNode[]
|
||||||
edges: WorkflowFlowEdge[]
|
edges: WorkflowFlowEdge[]
|
||||||
}
|
}
|
||||||
type WorkflowEdgeCondition = NonNullable<WorkflowEditorEdge["data"]>["condition"]
|
type WorkflowEdgeRenderData = {
|
||||||
type WorkflowEdgeRenderData = WorkflowEditorEdge["data"] & {
|
|
||||||
active?: boolean
|
active?: boolean
|
||||||
onSelect?: (edgeId: string) => void
|
|
||||||
}
|
}
|
||||||
type WorkflowFinalConnectionState = FinalConnectionState
|
type WorkflowFinalConnectionState = FinalConnectionState
|
||||||
|
|
||||||
@@ -163,8 +156,6 @@ function toFlowEdges(definition: AIWorkflowDefinition): WorkflowFlowEdge[] {
|
|||||||
type: "workflowEdge",
|
type: "workflowEdge",
|
||||||
source: edge.source,
|
source: edge.source,
|
||||||
target: edge.target,
|
target: edge.target,
|
||||||
label: edge.condition ? "条件" : undefined,
|
|
||||||
data: edge.condition ? { condition: edge.condition } : undefined,
|
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,7 +176,6 @@ function toDraft(nodes: WorkflowFlowNode[], edges: WorkflowFlowEdge[]) {
|
|||||||
id: edge.id,
|
id: edge.id,
|
||||||
source: edge.source,
|
source: edge.source,
|
||||||
target: edge.target,
|
target: edge.target,
|
||||||
data: edge.data as WorkflowEditorEdge["data"],
|
|
||||||
})),
|
})),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -231,7 +221,6 @@ export function WorkflowEditor({
|
|||||||
const [helperLines, setHelperLines] = useState<WorkflowHelperLine>({})
|
const [helperLines, setHelperLines] = useState<WorkflowHelperLine>({})
|
||||||
const [propertyPanelNode, setPropertyPanelNode] = useState<WorkflowFlowNode | null>(null)
|
const [propertyPanelNode, setPropertyPanelNode] = useState<WorkflowFlowNode | null>(null)
|
||||||
const [selectedEdgeId, setSelectedEdgeId] = useState<string | null>(null)
|
const [selectedEdgeId, setSelectedEdgeId] = useState<string | null>(null)
|
||||||
const [propertyPanelEdge, setPropertyPanelEdge] = useState<WorkflowFlowEdge | null>(null)
|
|
||||||
const [propertyPanelVisible, setPropertyPanelVisible] = useState(false)
|
const [propertyPanelVisible, setPropertyPanelVisible] = useState(false)
|
||||||
const editorRef = useRef<HTMLDivElement | null>(null)
|
const editorRef = useRef<HTMLDivElement | null>(null)
|
||||||
const canvasRef = useRef<HTMLElement | null>(null)
|
const canvasRef = useRef<HTMLElement | null>(null)
|
||||||
@@ -259,14 +248,13 @@ export function WorkflowEditor({
|
|||||||
[draft, nodeSpecs, propertyPanelNode]
|
[draft, nodeSpecs, propertyPanelNode]
|
||||||
)
|
)
|
||||||
const propertyPanelBranchSummaries = useMemo(
|
const propertyPanelBranchSummaries = useMemo(
|
||||||
() => (propertyPanelNode ? getBranchSummaries(nodes, edges, propertyPanelNode.id) : []),
|
() => (propertyPanelNode ? getBranchSummaries(nodes, propertyPanelNode.id) : []),
|
||||||
|
[nodes, propertyPanelNode]
|
||||||
|
)
|
||||||
|
const propertyPanelBranchTargetOptions = useMemo(
|
||||||
|
() => (propertyPanelNode ? getBranchTargetOptions(nodes, edges, propertyPanelNode.id) : []),
|
||||||
[edges, nodes, propertyPanelNode]
|
[edges, nodes, propertyPanelNode]
|
||||||
)
|
)
|
||||||
const propertyPanelEdgeVariables = useMemo(
|
|
||||||
() => (propertyPanelEdge ? getEdgeConditionVariables(draft, propertyPanelEdge.source, nodeSpecs) : []),
|
|
||||||
[draft, nodeSpecs, propertyPanelEdge]
|
|
||||||
)
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
onDefinitionChange(toApiDefinition(draft) as AIWorkflowDefinition)
|
onDefinitionChange(toApiDefinition(draft) as AIWorkflowDefinition)
|
||||||
}, [draft, onDefinitionChange])
|
}, [draft, onDefinitionChange])
|
||||||
@@ -311,19 +299,6 @@ export function WorkflowEditor({
|
|||||||
window.clearTimeout(propertyPanelAnimationTimerRef.current)
|
window.clearTimeout(propertyPanelAnimationTimerRef.current)
|
||||||
}
|
}
|
||||||
setPropertyPanelNode(node)
|
setPropertyPanelNode(node)
|
||||||
setPropertyPanelEdge(null)
|
|
||||||
propertyPanelAnimationTimerRef.current = window.setTimeout(() => {
|
|
||||||
setPropertyPanelVisible(true)
|
|
||||||
propertyPanelAnimationTimerRef.current = null
|
|
||||||
}, 0)
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
const showPropertyPanelEdge = useCallback((edge: WorkflowFlowEdge) => {
|
|
||||||
if (propertyPanelAnimationTimerRef.current !== null) {
|
|
||||||
window.clearTimeout(propertyPanelAnimationTimerRef.current)
|
|
||||||
}
|
|
||||||
setPropertyPanelEdge(edge)
|
|
||||||
setPropertyPanelNode(null)
|
|
||||||
propertyPanelAnimationTimerRef.current = window.setTimeout(() => {
|
propertyPanelAnimationTimerRef.current = window.setTimeout(() => {
|
||||||
setPropertyPanelVisible(true)
|
setPropertyPanelVisible(true)
|
||||||
propertyPanelAnimationTimerRef.current = null
|
propertyPanelAnimationTimerRef.current = null
|
||||||
@@ -337,7 +312,6 @@ export function WorkflowEditor({
|
|||||||
setPropertyPanelVisible(false)
|
setPropertyPanelVisible(false)
|
||||||
propertyPanelAnimationTimerRef.current = window.setTimeout(() => {
|
propertyPanelAnimationTimerRef.current = window.setTimeout(() => {
|
||||||
setPropertyPanelNode(null)
|
setPropertyPanelNode(null)
|
||||||
setPropertyPanelEdge(null)
|
|
||||||
propertyPanelAnimationTimerRef.current = null
|
propertyPanelAnimationTimerRef.current = null
|
||||||
}, 220)
|
}, 220)
|
||||||
}, [])
|
}, [])
|
||||||
@@ -377,9 +351,6 @@ export function WorkflowEditor({
|
|||||||
setPropertyPanelNode((current) =>
|
setPropertyPanelNode((current) =>
|
||||||
current ? snapshot.nodes.find((node) => node.id === current.id) ?? null : null
|
current ? snapshot.nodes.find((node) => node.id === current.id) ?? null : null
|
||||||
)
|
)
|
||||||
setPropertyPanelEdge((current) =>
|
|
||||||
current ? snapshot.edges.find((edge) => edge.id === current.id) ?? null : null
|
|
||||||
)
|
|
||||||
},
|
},
|
||||||
[setEdges, setNodes]
|
[setEdges, setNodes]
|
||||||
)
|
)
|
||||||
@@ -733,15 +704,6 @@ export function WorkflowEditor({
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const selectEdge = useCallback((edgeId: string) => {
|
|
||||||
const edge = edges.find((item) => item.id === edgeId)
|
|
||||||
if (!edge) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
setSelectedEdgeId(edgeId)
|
|
||||||
showPropertyPanelEdge(edge)
|
|
||||||
}, [edges, showPropertyPanelEdge])
|
|
||||||
|
|
||||||
const renderedEdges = useMemo(
|
const renderedEdges = useMemo(
|
||||||
() =>
|
() =>
|
||||||
edges.map((edge) => {
|
edges.map((edge) => {
|
||||||
@@ -750,34 +712,13 @@ export function WorkflowEditor({
|
|||||||
...edge,
|
...edge,
|
||||||
selected: active,
|
selected: active,
|
||||||
data: {
|
data: {
|
||||||
...((edge.data ?? {}) as WorkflowEditorEdge["data"]),
|
|
||||||
active,
|
active,
|
||||||
onSelect: selectEdge,
|
|
||||||
} satisfies WorkflowEdgeRenderData,
|
} satisfies WorkflowEdgeRenderData,
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
[edges, selectedEdgeId, selectEdge]
|
[edges, selectedEdgeId]
|
||||||
)
|
)
|
||||||
|
|
||||||
const updateEdgeCondition = (edgeId: string, condition?: WorkflowEdgeCondition) => {
|
|
||||||
pushCurrentSnapshotToHistory()
|
|
||||||
const updateEdge = (edge: WorkflowFlowEdge) => ({
|
|
||||||
...edge,
|
|
||||||
label: condition ? "条件" : undefined,
|
|
||||||
data: condition ? { ...(edge.data as object), condition } : undefined,
|
|
||||||
})
|
|
||||||
setEdges((current) =>
|
|
||||||
current.map((edge) =>
|
|
||||||
edge.id === edgeId
|
|
||||||
? updateEdge(edge)
|
|
||||||
: edge
|
|
||||||
)
|
|
||||||
)
|
|
||||||
setPropertyPanelEdge((current) =>
|
|
||||||
current?.id === edgeId ? updateEdge(current) : current
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const clampNodeLibraryWidth = useCallback((width: number) => {
|
const clampNodeLibraryWidth = useCallback((width: number) => {
|
||||||
const containerWidth = editorRef.current?.getBoundingClientRect().width ?? 0
|
const containerWidth = editorRef.current?.getBoundingClientRect().width ?? 0
|
||||||
const maxWidth = containerWidth > 0 ? containerWidth * 0.34 : 520
|
const maxWidth = containerWidth > 0 ? containerWidth * 0.34 : 520
|
||||||
@@ -936,7 +877,7 @@ export function WorkflowEditor({
|
|||||||
}}
|
}}
|
||||||
onEdgeClick={(event, edge) => {
|
onEdgeClick={(event, edge) => {
|
||||||
event.stopPropagation()
|
event.stopPropagation()
|
||||||
selectEdge(edge.id)
|
setSelectedEdgeId(edge.id)
|
||||||
}}
|
}}
|
||||||
onPaneClick={() => {
|
onPaneClick={() => {
|
||||||
setSelectedEdgeId(null)
|
setSelectedEdgeId(null)
|
||||||
@@ -977,7 +918,7 @@ export function WorkflowEditor({
|
|||||||
restoreDefaultDisabled={restoreDefaultDisabled}
|
restoreDefaultDisabled={restoreDefaultDisabled}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{propertyPanelNode || propertyPanelEdge ? (
|
{propertyPanelNode ? (
|
||||||
<aside
|
<aside
|
||||||
className={[
|
className={[
|
||||||
"absolute top-3 right-3 z-30 h-[calc(100%-1.5rem)] w-[min(380px,calc(100%-1.5rem))] overflow-hidden rounded-md border bg-background shadow-lg transition-all duration-200 ease-out",
|
"absolute top-3 right-3 z-30 h-[calc(100%-1.5rem)] w-[min(380px,calc(100%-1.5rem))] overflow-hidden rounded-md border bg-background shadow-lg transition-all duration-200 ease-out",
|
||||||
@@ -993,16 +934,10 @@ export function WorkflowEditor({
|
|||||||
nodeSpec={propertyPanelNodeSpec}
|
nodeSpec={propertyPanelNodeSpec}
|
||||||
availableVariables={propertyPanelAvailableVariables}
|
availableVariables={propertyPanelAvailableVariables}
|
||||||
branchSummaries={propertyPanelBranchSummaries}
|
branchSummaries={propertyPanelBranchSummaries}
|
||||||
|
branchTargetOptions={propertyPanelBranchTargetOptions}
|
||||||
onChange={updateNodeData}
|
onChange={updateNodeData}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
{propertyPanelEdge ? (
|
|
||||||
<EdgeConditionPanel
|
|
||||||
edge={propertyPanelEdge}
|
|
||||||
variables={propertyPanelEdgeVariables}
|
|
||||||
onChange={updateEdgeCondition}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
{!validation.valid ? (
|
{!validation.valid ? (
|
||||||
<div className="border-t p-4">
|
<div className="border-t p-4">
|
||||||
<div className="mb-2 text-sm font-medium">流程检查</div>
|
<div className="mb-2 text-sm font-medium">流程检查</div>
|
||||||
@@ -1067,30 +1002,6 @@ function enrichNodesForRender(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
function getEdgeConditionVariables(
|
|
||||||
draft: ReturnType<typeof toDraft>,
|
|
||||||
sourceNodeId: string,
|
|
||||||
nodeSpecs: AIWorkflowNodeSpec[]
|
|
||||||
): WorkflowVariableRef[] {
|
|
||||||
const variables = getAvailableVariables(draft, sourceNodeId, nodeSpecs)
|
|
||||||
const sourceNode = draft.nodes.find((node) => node.id === sourceNodeId)
|
|
||||||
if (!sourceNode) {
|
|
||||||
return variables
|
|
||||||
}
|
|
||||||
const nodeType = sourceNode.data?.nodeType ?? sourceNode.type ?? ""
|
|
||||||
const spec = getNodeSpec(nodeSpecs, nodeType)
|
|
||||||
for (const output of spec?.outputSchema ?? []) {
|
|
||||||
variables.push({
|
|
||||||
nodeId: sourceNode.id,
|
|
||||||
nodeName: sourceNode.data?.name ?? spec?.title ?? sourceNode.id,
|
|
||||||
field: output.name,
|
|
||||||
type: output.type,
|
|
||||||
description: output.description ?? "",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return variables
|
|
||||||
}
|
|
||||||
|
|
||||||
const conditionOperators = [
|
const conditionOperators = [
|
||||||
{ value: "eq", label: "等于" },
|
{ value: "eq", label: "等于" },
|
||||||
{ value: "neq", label: "不等于" },
|
{ value: "neq", label: "不等于" },
|
||||||
@@ -1107,24 +1018,40 @@ const conditionOperators = [
|
|||||||
|
|
||||||
function getBranchSummaries(
|
function getBranchSummaries(
|
||||||
nodes: WorkflowFlowNode[],
|
nodes: WorkflowFlowNode[],
|
||||||
edges: WorkflowFlowEdge[],
|
|
||||||
nodeId: string
|
nodeId: string
|
||||||
): WorkflowBranchSummary[] {
|
): WorkflowBranchSummary[] {
|
||||||
return edges
|
const node = nodes.find((item) => item.id === nodeId)
|
||||||
.filter((edge) => edge.source === nodeId)
|
const branches = node?.data.config?.branches ?? []
|
||||||
.map((edge) => {
|
return branches
|
||||||
const target = nodes.find((node) => node.id === edge.target)
|
.map((branch) => {
|
||||||
const condition = (edge.data as WorkflowEditorEdge["data"] | undefined)?.condition
|
const target = nodes.find((item) => item.id === branch.targetNodeId)
|
||||||
return {
|
return {
|
||||||
edgeId: edge.id,
|
branchId: branch.id,
|
||||||
targetName: target?.data.name ?? target?.data.title ?? edge.target,
|
targetNodeId: branch.targetNodeId,
|
||||||
conditionLabel: condition ? formatConditionLabel(condition) : "无条件匹配",
|
targetName: target?.data.name ?? target?.data.title ?? branch.targetNodeId,
|
||||||
isDefault: !condition,
|
conditionLabel: branch.condition ? formatConditionLabel(branch.condition) : "无条件匹配",
|
||||||
|
isDefault: Boolean(branch.default),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatConditionLabel(condition: NonNullable<WorkflowEdgeCondition>) {
|
function getBranchTargetOptions(
|
||||||
|
nodes: WorkflowFlowNode[],
|
||||||
|
edges: WorkflowFlowEdge[],
|
||||||
|
nodeId: string
|
||||||
|
): WorkflowBranchTargetOption[] {
|
||||||
|
return edges
|
||||||
|
.filter((edge) => edge.source === nodeId)
|
||||||
|
.map((edge) => {
|
||||||
|
const target = nodes.find((node) => node.id === edge.target)
|
||||||
|
return {
|
||||||
|
value: edge.target,
|
||||||
|
label: target?.data.name ?? target?.data.title ?? edge.target,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatConditionLabel(condition: WorkflowCondition) {
|
||||||
const left = condition.left?.nodeId && condition.left.field
|
const left = condition.left?.nodeId && condition.left.field
|
||||||
? `${condition.left.nodeId}.${condition.left.field}`
|
? `${condition.left.nodeId}.${condition.left.field}`
|
||||||
: "未选择变量"
|
: "未选择变量"
|
||||||
@@ -1149,105 +1076,6 @@ function formatConditionRight(value: unknown) {
|
|||||||
return String(value)
|
return String(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
function EdgeConditionPanel({
|
|
||||||
edge,
|
|
||||||
variables,
|
|
||||||
onChange,
|
|
||||||
}: {
|
|
||||||
edge: WorkflowFlowEdge
|
|
||||||
variables: WorkflowVariableRef[]
|
|
||||||
onChange: (edgeId: string, condition?: WorkflowEdgeCondition) => void
|
|
||||||
}) {
|
|
||||||
const condition = (edge.data as WorkflowEditorEdge["data"] | undefined)?.condition
|
|
||||||
const [left, setLeft] = useState<WorkflowVariableSelector | undefined>(condition?.left)
|
|
||||||
const [operator, setOperator] = useState(condition?.operator ?? "eq")
|
|
||||||
const [right, setRight] = useState(condition?.right === undefined ? "" : String(condition.right))
|
|
||||||
|
|
||||||
const commit = (next?: {
|
|
||||||
left?: WorkflowVariableSelector
|
|
||||||
operator?: string
|
|
||||||
right?: string
|
|
||||||
}) => {
|
|
||||||
const nextLeft = next?.left ?? left
|
|
||||||
const nextOperator = next?.operator ?? operator
|
|
||||||
const nextRight = next?.right ?? right
|
|
||||||
if (!nextLeft?.nodeId || !nextLeft.field || !nextOperator) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
onChange(edge.id, {
|
|
||||||
left: nextLeft,
|
|
||||||
operator: nextOperator,
|
|
||||||
right: normalizeConditionRight(nextRight),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex h-full min-h-0 flex-col gap-4 p-4">
|
|
||||||
<div>
|
|
||||||
<div className="text-sm font-medium">分支条件</div>
|
|
||||||
<div className="mt-1 text-xs text-muted-foreground">
|
|
||||||
{edge.source} {"->"} {edge.target}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label>左侧变量</Label>
|
|
||||||
<VariableSelector
|
|
||||||
value={left}
|
|
||||||
variables={variables}
|
|
||||||
onChange={(value) => {
|
|
||||||
setLeft(value)
|
|
||||||
commit({ left: value })
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label>判断方式</Label>
|
|
||||||
<OptionCombobox
|
|
||||||
value={operator}
|
|
||||||
options={conditionOperators}
|
|
||||||
placeholder="选择判断方式"
|
|
||||||
searchPlaceholder="搜索判断方式"
|
|
||||||
emptyText="没有可用判断方式"
|
|
||||||
onChange={(value) => {
|
|
||||||
setOperator(value)
|
|
||||||
commit({ operator: value })
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
{!["exists", "not_exists", "truthy", "falsy"].includes(operator) ? (
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="workflow-edge-condition-right">比较值</Label>
|
|
||||||
<Input
|
|
||||||
id="workflow-edge-condition-right"
|
|
||||||
value={right}
|
|
||||||
onChange={(event) => setRight(event.target.value)}
|
|
||||||
onBlur={() => commit({ right })}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<Button type="button" size="sm" onClick={() => commit()}>
|
|
||||||
保存条件
|
|
||||||
</Button>
|
|
||||||
<Button type="button" size="sm" variant="outline" onClick={() => onChange(edge.id, undefined)}>
|
|
||||||
设为默认分支
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<div className="rounded-md border bg-muted/30 p-3 text-xs text-muted-foreground">
|
|
||||||
没有条件的边会作为默认分支;同一节点存在条件边时,建议保留一条默认分支。
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeConditionRight(value: string) {
|
|
||||||
const trimmed = value.trim()
|
|
||||||
if (trimmed === "true") return true
|
|
||||||
if (trimmed === "false") return false
|
|
||||||
if (trimmed !== "" && !Number.isNaN(Number(trimmed))) return Number(trimmed)
|
|
||||||
return trimmed
|
|
||||||
}
|
|
||||||
|
|
||||||
function getEventClientPoint(event: MouseEvent | TouchEvent) {
|
function getEventClientPoint(event: MouseEvent | TouchEvent) {
|
||||||
if ("changedTouches" in event) {
|
if ("changedTouches" in event) {
|
||||||
const touch = event.changedTouches[0] ?? event.touches[0]
|
const touch = event.changedTouches[0] ?? event.touches[0]
|
||||||
@@ -1334,7 +1162,7 @@ function WorkflowCanvasEdge({
|
|||||||
}: EdgeProps<WorkflowFlowEdge>) {
|
}: EdgeProps<WorkflowFlowEdge>) {
|
||||||
const sourceOffset = getEdgeEndpointOffset(sourcePosition, workflowHandleRadius)
|
const sourceOffset = getEdgeEndpointOffset(sourcePosition, workflowHandleRadius)
|
||||||
const targetOffset = getEdgeEndpointOffset(targetPosition, workflowHandleRadius)
|
const targetOffset = getEdgeEndpointOffset(targetPosition, workflowHandleRadius)
|
||||||
const [edgePath, labelX, labelY] = getBezierPath({
|
const [edgePath] = getBezierPath({
|
||||||
sourceX: sourceX + sourceOffset.x,
|
sourceX: sourceX + sourceOffset.x,
|
||||||
sourceY: sourceY + sourceOffset.y,
|
sourceY: sourceY + sourceOffset.y,
|
||||||
sourcePosition,
|
sourcePosition,
|
||||||
@@ -1343,54 +1171,19 @@ function WorkflowCanvasEdge({
|
|||||||
targetPosition,
|
targetPosition,
|
||||||
curvature: 0.18,
|
curvature: 0.18,
|
||||||
})
|
})
|
||||||
const condition = (data as WorkflowEditorEdge["data"] | undefined)?.condition
|
|
||||||
const edgeData = data as WorkflowEdgeRenderData | undefined
|
const edgeData = data as WorkflowEdgeRenderData | undefined
|
||||||
const active = selected || edgeData?.active
|
const active = selected || edgeData?.active
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<BaseEdge
|
||||||
<BaseEdge
|
id={id}
|
||||||
id={id}
|
path={edgePath}
|
||||||
path={edgePath}
|
markerEnd={markerEnd}
|
||||||
markerEnd={markerEnd}
|
className={cn(
|
||||||
className={cn(
|
"transition-all",
|
||||||
"transition-all",
|
active ? "!stroke-primary !stroke-[2.4px]" : "!stroke-muted-foreground/45 !stroke-[1.8px]"
|
||||||
active ? "!stroke-primary !stroke-[2.4px]" : "!stroke-muted-foreground/45 !stroke-[1.8px]"
|
)}
|
||||||
)}
|
/>
|
||||||
/>
|
|
||||||
{condition ? (
|
|
||||||
<EdgeLabelRenderer>
|
|
||||||
<div
|
|
||||||
role="button"
|
|
||||||
tabIndex={0}
|
|
||||||
aria-label="选择条件连接线"
|
|
||||||
className={cn(
|
|
||||||
"nodrag nopan pointer-events-auto absolute inline-flex -translate-x-1/2 -translate-y-1/2 cursor-pointer select-none items-center rounded-md border px-2 py-1 text-[11px] font-medium shadow-sm backdrop-blur transition-all",
|
|
||||||
active
|
|
||||||
? "border-primary bg-primary text-primary-foreground shadow-md"
|
|
||||||
: "border-border/80 bg-background/95 text-muted-foreground hover:border-primary/60 hover:text-foreground"
|
|
||||||
)}
|
|
||||||
style={{
|
|
||||||
transform: `translate(-50%, -50%) translate(${labelX}px, ${labelY}px)`,
|
|
||||||
}}
|
|
||||||
onClick={(event) => {
|
|
||||||
event.stopPropagation()
|
|
||||||
edgeData?.onSelect?.(id)
|
|
||||||
}}
|
|
||||||
onKeyDown={(event) => {
|
|
||||||
if (event.key !== "Enter" && event.key !== " ") {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
event.preventDefault()
|
|
||||||
event.stopPropagation()
|
|
||||||
edgeData?.onSelect?.(id)
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
条件
|
|
||||||
</div>
|
|
||||||
</EdgeLabelRenderer>
|
|
||||||
) : null}
|
|
||||||
</>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -320,6 +320,102 @@ describe("getAvailableVariables", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe("toApiDefinition", () => {
|
describe("toApiDefinition", () => {
|
||||||
|
it("keeps condition branches on the condition node config and exports plain edges", async () => {
|
||||||
|
const { toApiDefinition } = await loadModule()
|
||||||
|
|
||||||
|
const definition = toApiDefinition({
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "start_1",
|
||||||
|
type: "workflowNode",
|
||||||
|
position: { x: 0, y: 0 },
|
||||||
|
data: { nodeType: "start", name: "Start", config: {} },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "condition_1",
|
||||||
|
type: "workflowNode",
|
||||||
|
position: { x: 200, y: 0 },
|
||||||
|
data: {
|
||||||
|
nodeType: "condition",
|
||||||
|
name: "Route",
|
||||||
|
config: {
|
||||||
|
branches: [
|
||||||
|
{
|
||||||
|
id: "vip",
|
||||||
|
name: "VIP",
|
||||||
|
targetNodeId: "vip_reply",
|
||||||
|
condition: {
|
||||||
|
left: { nodeId: "start_1", field: "userMessage" },
|
||||||
|
operator: "eq",
|
||||||
|
right: "vip",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "default",
|
||||||
|
name: "Default",
|
||||||
|
targetNodeId: "normal_reply",
|
||||||
|
default: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "vip_reply",
|
||||||
|
type: "workflowNode",
|
||||||
|
position: { x: 400, y: 0 },
|
||||||
|
data: { nodeType: "llm_reply", name: "VIP", config: {} },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "normal_reply",
|
||||||
|
type: "workflowNode",
|
||||||
|
position: { x: 400, y: 160 },
|
||||||
|
data: { nodeType: "llm_reply", name: "Normal", config: {} },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
edges: [
|
||||||
|
{ id: "e1", source: "start_1", target: "condition_1" },
|
||||||
|
{
|
||||||
|
id: "e2",
|
||||||
|
source: "condition_1",
|
||||||
|
target: "vip_reply",
|
||||||
|
data: {
|
||||||
|
condition: {
|
||||||
|
left: { nodeId: "start_1", field: "userMessage" },
|
||||||
|
operator: "eq",
|
||||||
|
right: "legacy",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ id: "e3", source: "condition_1", target: "normal_reply" },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.deepEqual(plain(definition.edges), [
|
||||||
|
{ id: "e1", source: "start_1", target: "condition_1" },
|
||||||
|
{ id: "e2", source: "condition_1", target: "vip_reply" },
|
||||||
|
{ id: "e3", source: "condition_1", target: "normal_reply" },
|
||||||
|
])
|
||||||
|
assert.deepEqual(plain(definition.nodes[1].config.branches), [
|
||||||
|
{
|
||||||
|
id: "vip",
|
||||||
|
name: "VIP",
|
||||||
|
targetNodeId: "vip_reply",
|
||||||
|
condition: {
|
||||||
|
left: { nodeId: "start_1", field: "userMessage" },
|
||||||
|
operator: "eq",
|
||||||
|
right: "vip",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "default",
|
||||||
|
name: "Default",
|
||||||
|
targetNodeId: "normal_reply",
|
||||||
|
default: true,
|
||||||
|
},
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
it("preserves xyflow node positions", async () => {
|
it("preserves xyflow node positions", async () => {
|
||||||
const { toApiDefinition } = await loadModule()
|
const { toApiDefinition } = await loadModule()
|
||||||
|
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ export type WorkflowEditorNode = {
|
|||||||
nodeType?: string
|
nodeType?: string
|
||||||
name?: string
|
name?: string
|
||||||
label?: string
|
label?: string
|
||||||
config?: Record<string, unknown>
|
config?: WorkflowNodeConfig
|
||||||
inputs?: Record<string, WorkflowVariableSelector>
|
inputs?: Record<string, WorkflowVariableSelector>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -48,14 +48,25 @@ export type WorkflowEditorEdge = {
|
|||||||
id: string
|
id: string
|
||||||
source: string
|
source: string
|
||||||
target: string
|
target: string
|
||||||
data?: {
|
}
|
||||||
condition?: {
|
|
||||||
expression?: string
|
export type WorkflowCondition = {
|
||||||
left?: WorkflowVariableSelector
|
expression?: string
|
||||||
operator?: string
|
left?: WorkflowVariableSelector
|
||||||
right?: unknown
|
operator?: string
|
||||||
}
|
right?: unknown
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type WorkflowConditionBranch = {
|
||||||
|
id: string
|
||||||
|
name?: string
|
||||||
|
targetNodeId: string
|
||||||
|
condition?: WorkflowCondition
|
||||||
|
default?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export type WorkflowNodeConfig = Record<string, unknown> & {
|
||||||
|
branches?: WorkflowConditionBranch[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export type WorkflowDraft = {
|
export type WorkflowDraft = {
|
||||||
@@ -71,19 +82,13 @@ export type WorkflowDefinition = {
|
|||||||
type: string
|
type: string
|
||||||
name: string
|
name: string
|
||||||
position: WorkflowNodePosition
|
position: WorkflowNodePosition
|
||||||
config: Record<string, unknown>
|
config: WorkflowNodeConfig
|
||||||
inputs?: Record<string, WorkflowVariableSelector>
|
inputs?: Record<string, WorkflowVariableSelector>
|
||||||
}[]
|
}[]
|
||||||
edges: {
|
edges: {
|
||||||
id: string
|
id: string
|
||||||
source: string
|
source: string
|
||||||
target: string
|
target: string
|
||||||
condition?: {
|
|
||||||
expression?: string
|
|
||||||
left?: WorkflowVariableSelector
|
|
||||||
operator?: string
|
|
||||||
right?: unknown
|
|
||||||
}
|
|
||||||
}[]
|
}[]
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -354,8 +359,7 @@ export function validateWorkflowDraft(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const edgeIds = new Set<string>()
|
const edgeIds = new Set<string>()
|
||||||
const conditionalSources = new Set<string>()
|
const outgoingTargets = new Map<string, Set<string>>()
|
||||||
const defaultSources = new Set<string>()
|
|
||||||
for (const edge of draft.edges) {
|
for (const edge of draft.edges) {
|
||||||
const id = edge.id.trim()
|
const id = edge.id.trim()
|
||||||
if (!id) {
|
if (!id) {
|
||||||
@@ -370,22 +374,10 @@ export function validateWorkflowDraft(
|
|||||||
if (!nodeIds.has(edge.target)) {
|
if (!nodeIds.has(edge.target)) {
|
||||||
errors.push(`edge target node does not exist: ${edge.target}`)
|
errors.push(`edge target node does not exist: ${edge.target}`)
|
||||||
}
|
}
|
||||||
if (edge.data?.condition) {
|
if (!outgoingTargets.has(edge.source)) {
|
||||||
conditionalSources.add(edge.source)
|
outgoingTargets.set(edge.source, new Set())
|
||||||
if (!edge.data.condition.left?.nodeId || !edge.data.condition.left.field) {
|
|
||||||
errors.push(`edge ${edge.id} condition left variable is required`)
|
|
||||||
}
|
|
||||||
if (!edge.data.condition.operator) {
|
|
||||||
errors.push(`edge ${edge.id} condition operator is required`)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
defaultSources.add(edge.source)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (const source of conditionalSources) {
|
|
||||||
if (!defaultSources.has(source)) {
|
|
||||||
errors.push(`node ${source} conditional branch must include a default edge`)
|
|
||||||
}
|
}
|
||||||
|
outgoingTargets.get(edge.source)?.add(edge.target)
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const node of draft.nodes) {
|
for (const node of draft.nodes) {
|
||||||
@@ -401,6 +393,48 @@ export function validateWorkflowDraft(
|
|||||||
errors.push(`${nodeName} 缺少必填输入「${input.name}」,请选择上游节点的输出变量。`)
|
errors.push(`${nodeName} 缺少必填输入「${input.name}」,请选择上游节点的输出变量。`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (nodeType === "condition") {
|
||||||
|
const branches = node.data?.config?.branches ?? []
|
||||||
|
if (branches.length === 0) {
|
||||||
|
errors.push(`${node.data?.name ?? node.id} 至少需要一个分支。`)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
let defaultCount = 0
|
||||||
|
const branchIds = new Set<string>()
|
||||||
|
const targets = outgoingTargets.get(node.id) ?? new Set<string>()
|
||||||
|
for (const branch of branches) {
|
||||||
|
const branchName = branch.name || branch.id || "未命名分支"
|
||||||
|
if (!branch.id) {
|
||||||
|
errors.push(`${node.data?.name ?? node.id} 存在未填写 ID 的分支。`)
|
||||||
|
} else if (branchIds.has(branch.id)) {
|
||||||
|
errors.push(`${node.data?.name ?? node.id} 存在重复分支 ID「${branch.id}」。`)
|
||||||
|
}
|
||||||
|
branchIds.add(branch.id)
|
||||||
|
if (!branch.targetNodeId) {
|
||||||
|
errors.push(`${node.data?.name ?? node.id} 的分支「${branchName}」缺少目标节点。`)
|
||||||
|
} else if (!nodeIds.has(branch.targetNodeId)) {
|
||||||
|
errors.push(`${node.data?.name ?? node.id} 的分支「${branchName}」目标节点不存在。`)
|
||||||
|
} else if (!targets.has(branch.targetNodeId)) {
|
||||||
|
errors.push(`${node.data?.name ?? node.id} 的分支「${branchName}」需要连接到目标节点。`)
|
||||||
|
}
|
||||||
|
if (branch.default) {
|
||||||
|
defaultCount += 1
|
||||||
|
if (branch.condition) {
|
||||||
|
errors.push(`${node.data?.name ?? node.id} 的默认分支不能配置条件。`)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (!branch.condition?.left?.nodeId || !branch.condition.left.field) {
|
||||||
|
errors.push(`${node.data?.name ?? node.id} 的分支「${branchName}」缺少判断变量。`)
|
||||||
|
}
|
||||||
|
if (!branch.condition?.operator) {
|
||||||
|
errors.push(`${node.data?.name ?? node.id} 的分支「${branchName}」缺少判断方式。`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (defaultCount !== 1) {
|
||||||
|
errors.push(`${node.data?.name ?? node.id} 必须且只能有一个默认分支。`)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -429,16 +463,6 @@ export function toApiDefinition(draft: WorkflowDraft): WorkflowDefinition {
|
|||||||
id: edge.id,
|
id: edge.id,
|
||||||
source: edge.source,
|
source: edge.source,
|
||||||
target: edge.target,
|
target: edge.target,
|
||||||
...(edge.data?.condition
|
|
||||||
? {
|
|
||||||
condition: {
|
|
||||||
...(edge.data.condition.expression ? { expression: edge.data.condition.expression } : {}),
|
|
||||||
...(edge.data.condition.left ? { left: edge.data.condition.left } : {}),
|
|
||||||
...(edge.data.condition.operator ? { operator: edge.data.condition.operator } : {}),
|
|
||||||
...(edge.data.condition.right !== undefined ? { right: edge.data.condition.right } : {}),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
: {}),
|
|
||||||
})),
|
})),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -460,7 +484,6 @@ export function fromApiDefinition(definition: WorkflowDefinition): WorkflowDraft
|
|||||||
id: edge.id,
|
id: edge.id,
|
||||||
source: edge.source,
|
source: edge.source,
|
||||||
target: edge.target,
|
target: edge.target,
|
||||||
data: edge.condition ? { condition: edge.condition } : undefined,
|
|
||||||
})),
|
})),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-12
@@ -318,18 +318,12 @@ export type AIWorkflowDefinition = {
|
|||||||
config: Record<string, unknown>
|
config: Record<string, unknown>
|
||||||
inputs?: Record<string, AIWorkflowVariableSelector>
|
inputs?: Record<string, AIWorkflowVariableSelector>
|
||||||
}[]
|
}[]
|
||||||
edges: {
|
edges: {
|
||||||
id: string
|
id: string
|
||||||
source: string
|
source: string
|
||||||
target: string
|
target: string
|
||||||
condition?: {
|
}[]
|
||||||
expression?: string
|
}
|
||||||
left?: AIWorkflowVariableSelector
|
|
||||||
operator?: string
|
|
||||||
right?: unknown
|
|
||||||
}
|
|
||||||
}[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export type AIWorkflow = {
|
export type AIWorkflow = {
|
||||||
id: number
|
id: number
|
||||||
|
|||||||
Reference in New Issue
Block a user