From d979b3941d2540c20e3a80e1ff15cdcf2ea28357 Mon Sep 17 00:00:00 2001 From: lanyuanxiaoyao Date: Thu, 3 Jul 2025 23:40:41 +0800 Subject: [PATCH] =?UTF-8?q?feat(ai-web):=20=E5=AE=8C=E6=88=90=E8=87=AA?= =?UTF-8?q?=E7=A0=94=E6=B5=81=E7=A8=8B=E5=9B=BE=E7=9A=84=E4=BF=9D=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service-ai/database/20250702.sql | 2 +- .../task/TaskTemplateController.java | 35 +-- .../ai/web/entity/FlowTaskTemplate.java | 4 +- .../service/task/FlowTaskTemplateService.java | 8 + .../src/components/flow/FlowChecker.test.tsx | 53 +--- .../src/components/flow/FlowChecker.tsx | 228 ++---------------- .../client/src/components/flow/FlowEditor.tsx | 45 ++-- .../flow/node/{EndNode.tsx => OutputNode.tsx} | 6 +- .../src/components/flow/node/StartNode.tsx | 68 ------ .../template/FlowTaskTemplateFlowEdit.tsx | 19 +- 10 files changed, 92 insertions(+), 376 deletions(-) rename service-web/client/src/components/flow/node/{EndNode.tsx => OutputNode.tsx} (67%) delete mode 100644 service-web/client/src/components/flow/node/StartNode.tsx diff --git a/service-ai/database/20250702.sql b/service-ai/database/20250702.sql index 0ad4cde..ae11869 100644 --- a/service-ai/database/20250702.sql +++ b/service-ai/database/20250702.sql @@ -52,7 +52,7 @@ create table hudi_collect_build_b12.service_ai_flow_task_template created_time datetime(6) comment '记录创建时间', modified_time datetime(6) comment '记录更新时间', description varchar(255) comment '模板功能、内容说明', - flow_graph longtext comment '前端流程图数据', + flow_graph longtext not null comment '前端流程图数据', input_schema longtext not null comment '模板入参Schema', name varchar(255) not null comment '模板名称', primary key (id) diff --git a/service-ai/service-ai-web/src/main/java/com/lanyuanxiaoyao/service/ai/web/controller/task/TaskTemplateController.java b/service-ai/service-ai-web/src/main/java/com/lanyuanxiaoyao/service/ai/web/controller/task/TaskTemplateController.java index c61e9e2..306fdb1 100644 --- a/service-ai/service-ai-web/src/main/java/com/lanyuanxiaoyao/service/ai/web/controller/task/TaskTemplateController.java +++ b/service-ai/service-ai-web/src/main/java/com/lanyuanxiaoyao/service/ai/web/controller/task/TaskTemplateController.java @@ -3,10 +3,8 @@ package com.lanyuanxiaoyao.service.ai.web.controller.task; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import com.lanyuanxiaoyao.service.ai.core.entity.amis.AmisCrudResponse; import com.lanyuanxiaoyao.service.ai.core.entity.amis.AmisResponse; import com.lanyuanxiaoyao.service.ai.web.base.controller.SimpleControllerSupport; -import com.lanyuanxiaoyao.service.ai.web.base.controller.query.Query; import com.lanyuanxiaoyao.service.ai.web.base.entity.SimpleItem; import com.lanyuanxiaoyao.service.ai.web.entity.FlowTaskTemplate; import com.lanyuanxiaoyao.service.ai.web.service.task.FlowTaskTemplateService; @@ -17,6 +15,8 @@ import lombok.extern.slf4j.Slf4j; import org.mapstruct.Context; import org.mapstruct.factory.Mappers; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -24,26 +24,19 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("flow_task/template") public class TaskTemplateController extends SimpleControllerSupport { + private final FlowTaskTemplateService flowTaskTemplateService; private final ObjectMapper mapper; public TaskTemplateController(FlowTaskTemplateService flowTaskTemplateService, Jackson2ObjectMapperBuilder builder) { super(flowTaskTemplateService); + this.flowTaskTemplateService = flowTaskTemplateService; this.mapper = builder.build(); } - @Override - public AmisResponse save(SaveItem saveItem) throws Exception { - log.info("Save: {}", saveItem); - SaveItem.Mapper map = Mappers.getMapper(SaveItem.Mapper.class); - log.info("Mapper: {}", map.from(saveItem, mapper)); - return super.save(saveItem); - } - - @Override - public AmisCrudResponse list(Query query) throws Exception { - AmisCrudResponse list = super.list(query); - log.info("List: {}", list); - return list; + @PostMapping("update_flow_graph") + public AmisResponse updateFlowGraph(@RequestBody UpdateGraphItem item) throws JsonProcessingException { + flowTaskTemplateService.updateFlowGraph(item.getId(), mapper.writeValueAsString(item.getGraph())); + return AmisResponse.responseSuccess(); } @Override @@ -97,14 +90,22 @@ public class TaskTemplateController extends SimpleControllerSupport inputSchema; + private Map flowGraph; @org.mapstruct.Mapper public static abstract class Mapper { public abstract DetailItem from(FlowTaskTemplate template, @Context ObjectMapper mapper) throws Exception; - public Map mapInputSchema(String inputSchema, @Context ObjectMapper mapper) throws Exception { - return mapper.readValue(inputSchema, new TypeReference<>() {}); + public Map mapJson(String source, @Context ObjectMapper mapper) throws Exception { + return mapper.readValue(source, new TypeReference<>() { + }); } } } + + @Data + public static class UpdateGraphItem { + private Long id; + private Map graph; + } } diff --git a/service-ai/service-ai-web/src/main/java/com/lanyuanxiaoyao/service/ai/web/entity/FlowTaskTemplate.java b/service-ai/service-ai-web/src/main/java/com/lanyuanxiaoyao/service/ai/web/entity/FlowTaskTemplate.java index 2a8e2a7..cf47acb 100644 --- a/service-ai/service-ai-web/src/main/java/com/lanyuanxiaoyao/service/ai/web/entity/FlowTaskTemplate.java +++ b/service-ai/service-ai-web/src/main/java/com/lanyuanxiaoyao/service/ai/web/entity/FlowTaskTemplate.java @@ -31,6 +31,6 @@ public class FlowTaskTemplate extends SimpleEntity { @Column(nullable = false, columnDefinition = "longtext") private String inputSchema; @Comment("前端流程图数据") - @Column(columnDefinition = "longtext") - private String flowGraph; + @Column(nullable = false, columnDefinition = "longtext") + private String flowGraph = "{}"; } diff --git a/service-ai/service-ai-web/src/main/java/com/lanyuanxiaoyao/service/ai/web/service/task/FlowTaskTemplateService.java b/service-ai/service-ai-web/src/main/java/com/lanyuanxiaoyao/service/ai/web/service/task/FlowTaskTemplateService.java index 472f3fd..c46e759 100644 --- a/service-ai/service-ai-web/src/main/java/com/lanyuanxiaoyao/service/ai/web/service/task/FlowTaskTemplateService.java +++ b/service-ai/service-ai-web/src/main/java/com/lanyuanxiaoyao/service/ai/web/service/task/FlowTaskTemplateService.java @@ -5,6 +5,7 @@ import com.lanyuanxiaoyao.service.ai.web.entity.FlowTaskTemplate; import com.lanyuanxiaoyao.service.ai.web.repository.FlowTaskTemplateRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; @Slf4j @Service @@ -12,4 +13,11 @@ public class FlowTaskTemplateService extends SimpleServiceSupport { } } -const createStartNode = (id: string): Node => createNode(id, 'start-node') -const createEndNode = (id: string): Node => createNode(id, 'end-node') - const createConnection = function (source: string, target: string, sourceHandle: string | null = null, targetHandle: string | null = null): Connection { return { source, @@ -41,31 +29,13 @@ const createConnection = function (source: string, target: string, sourceHandle: } } -/* check add node */ - -test(multiStartNodeError().message, () => { - expect(() => checkAddNode('start-node', [createStartNode(uuid())], [])).toThrowError(multiStartNodeError()) -}) - -test(multiEndNodeError().message, () => { - expect(() => checkAddNode('end-node', [createEndNode(uuid())], [])).toThrowError(multiEndNodeError()) -}) - /* check add connection */ test(sourceNodeNotFoundError().message, () => { expect(() => checkAddConnection(createConnection('a', 'b'), [], [])) }) test(targetNodeNotFoundError().message, () => { - expect(() => checkAddConnection(createConnection('a', 'b'), [createStartNode('a')], [])) -}) - -test(startNodeToEndNodeError().message, () => { - expect(() => checkAddConnection( - createConnection('a', 'b'), - [createStartNode('a'), createEndNode('b')], - [] - )) + expect(() => checkAddConnection(createConnection('a', 'b'), [createNode('a', 'normal-node')], [])) }) test(nodeToSelfError().message, () => { @@ -90,24 +60,3 @@ test(hasCycleError().message, () => { checkAddConnection(JSON.parse('{\n "source": "yp-yYfKUzC",\n "sourceHandle": null,\n "target": "N4HQPN-NYZ",\n "targetHandle": null\n}'), nodes, edges) }).toThrowError(hasCycleError()) }) - -test(hasRedundantEdgeError().message, () => { - expect(() => { - // language=JSON - const { - nodes, - edges, - } = JSON.parse('{\n "nodes": [\n {\n "id": "TCxPixrdkI",\n "type": "start-node",\n "position": {\n "x": -256,\n "y": 109.5\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 83\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "tGs78_ietp",\n "type": "llm-node",\n "position": {\n "x": 108,\n "y": -2.5\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 105\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "OeZdaU7LpY",\n "type": "llm-node",\n "position": {\n "x": 111,\n "y": 196\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 105\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "LjfoCYZo-E",\n "type": "knowledge-node",\n "position": {\n "x": 497.62196259607214,\n "y": -10.792497317791003\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 75\n },\n "selected": true,\n "dragging": false\n },\n {\n "id": "sQM_22GYB5",\n "type": "end-node",\n "position": {\n "x": 874.3164534765615,\n "y": 151.70316541496913\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 75\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "KpMH_xc3ZZ",\n "type": "llm-node",\n "position": {\n "x": 529.6286840434341,\n "y": 150.4721376669937\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 75\n },\n "selected": false,\n "dragging": false\n }\n ],\n "edges": [\n {\n "source": "TCxPixrdkI",\n "sourceHandle": "source",\n "target": "tGs78_ietp",\n "targetHandle": "target",\n "id": "xy-edge__TCxPixrdkIsource-tGs78_ietptarget"\n },\n {\n "source": "TCxPixrdkI",\n "sourceHandle": "source",\n "target": "OeZdaU7LpY",\n "targetHandle": "target",\n "id": "xy-edge__TCxPixrdkIsource-OeZdaU7LpYtarget"\n },\n {\n "source": "tGs78_ietp",\n "sourceHandle": "source",\n "target": "LjfoCYZo-E",\n "targetHandle": "target",\n "id": "xy-edge__tGs78_ietpsource-LjfoCYZo-Etarget"\n },\n {\n "source": "LjfoCYZo-E",\n "sourceHandle": "source",\n "target": "KpMH_xc3ZZ",\n "targetHandle": "target",\n "id": "xy-edge__LjfoCYZo-Esource-KpMH_xc3ZZtarget"\n },\n {\n "source": "OeZdaU7LpY",\n "sourceHandle": "source",\n "target": "KpMH_xc3ZZ",\n "targetHandle": "target",\n "id": "xy-edge__OeZdaU7LpYsource-KpMH_xc3ZZtarget"\n },\n {\n "source": "KpMH_xc3ZZ",\n "sourceHandle": "source",\n "target": "sQM_22GYB5",\n "targetHandle": "target",\n "id": "xy-edge__KpMH_xc3ZZsource-sQM_22GYB5target"\n }\n ],\n "data": {\n "tGs78_ietp": {\n "model": "qwen3",\n "outputs": {\n "text": {\n "type": "string"\n }\n },\n "systemPrompt": "你是个聪明人"\n },\n "OeZdaU7LpY": {\n "model": "qwen3",\n "outputs": {\n "text": {\n "type": "string"\n }\n },\n "systemPrompt": "你也是个聪明人"\n }\n }\n}') - // language=JSON - checkAddConnection(JSON.parse('{\n "source": "OeZdaU7LpY",\n "sourceHandle": "source",\n "target": "LjfoCYZo-E",\n "targetHandle": "target"\n}'), nodes, edges) - }).toThrowError(hasRedundantEdgeError()) -}) - -/* check save */ -test(atLeastOneStartNodeError().message, () => { - expect(() => checkSave([], [], {})).toThrowError(atLeastOneStartNodeError()) -}) - -test(atLeastOneEndNodeError().message, () => { - expect(() => checkSave([createStartNode(uuid())], [], {})).toThrowError(atLeastOneEndNodeError()) -}) diff --git a/service-web/client/src/components/flow/FlowChecker.tsx b/service-web/client/src/components/flow/FlowChecker.tsx index 384cd06..46a6254 100644 --- a/service-web/client/src/components/flow/FlowChecker.tsx +++ b/service-web/client/src/components/flow/FlowChecker.tsx @@ -1,5 +1,5 @@ -import {type Connection, type Edge, getConnectedEdges, getIncomers, getOutgoers, type Node} from '@xyflow/react' -import {clone, find, findIdx, isEqual, lpad, toStr, uuid} from 'licia' +import {type Connection, type Edge, getOutgoers, type Node} from '@xyflow/react' +import {find, isEmpty, isEqual, lpad, toStr} from 'licia' export class CheckError extends Error { readonly id: string @@ -17,28 +17,16 @@ export class CheckError extends Error { } } -export const multiStartNodeError = () => new CheckError(100, '只能存在1个开始节点') -export const multiEndNodeError = () => new CheckError(101, '只能存在1个结束节点') - const getNodeById = (id: string, nodes: Node[]) => find(nodes, (n: Node) => isEqual(n.id, id)) // @ts-ignore export const checkAddNode: (type: string, nodes: Node[], edges: Edge[]) => void = (type, nodes, edges) => { - if (isEqual(type, 'start-node') && findIdx(nodes, (node: Node) => isEqual(type, node.type)) > -1) { - throw multiStartNodeError() - } - if (isEqual(type, 'end-node') && findIdx(nodes, (node: Node) => isEqual(type, node.type)) > -1) { - throw multiEndNodeError() - } } export const sourceNodeNotFoundError = () => new CheckError(200, '连线起始节点未找到') export const targetNodeNotFoundError = () => new CheckError(201, '连线目标节点未找到') -export const startNodeToEndNodeError = () => new CheckError(202, '开始节点不能直连结束节点') export const nodeToSelfError = () => new CheckError(203, '节点不能直连自身') export const hasCycleError = () => new CheckError(204, '禁止流程循环') -export const nodeNotOnlyToEndNode = () => new CheckError(206, '直连结束节点的节点不允许连接其他节点') -export const hasRedundantEdgeError = () => new CheckError(207, '禁止出现冗余边') const hasCycle = (sourceNode: Node, targetNode: Node, nodes: Node[], edges: Edge[], visited = new Set()) => { if (visited.has(targetNode.id)) return false @@ -49,189 +37,6 @@ const hasCycle = (sourceNode: Node, targetNode: Node, nodes: Node[], edges: Edge } } -/* 摘自Dify的流程合法性判断 */ - -type ParallelInfoItem = { - parallelNodeId: string - depth: number - isBranch?: boolean -} - -type NodeParallelInfo = { - parallelNodeId: string - edgeHandleId: string - depth: number -} - -type NodeHandle = { - node: Node - handle: string -} - -type NodeStreamInfo = { - upstreamNodes: Set - downstreamEdges: Set -} - -const groupBy = (array: Record[], iteratee: string) => { - const result: Record = {} - for (const item of array) { - // 获取属性值并转换为字符串键 - const key = item[iteratee] - if (!result[key]) { - result[key] = [] - } - result[key].push(item) - } - return result -} - -// @ts-ignore -export const getParallelInfo = (nodes: Node[], edges: Edge[], parentNodeId?: string) => { - // 等到有子图的时候再考虑 - /*if (parentNodeId) { - const parentNode = nodes.find(node => node.id === parentNodeId) - if (!parentNode) - throw new Error('Parent node not found') - - startNode = nodes.find(node => node.id === (parentNode.data as (IterationNodeType | LoopNodeType)).start_node_id) - } - else { - startNode = nodes.find(node => isEqual(node.type, 'start_node')) - }*/ - let startNode = nodes.find(node => isEqual(node.type, 'start-node')) - if (!startNode) - throw new Error('Start node not found') - - const parallelList = [] as ParallelInfoItem[] - const nextNodeHandles = [{node: startNode, handle: 'source'}] - let hasAbnormalEdges = false - - const traverse = (firstNodeHandle: NodeHandle) => { - const nodeEdgesSet = {} as Record> - const totalEdgesSet = new Set() - const nextHandles = [firstNodeHandle] - const streamInfo = {} as Record - const parallelListItem = { - parallelNodeId: '', - depth: 0, - } as ParallelInfoItem - const nodeParallelInfoMap = {} as Record - nodeParallelInfoMap[firstNodeHandle.node.id] = { - parallelNodeId: '', - edgeHandleId: '', - depth: 0, - } - - while (nextHandles.length) { - const currentNodeHandle = nextHandles.shift()! - const {node: currentNode, handle: currentHandle = 'source'} = currentNodeHandle - const currentNodeHandleKey = currentNode.id - const connectedEdges = edges.filter(edge => edge.source === currentNode.id && edge.sourceHandle === currentHandle) - const connectedEdgesLength = connectedEdges.length - const outgoers = nodes.filter(node => connectedEdges.some(edge => edge.target === node.id)) - const incomers = getIncomers(currentNode, nodes, edges) - - if (!streamInfo[currentNodeHandleKey]) { - streamInfo[currentNodeHandleKey] = { - upstreamNodes: new Set(), - downstreamEdges: new Set(), - } - } - - if (nodeEdgesSet[currentNodeHandleKey]?.size > 0 && incomers.length > 1) { - const newSet = new Set() - for (const item of totalEdgesSet) { - if (!streamInfo[currentNodeHandleKey].downstreamEdges.has(item)) - newSet.add(item) - } - if (isEqual(nodeEdgesSet[currentNodeHandleKey], newSet)) { - parallelListItem.depth = nodeParallelInfoMap[currentNode.id].depth - nextNodeHandles.push({node: currentNode, handle: currentHandle}) - break - } - } - - if (nodeParallelInfoMap[currentNode.id].depth > parallelListItem.depth) - parallelListItem.depth = nodeParallelInfoMap[currentNode.id].depth - - outgoers.forEach((outgoer) => { - const outgoerConnectedEdges = getConnectedEdges([outgoer], edges).filter(edge => edge.source === outgoer.id) - const sourceEdgesGroup = groupBy(outgoerConnectedEdges, 'sourceHandle') - const incomers = getIncomers(outgoer, nodes, edges) - - if (outgoers.length > 1 && incomers.length > 1) - hasAbnormalEdges = true - - Object.keys(sourceEdgesGroup).forEach((sourceHandle) => { - nextHandles.push({node: outgoer, handle: sourceHandle}) - }) - if (!outgoerConnectedEdges.length) - nextHandles.push({node: outgoer, handle: 'source'}) - - const outgoerKey = outgoer.id - if (!nodeEdgesSet[outgoerKey]) - nodeEdgesSet[outgoerKey] = new Set() - - if (nodeEdgesSet[currentNodeHandleKey]) { - for (const item of nodeEdgesSet[currentNodeHandleKey]) - nodeEdgesSet[outgoerKey].add(item) - } - - if (!streamInfo[outgoerKey]) { - streamInfo[outgoerKey] = { - upstreamNodes: new Set(), - downstreamEdges: new Set(), - } - } - - if (!nodeParallelInfoMap[outgoer.id]) { - nodeParallelInfoMap[outgoer.id] = { - ...nodeParallelInfoMap[currentNode.id], - } - } - - if (connectedEdgesLength > 1) { - const edge = connectedEdges.find(edge => edge.target === outgoer.id)! - nodeEdgesSet[outgoerKey].add(edge.id) - totalEdgesSet.add(edge.id) - - streamInfo[currentNodeHandleKey].downstreamEdges.add(edge.id) - streamInfo[outgoerKey].upstreamNodes.add(currentNodeHandleKey) - - for (const item of streamInfo[currentNodeHandleKey].upstreamNodes) - streamInfo[item].downstreamEdges.add(edge.id) - - if (!parallelListItem.parallelNodeId) - parallelListItem.parallelNodeId = currentNode.id - - const prevDepth = nodeParallelInfoMap[currentNode.id].depth + 1 - const currentDepth = nodeParallelInfoMap[outgoer.id].depth - - nodeParallelInfoMap[outgoer.id].depth = Math.max(prevDepth, currentDepth) - } else { - for (const item of streamInfo[currentNodeHandleKey].upstreamNodes) - streamInfo[outgoerKey].upstreamNodes.add(item) - - nodeParallelInfoMap[outgoer.id].depth = nodeParallelInfoMap[currentNode.id].depth - } - }) - } - - parallelList.push(parallelListItem) - } - - while (nextNodeHandles.length) { - const nodeHandle = nextNodeHandles.shift()! - traverse(nodeHandle) - } - - return { - parallelList, - hasAbnormalEdges, - } -} - export const checkAddConnection: (connection: Connection, nodes: Node[], edges: Edge[]) => void = (connection, nodes, edges) => { let sourceNode = getNodeById(connection.source, nodes) if (!sourceNode) { @@ -241,10 +46,6 @@ export const checkAddConnection: (connection: Connection, nodes: Node[], edges: if (!targetNode) { throw targetNodeNotFoundError() } - // 禁止短路整个流程 - if (isEqual('start-node', sourceNode.type) && isEqual('end-node', targetNode.type)) { - throw startNodeToEndNodeError() - } // 禁止流程出现环,必须是有向无环图 if (isEqual(sourceNode.id, targetNode.id)) { @@ -253,22 +54,25 @@ export const checkAddConnection: (connection: Connection, nodes: Node[], edges: throw hasCycleError() } - let newEdges = [...clone(edges), {...connection, id: uuid()}] - let {hasAbnormalEdges} = getParallelInfo(nodes, newEdges) - if (hasAbnormalEdges) { - throw hasRedundantEdgeError() - } + // let newEdges = [...clone(edges), {...connection, id: uuid()}] + // let {hasAbnormalEdges} = getParallelInfo(nodes, newEdges) + // if (hasAbnormalEdges) { + // throw hasRedundantEdgeError() + // } } -export const atLeastOneStartNodeError = () => new CheckError(300, '至少存在1个开始节点') -export const atLeastOneEndNodeError = () => new CheckError(301, '至少存在1个结束节点') +export const atLeastOneNode = () => new CheckError(300, '至少包含一个节点') +export const hasUnfinishedNode = (nodeId: string) => new CheckError(301, `存在尚未配置完成的节点: ${nodeId}`) // @ts-ignore export const checkSave: (nodes: Node[], edges: Edge[], data: any) => void = (nodes, edges, data) => { - if (nodes.filter(n => isEqual('start-node', n.type)).length < 1) { - throw atLeastOneStartNodeError() + if (isEmpty(nodes)) { + throw atLeastOneNode() } - if (nodes.filter(n => isEqual('end-node', n.type)).length < 1) { - throw atLeastOneEndNodeError() + + for (let node of nodes) { + if (!data[node.id] || !data[node.id]?.finished) { + throw hasUnfinishedNode(node.id) + } } } \ No newline at end of file diff --git a/service-web/client/src/components/flow/FlowEditor.tsx b/service-web/client/src/components/flow/FlowEditor.tsx index 6119b6b..8fdc5ec 100644 --- a/service-web/client/src/components/flow/FlowEditor.tsx +++ b/service-web/client/src/components/flow/FlowEditor.tsx @@ -1,4 +1,4 @@ -import {PlusCircleFilled, SaveFilled} from '@ant-design/icons' +import {PlusCircleFilled, RollbackOutlined, SaveFilled} from '@ant-design/icons' import { Background, BackgroundVariant, @@ -9,23 +9,22 @@ import { type NodeProps, ReactFlow } from '@xyflow/react' -import {useMount} from 'ahooks' import type {Schema} from 'amis' -import {Button, Drawer, Dropdown, message, Space} from 'antd' +import {Button, Drawer, Dropdown, message, Popconfirm, Space} from 'antd' import {arrToMap, find, isEqual, isNil, randomId} from 'licia' -import {type JSX, type MemoExoticComponent, useState} from 'react' +import {type JSX, type MemoExoticComponent, useEffect, useState} from 'react' import styled from 'styled-components' import '@xyflow/react/dist/style.css' import {amisRender, commonInfo, horizontalFormOptions} from '../../util/amis.tsx' import {checkAddConnection, checkAddNode, checkSave} from './FlowChecker.tsx' import CodeNode from './node/CodeNode.tsx' -import EndNode from './node/EndNode.tsx' +import OutputNode from './node/OutputNode.tsx' import KnowledgeNode from './node/KnowledgeNode.tsx' import LlmNode from './node/LlmNode.tsx' -import StartNode from './node/StartNode.tsx' import SwitchNode from './node/SwitchNode.tsx' import {useDataStore} from './store/DataStore.ts' import {useFlowStore} from './store/FlowStore.ts' +import {useNavigate} from 'react-router' const FlowableDiv = styled.div` height: 100%; @@ -72,6 +71,7 @@ export type FlowEditorProps = { } function FlowEditor(props: FlowEditorProps) { + const navigate = useNavigate() const [messageApi, contextHolder] = message.useMessage() const [nodeDef] = useState<{ key: string, @@ -79,14 +79,9 @@ function FlowEditor(props: FlowEditorProps) { component: MemoExoticComponent<(props: NodeProps) => JSX.Element> }[]>([ { - key: 'start-node', - name: '开始', - component: StartNode, - }, - { - key: 'end-node', - name: '结束', - component: EndNode, + key: 'output-node', + name: '输出', + component: OutputNode, }, { key: 'llm-node', @@ -145,7 +140,13 @@ function FlowEditor(props: FlowEditorProps) { actionType: 'custom', // @ts-ignore script: (context, action, event) => { - setDataById(id, context.props.data) + setDataById( + id, + { + ...context.props.data, + finished: true, + } + ) setOpen(false) }, }, @@ -202,7 +203,7 @@ function FlowEditor(props: FlowEditorProps) { editNode, } - useMount(() => { + useEffect(() => { // language=JSON // let initialData = JSON.parse('{"nodes":[{"id":"TCxPixrdkI","type":"start-node","position":{"x":-256,"y":109.5},"data":{},"measured":{"width":256,"height":83},"selected":false,"dragging":false},{"id":"tGs78_ietp","type":"llm-node","position":{"x":108,"y":-2.5},"data":{},"measured":{"width":256,"height":105},"selected":false,"dragging":false},{"id":"OeZdaU7LpY","type":"llm-node","position":{"x":111,"y":196},"data":{},"measured":{"width":256,"height":105},"selected":false,"dragging":false},{"id":"LjfoCYZo-E","type":"knowledge-node","position":{"x":497.62196259607214,"y":-10.792497317791003},"data":{},"measured":{"width":256,"height":75},"selected":false,"dragging":false},{"id":"sQM_22GYB5","type":"end-node","position":{"x":874.3164534765615,"y":151.70316541496913},"data":{},"measured":{"width":256,"height":75},"selected":false,"dragging":false},{"id":"KpMH_xc3ZZ","type":"llm-node","position":{"x":529.6286840434341,"y":150.4721376669937},"data":{},"measured":{"width":256,"height":75},"selected":false,"dragging":false},{"id":"pOrR6EMVbe","type":"switch-node","position":{"x":110.33793030183864,"y":373.9551529987239},"data":{},"measured":{"width":256,"height":157},"selected":false,"dragging":false}],"edges":[{"source":"TCxPixrdkI","sourceHandle":"source","target":"tGs78_ietp","targetHandle":"target","id":"xy-edge__TCxPixrdkIsource-tGs78_ietptarget"},{"source":"TCxPixrdkI","sourceHandle":"source","target":"OeZdaU7LpY","targetHandle":"target","id":"xy-edge__TCxPixrdkIsource-OeZdaU7LpYtarget"},{"source":"tGs78_ietp","sourceHandle":"source","target":"LjfoCYZo-E","targetHandle":"target","id":"xy-edge__tGs78_ietpsource-LjfoCYZo-Etarget"},{"source":"LjfoCYZo-E","sourceHandle":"source","target":"KpMH_xc3ZZ","targetHandle":"target","id":"xy-edge__LjfoCYZo-Esource-KpMH_xc3ZZtarget"},{"source":"OeZdaU7LpY","sourceHandle":"source","target":"KpMH_xc3ZZ","targetHandle":"target","id":"xy-edge__OeZdaU7LpYsource-KpMH_xc3ZZtarget"},{"source":"KpMH_xc3ZZ","sourceHandle":"source","target":"sQM_22GYB5","targetHandle":"target","id":"xy-edge__KpMH_xc3ZZsource-sQM_22GYB5target"},{"source":"TCxPixrdkI","sourceHandle":"source","target":"pOrR6EMVbe","id":"xy-edge__TCxPixrdkIsource-pOrR6EMVbe"},{"source":"pOrR6EMVbe","sourceHandle":"3","target":"sQM_22GYB5","targetHandle":"target","id":"xy-edge__pOrR6EMVbe3-sQM_22GYB5target"},{"source":"pOrR6EMVbe","sourceHandle":"1","target":"KpMH_xc3ZZ","targetHandle":"target","id":"xy-edge__pOrR6EMVbe1-KpMH_xc3ZZtarget"}],"data":{"tGs78_ietp":{"model":"qwen3","outputs":{"text":{"type":"string"}},"systemPrompt":"你是个聪明人"},"OeZdaU7LpY":{"model":"qwen3","outputs":{"text":{"type":"string"}},"systemPrompt":"你也是个聪明人"}}}') // let initialData: any = {} @@ -217,7 +218,7 @@ function FlowEditor(props: FlowEditorProps) { } setNodes(initialNodes) setEdges(initialEdges) - }) + }, [props.graphData]) return ( @@ -250,6 +251,16 @@ function FlowEditor(props: FlowEditorProps) { 新增节点 + navigate(-1)} + > + +