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:
@@ -7,9 +7,12 @@ import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { OptionCombobox } from "@/components/option-combobox"
|
||||
import { VariableSelector } from "./variable-selector"
|
||||
import type {
|
||||
WorkflowConditionBranch,
|
||||
WorkflowNodeSpec,
|
||||
WorkflowNodeConfig,
|
||||
WorkflowVariableRef,
|
||||
WorkflowVariableSpec,
|
||||
WorkflowVariableSelector,
|
||||
@@ -18,28 +21,36 @@ import type {
|
||||
type WorkflowNodeData = Record<string, unknown> & {
|
||||
nodeType?: string
|
||||
name?: string
|
||||
config?: Record<string, unknown>
|
||||
config?: WorkflowNodeConfig
|
||||
inputs?: Record<string, WorkflowVariableSelector>
|
||||
}
|
||||
|
||||
export type WorkflowBranchSummary = {
|
||||
edgeId: string
|
||||
branchId: string
|
||||
targetNodeId: string
|
||||
targetName: string
|
||||
conditionLabel: string
|
||||
isDefault: boolean
|
||||
}
|
||||
|
||||
export type WorkflowBranchTargetOption = {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
export function NodeConfigPanel({
|
||||
node,
|
||||
nodeSpec,
|
||||
availableVariables,
|
||||
branchSummaries = [],
|
||||
branchTargetOptions = [],
|
||||
onChange,
|
||||
}: {
|
||||
node: Node<WorkflowNodeData> | null
|
||||
nodeSpec?: WorkflowNodeSpec
|
||||
availableVariables: WorkflowVariableRef[]
|
||||
branchSummaries?: WorkflowBranchSummary[]
|
||||
branchTargetOptions?: WorkflowBranchTargetOption[]
|
||||
onChange: (nodeId: string, data: WorkflowNodeData) => void
|
||||
}) {
|
||||
if (!node) {
|
||||
@@ -57,6 +68,7 @@ export function NodeConfigPanel({
|
||||
nodeSpec={nodeSpec}
|
||||
availableVariables={availableVariables}
|
||||
branchSummaries={branchSummaries}
|
||||
branchTargetOptions={branchTargetOptions}
|
||||
onChange={onChange}
|
||||
/>
|
||||
)
|
||||
@@ -67,12 +79,14 @@ function NodeConfigForm({
|
||||
nodeSpec,
|
||||
availableVariables,
|
||||
branchSummaries,
|
||||
branchTargetOptions,
|
||||
onChange,
|
||||
}: {
|
||||
node: Node<WorkflowNodeData>
|
||||
nodeSpec?: WorkflowNodeSpec
|
||||
availableVariables: WorkflowVariableRef[]
|
||||
branchSummaries: WorkflowBranchSummary[]
|
||||
branchTargetOptions: WorkflowBranchTargetOption[]
|
||||
onChange: (nodeId: string, data: WorkflowNodeData) => void
|
||||
}) {
|
||||
const [name, setName] = useState(node.data.name ?? "")
|
||||
@@ -121,7 +135,14 @@ function NodeConfigForm({
|
||||
/>
|
||||
</div>
|
||||
{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 ? (
|
||||
@@ -207,38 +228,161 @@ function NodeConfigForm({
|
||||
}
|
||||
|
||||
function ConditionNodePanel({
|
||||
branches,
|
||||
branchSummaries,
|
||||
branchTargetOptions,
|
||||
availableVariables,
|
||||
outputSchema,
|
||||
onChange,
|
||||
}: {
|
||||
branches: WorkflowConditionBranch[]
|
||||
branchSummaries: WorkflowBranchSummary[]
|
||||
branchTargetOptions: WorkflowBranchTargetOption[]
|
||||
availableVariables: WorkflowVariableRef[]
|
||||
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 (
|
||||
<>
|
||||
{/* <div className="rounded-md border bg-muted/30 p-3 text-xs text-muted-foreground">
|
||||
条件节点只负责分流;每条出口连线承载自己的判断条件,没有条件的出口会作为默认分支。
|
||||
</div> */}
|
||||
<div className="space-y-2">
|
||||
<div className="text-sm font-medium">出口分支</div>
|
||||
{branchSummaries.length > 0 ? (
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<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">
|
||||
{branchSummaries.map((branch) => (
|
||||
<div key={branch.edgeId} className="rounded-md border bg-background p-2">
|
||||
<div className="flex items-center justify-between gap-2 text-xs">
|
||||
<span className="min-w-0 truncate font-medium">{branch.targetName}</span>
|
||||
<span className="shrink-0 rounded-sm bg-muted px-1.5 py-0.5 text-muted-foreground">
|
||||
{branch.isDefault ? "默认" : "条件"}
|
||||
</span>
|
||||
{branches.map((branch, index) => {
|
||||
const summary = summariesByBranchID.get(branch.id)
|
||||
const condition = branch.condition ?? {}
|
||||
const conditionRight = condition.right === undefined || condition.right === null
|
||||
? ""
|
||||
: String(condition.right)
|
||||
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 className="mt-1 line-clamp-2 text-xs text-muted-foreground">
|
||||
{branch.conditionLabel}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-md border border-dashed p-2 text-xs text-muted-foreground">
|
||||
当前还没有出口连线。
|
||||
当前还没有分支。
|
||||
</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,
|
||||
BaseEdge,
|
||||
ConnectionMode,
|
||||
EdgeLabelRenderer,
|
||||
Controls,
|
||||
getBezierPath,
|
||||
Handle,
|
||||
@@ -44,9 +43,6 @@ import {
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
|
||||
|
||||
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 {
|
||||
Popover,
|
||||
@@ -69,20 +65,19 @@ import {
|
||||
toApiDefinition,
|
||||
undoWorkflowHistory,
|
||||
validateWorkflowDraft,
|
||||
type WorkflowVariableRef,
|
||||
type WorkflowVariableSelector,
|
||||
type WorkflowEditorEdge,
|
||||
type WorkflowCondition,
|
||||
type WorkflowEditorNode,
|
||||
type WorkflowHistory,
|
||||
type WorkflowHelperLine,
|
||||
type WorkflowNodeConfig,
|
||||
} from "./workflow-utils"
|
||||
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> & {
|
||||
nodeType?: string
|
||||
name?: string
|
||||
config?: Record<string, unknown>
|
||||
config?: WorkflowNodeConfig
|
||||
inputs?: Record<string, { nodeId: string; field: string }>
|
||||
nodeSpecs?: AIWorkflowNodeSpec[]
|
||||
onAddAfter?: (sourceNodeId: string, spec: AIWorkflowNodeSpec) => void
|
||||
@@ -100,10 +95,8 @@ type WorkflowEditorSnapshot = {
|
||||
nodes: WorkflowFlowNode[]
|
||||
edges: WorkflowFlowEdge[]
|
||||
}
|
||||
type WorkflowEdgeCondition = NonNullable<WorkflowEditorEdge["data"]>["condition"]
|
||||
type WorkflowEdgeRenderData = WorkflowEditorEdge["data"] & {
|
||||
type WorkflowEdgeRenderData = {
|
||||
active?: boolean
|
||||
onSelect?: (edgeId: string) => void
|
||||
}
|
||||
type WorkflowFinalConnectionState = FinalConnectionState
|
||||
|
||||
@@ -163,8 +156,6 @@ function toFlowEdges(definition: AIWorkflowDefinition): WorkflowFlowEdge[] {
|
||||
type: "workflowEdge",
|
||||
source: edge.source,
|
||||
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,
|
||||
source: edge.source,
|
||||
target: edge.target,
|
||||
data: edge.data as WorkflowEditorEdge["data"],
|
||||
})),
|
||||
}
|
||||
}
|
||||
@@ -231,7 +221,6 @@ export function WorkflowEditor({
|
||||
const [helperLines, setHelperLines] = useState<WorkflowHelperLine>({})
|
||||
const [propertyPanelNode, setPropertyPanelNode] = useState<WorkflowFlowNode | null>(null)
|
||||
const [selectedEdgeId, setSelectedEdgeId] = useState<string | null>(null)
|
||||
const [propertyPanelEdge, setPropertyPanelEdge] = useState<WorkflowFlowEdge | null>(null)
|
||||
const [propertyPanelVisible, setPropertyPanelVisible] = useState(false)
|
||||
const editorRef = useRef<HTMLDivElement | null>(null)
|
||||
const canvasRef = useRef<HTMLElement | null>(null)
|
||||
@@ -259,14 +248,13 @@ export function WorkflowEditor({
|
||||
[draft, nodeSpecs, propertyPanelNode]
|
||||
)
|
||||
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]
|
||||
)
|
||||
const propertyPanelEdgeVariables = useMemo(
|
||||
() => (propertyPanelEdge ? getEdgeConditionVariables(draft, propertyPanelEdge.source, nodeSpecs) : []),
|
||||
[draft, nodeSpecs, propertyPanelEdge]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
onDefinitionChange(toApiDefinition(draft) as AIWorkflowDefinition)
|
||||
}, [draft, onDefinitionChange])
|
||||
@@ -311,19 +299,6 @@ export function WorkflowEditor({
|
||||
window.clearTimeout(propertyPanelAnimationTimerRef.current)
|
||||
}
|
||||
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(() => {
|
||||
setPropertyPanelVisible(true)
|
||||
propertyPanelAnimationTimerRef.current = null
|
||||
@@ -337,7 +312,6 @@ export function WorkflowEditor({
|
||||
setPropertyPanelVisible(false)
|
||||
propertyPanelAnimationTimerRef.current = window.setTimeout(() => {
|
||||
setPropertyPanelNode(null)
|
||||
setPropertyPanelEdge(null)
|
||||
propertyPanelAnimationTimerRef.current = null
|
||||
}, 220)
|
||||
}, [])
|
||||
@@ -377,9 +351,6 @@ export function WorkflowEditor({
|
||||
setPropertyPanelNode((current) =>
|
||||
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]
|
||||
)
|
||||
@@ -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(
|
||||
() =>
|
||||
edges.map((edge) => {
|
||||
@@ -750,34 +712,13 @@ export function WorkflowEditor({
|
||||
...edge,
|
||||
selected: active,
|
||||
data: {
|
||||
...((edge.data ?? {}) as WorkflowEditorEdge["data"]),
|
||||
active,
|
||||
onSelect: selectEdge,
|
||||
} 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 containerWidth = editorRef.current?.getBoundingClientRect().width ?? 0
|
||||
const maxWidth = containerWidth > 0 ? containerWidth * 0.34 : 520
|
||||
@@ -936,7 +877,7 @@ export function WorkflowEditor({
|
||||
}}
|
||||
onEdgeClick={(event, edge) => {
|
||||
event.stopPropagation()
|
||||
selectEdge(edge.id)
|
||||
setSelectedEdgeId(edge.id)
|
||||
}}
|
||||
onPaneClick={() => {
|
||||
setSelectedEdgeId(null)
|
||||
@@ -977,7 +918,7 @@ export function WorkflowEditor({
|
||||
restoreDefaultDisabled={restoreDefaultDisabled}
|
||||
/>
|
||||
</div>
|
||||
{propertyPanelNode || propertyPanelEdge ? (
|
||||
{propertyPanelNode ? (
|
||||
<aside
|
||||
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",
|
||||
@@ -993,16 +934,10 @@ export function WorkflowEditor({
|
||||
nodeSpec={propertyPanelNodeSpec}
|
||||
availableVariables={propertyPanelAvailableVariables}
|
||||
branchSummaries={propertyPanelBranchSummaries}
|
||||
branchTargetOptions={propertyPanelBranchTargetOptions}
|
||||
onChange={updateNodeData}
|
||||
/>
|
||||
) : null}
|
||||
{propertyPanelEdge ? (
|
||||
<EdgeConditionPanel
|
||||
edge={propertyPanelEdge}
|
||||
variables={propertyPanelEdgeVariables}
|
||||
onChange={updateEdgeCondition}
|
||||
/>
|
||||
) : null}
|
||||
{!validation.valid ? (
|
||||
<div className="border-t p-4">
|
||||
<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 = [
|
||||
{ value: "eq", label: "等于" },
|
||||
{ value: "neq", label: "不等于" },
|
||||
@@ -1107,24 +1018,40 @@ const conditionOperators = [
|
||||
|
||||
function getBranchSummaries(
|
||||
nodes: WorkflowFlowNode[],
|
||||
edges: WorkflowFlowEdge[],
|
||||
nodeId: string
|
||||
): WorkflowBranchSummary[] {
|
||||
return edges
|
||||
.filter((edge) => edge.source === nodeId)
|
||||
.map((edge) => {
|
||||
const target = nodes.find((node) => node.id === edge.target)
|
||||
const condition = (edge.data as WorkflowEditorEdge["data"] | undefined)?.condition
|
||||
const node = nodes.find((item) => item.id === nodeId)
|
||||
const branches = node?.data.config?.branches ?? []
|
||||
return branches
|
||||
.map((branch) => {
|
||||
const target = nodes.find((item) => item.id === branch.targetNodeId)
|
||||
return {
|
||||
edgeId: edge.id,
|
||||
targetName: target?.data.name ?? target?.data.title ?? edge.target,
|
||||
conditionLabel: condition ? formatConditionLabel(condition) : "无条件匹配",
|
||||
isDefault: !condition,
|
||||
branchId: branch.id,
|
||||
targetNodeId: branch.targetNodeId,
|
||||
targetName: target?.data.name ?? target?.data.title ?? branch.targetNodeId,
|
||||
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
|
||||
? `${condition.left.nodeId}.${condition.left.field}`
|
||||
: "未选择变量"
|
||||
@@ -1149,105 +1076,6 @@ function formatConditionRight(value: unknown) {
|
||||
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) {
|
||||
if ("changedTouches" in event) {
|
||||
const touch = event.changedTouches[0] ?? event.touches[0]
|
||||
@@ -1334,7 +1162,7 @@ function WorkflowCanvasEdge({
|
||||
}: EdgeProps<WorkflowFlowEdge>) {
|
||||
const sourceOffset = getEdgeEndpointOffset(sourcePosition, workflowHandleRadius)
|
||||
const targetOffset = getEdgeEndpointOffset(targetPosition, workflowHandleRadius)
|
||||
const [edgePath, labelX, labelY] = getBezierPath({
|
||||
const [edgePath] = getBezierPath({
|
||||
sourceX: sourceX + sourceOffset.x,
|
||||
sourceY: sourceY + sourceOffset.y,
|
||||
sourcePosition,
|
||||
@@ -1343,54 +1171,19 @@ function WorkflowCanvasEdge({
|
||||
targetPosition,
|
||||
curvature: 0.18,
|
||||
})
|
||||
const condition = (data as WorkflowEditorEdge["data"] | undefined)?.condition
|
||||
const edgeData = data as WorkflowEdgeRenderData | undefined
|
||||
const active = selected || edgeData?.active
|
||||
|
||||
return (
|
||||
<>
|
||||
<BaseEdge
|
||||
id={id}
|
||||
path={edgePath}
|
||||
markerEnd={markerEnd}
|
||||
className={cn(
|
||||
"transition-all",
|
||||
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}
|
||||
</>
|
||||
<BaseEdge
|
||||
id={id}
|
||||
path={edgePath}
|
||||
markerEnd={markerEnd}
|
||||
className={cn(
|
||||
"transition-all",
|
||||
active ? "!stroke-primary !stroke-[2.4px]" : "!stroke-muted-foreground/45 !stroke-[1.8px]"
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -320,6 +320,102 @@ describe("getAvailableVariables", () => {
|
||||
})
|
||||
|
||||
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 () => {
|
||||
const { toApiDefinition } = await loadModule()
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ export type WorkflowEditorNode = {
|
||||
nodeType?: string
|
||||
name?: string
|
||||
label?: string
|
||||
config?: Record<string, unknown>
|
||||
config?: WorkflowNodeConfig
|
||||
inputs?: Record<string, WorkflowVariableSelector>
|
||||
}
|
||||
}
|
||||
@@ -48,14 +48,25 @@ export type WorkflowEditorEdge = {
|
||||
id: string
|
||||
source: string
|
||||
target: string
|
||||
data?: {
|
||||
condition?: {
|
||||
expression?: string
|
||||
left?: WorkflowVariableSelector
|
||||
operator?: string
|
||||
right?: unknown
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type WorkflowCondition = {
|
||||
expression?: string
|
||||
left?: WorkflowVariableSelector
|
||||
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 = {
|
||||
@@ -71,19 +82,13 @@ export type WorkflowDefinition = {
|
||||
type: string
|
||||
name: string
|
||||
position: WorkflowNodePosition
|
||||
config: Record<string, unknown>
|
||||
config: WorkflowNodeConfig
|
||||
inputs?: Record<string, WorkflowVariableSelector>
|
||||
}[]
|
||||
edges: {
|
||||
id: string
|
||||
source: 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 conditionalSources = new Set<string>()
|
||||
const defaultSources = new Set<string>()
|
||||
const outgoingTargets = new Map<string, Set<string>>()
|
||||
for (const edge of draft.edges) {
|
||||
const id = edge.id.trim()
|
||||
if (!id) {
|
||||
@@ -370,22 +374,10 @@ export function validateWorkflowDraft(
|
||||
if (!nodeIds.has(edge.target)) {
|
||||
errors.push(`edge target node does not exist: ${edge.target}`)
|
||||
}
|
||||
if (edge.data?.condition) {
|
||||
conditionalSources.add(edge.source)
|
||||
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`)
|
||||
if (!outgoingTargets.has(edge.source)) {
|
||||
outgoingTargets.set(edge.source, new Set())
|
||||
}
|
||||
outgoingTargets.get(edge.source)?.add(edge.target)
|
||||
}
|
||||
|
||||
for (const node of draft.nodes) {
|
||||
@@ -401,6 +393,48 @@ export function validateWorkflowDraft(
|
||||
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 {
|
||||
@@ -429,16 +463,6 @@ export function toApiDefinition(draft: WorkflowDraft): WorkflowDefinition {
|
||||
id: edge.id,
|
||||
source: edge.source,
|
||||
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,
|
||||
source: edge.source,
|
||||
target: edge.target,
|
||||
data: edge.condition ? { condition: edge.condition } : undefined,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user