25 Commits

Author SHA1 Message Date
d979b3941d feat(ai-web): 完成自研流程图的保存 2025-07-03 23:40:41 +08:00
abdbb5ed03 feat(web): 增加任务和流程图CRUD 2025-07-03 22:21:31 +08:00
v-zhangjc9
8ebaf5de8e feat(web): 优化流程任务编辑 2025-07-03 19:18:17 +08:00
v-zhangjc9
5f7eeb3596 feat(ai-web): 完成任务模板的CRUD 2025-07-03 18:01:36 +08:00
v-zhangjc9
064443f740 feat(ai-web): 移除liteflow入参,该用自己实现的流程引擎 2025-07-03 16:10:02 +08:00
v-zhangjc9
6809750cfa fix(ai-web): 不能设置私有网络访问,会拒绝所有的跨域访问 2025-07-03 10:37:29 +08:00
v-zhangjc9
49cb62b287 fix(bin): 修复pom文件名错误 2025-07-03 10:36:57 +08:00
v-zhangjc9
5cbda28594 fix(gateway): 网关导致重复跨域标记,关闭网关的跨域设置 2025-07-03 10:36:33 +08:00
v-zhangjc9
11c5481287 fix(bin): 修复项目编译时间不正确导致无法识别项目修改状态 2025-07-03 10:01:47 +08:00
v-zhangjc9
67e0cada00 feat(bin): 优化打包脚本,遇到没有修改的模块就跳过发布流程 2025-07-02 17:29:28 +08:00
v-zhangjc9
cdf51cc85f fix(configuration): 优化安全配置 2025-07-02 16:25:06 +08:00
v-zhangjc9
9277d1690c feat(web): 增加常用app list 2025-07-02 15:48:22 +08:00
v-zhangjc9
24ac681cb3 feat(web): 增加装饰 2025-07-02 13:06:10 +08:00
v-zhangjc9
c46da52942 fix(web): 修复访问地址改到了本地测试 2025-07-02 11:28:44 +08:00
v-zhangjc9
7209b52e3d feat(ai-web): 增加JPA建表语句自动生成 2025-07-02 10:54:32 +08:00
v-zhangjc9
959d6fb5c7 feat(ai-web): 完成选择节点 2025-07-01 18:16:05 +08:00
v-zhangjc9
c5c62ab713 feat(ai-web): 完成流程引擎雏形 2025-07-01 15:33:07 +08:00
e59e89a5ad feat(ai-web): 尝试设计流程引擎 2025-06-30 23:31:01 +08:00
b7626180c1 refactor(ai-web): 统一bean工具类 2025-06-30 22:54:40 +08:00
v-zhangjc9
68e54d5110 feat(ai-web): 尝试自建流程引擎 2025-06-30 19:15:19 +08:00
v-zhangjc9
5f133fbfc3 refactor(web): 无聊的改动 2025-06-30 17:15:35 +08:00
v-zhangjc9
d28fbbbba8 fix(web): 优化冗余边检测导致分支节点不正常 2025-06-30 11:14:45 +08:00
v-zhangjc9
67f41c08a0 feat(web): 优化冗余边检测 2025-06-30 10:41:40 +08:00
111ca49815 feat(web): 引入dify的流程检查算法 2025-06-30 00:12:51 +08:00
779fd0eb18 feat(web): 增加分支节点,增加流程检查的测试 2025-06-29 19:02:19 +08:00
71 changed files with 2069 additions and 1100 deletions

1
.gitignore vendored
View File

@@ -110,3 +110,4 @@ Network Trash Folder
Temporary Items Temporary Items
.apdisk .apdisk
**/temp/ **/temp/
.build

View File

@@ -1,5 +1,5 @@
import {$, fetch, fs, glob, os, path, spinner, syncProcessCwd, usePowerShell} from 'zx' import {$, fetch, fs, glob, os, path, spinner, syncProcessCwd, usePowerShell} from 'zx'
import {isEqual, trim, fileSize} from "licia"; import {fileSize, isEqual, trim} from "licia";
import md5file from 'md5-file' import md5file from 'md5-file'
syncProcessCwd(true) syncProcessCwd(true)
@@ -41,20 +41,70 @@ const millisecondToString = (timestamp) => {
return parts.join('') return parts.join('')
} }
const dotBuildPath = () => `.build`
const modifiedDataPath = () => `${dotBuildPath()}/modified_time.json`
const readModifiedTimeData = async () => {
if (!fs.existsSync(dotBuildPath())) {
fs.mkdirSync(dotBuildPath(), {recursive: true})
}
if (!(await fs.exists(modifiedDataPath()))) {
fs.writeFileSync(modifiedDataPath(), '{}')
}
return JSON.parse(await fs.readFile(modifiedDataPath(), 'utf-8'))
}
const updateModifiedTimeData = (data) => {
fs.writeFileSync(modifiedDataPath(), JSON.stringify(data, null, 2))
}
const isModified = async (target) => {
if (!target || !(await fs.exists(target))) {
throw new Error("Target 不存在")
}
let stat = fs.statSync(target)
let currentModifiedTime = stat.mtimeMs
let lastModifiedTime = (await readModifiedTimeData())[target]
return !(lastModifiedTime && isEqual(currentModifiedTime, lastModifiedTime));
}
const updateModifiedTime = async (target) => {
if (!target || !(await fs.exists(target))) {
throw new Error("Target 不存在")
}
let stat = fs.statSync(target)
let currentModifiedTime = stat.mtimeMs
let modifiedTimeData = await readModifiedTimeData()
modifiedTimeData[target] = currentModifiedTime
updateModifiedTimeData(modifiedTimeData)
}
export const run_deploy = async (project) => { export const run_deploy = async (project) => {
if (!(await isModified(project))) {
console.log(`✅ Skip deploy ${project}`)
return
}
let output = await spinner( let output = await spinner(
`Deploying project ${project}`, `Deploying project ${project}`,
() => $`mvn -pl ${project} clean deploy -D skipTests -s ${maven_setting}` () => $`mvn -pl ${project} clean deploy -D skipTests -s ${maven_setting}`
) )
console.log(`✅ Finished deploy ${project} (${millisecondToString(output['duration'])})`) console.log(`✅ Finished deploy ${project} (${millisecondToString(output['duration'])})`)
await updateModifiedTime(project)
} }
export const run_deploy_root = async () => { export const run_deploy_root = async () => {
if (!(await isModified('pom.xml'))) {
console.log(`✅ Skip deploy root`)
return
}
let output = await spinner( let output = await spinner(
`Deploying root`, `Deploying root`,
() => $`mvn clean deploy -N -D skipTests -s ${maven_setting}` () => $`mvn clean deploy -N -D skipTests -s ${maven_setting}`
) )
console.log(`✅ Finished deploy root (${millisecondToString(output['duration'])})`) console.log(`✅ Finished deploy root (${millisecondToString(output['duration'])})`)
await updateModifiedTime('pom.xml')
} }
export const run_deploy_batch = async (projects) => { export const run_deploy_batch = async (projects) => {

3
bin/test.js Normal file
View File

@@ -0,0 +1,3 @@
import {isModified} from './library.js'
console.log(await isModified('/Users/lanyuanxiaoyao/Project/IdeaProjects/hudi-service/pom.xml'))

View File

@@ -0,0 +1,82 @@
create table hudi_collect_build_b12.service_ai_feedback
(
id bigint not null comment '记录唯一标记',
created_time datetime(6) comment '记录创建时间',
modified_time datetime(6) comment '记录更新时间',
analysis longtext comment 'AI的分析结果',
conclusion longtext comment 'AI的解决方案',
source longtext not null comment '原始报障说明',
status enum ('ANALYSIS_PROCESSING','ANALYSIS_SUCCESS','FINISHED') not null comment '报障处理状态',
primary key (id)
) comment ='报障信息记录' charset = utf8mb4;
create table hudi_collect_build_b12.service_ai_feedback_pictures
(
feedback_id bigint not null,
pictures_id bigint not null,
primary key (feedback_id, pictures_id)
) comment ='报障相关截图' charset = utf8mb4;
alter table hudi_collect_build_b12.service_ai_feedback_pictures
add constraint UK3npjcyjyqfbdlf2v5tj64j2g3 unique (pictures_id);
create table hudi_collect_build_b12.service_ai_file
(
id bigint not null comment '记录唯一标记',
created_time datetime(6) comment '记录创建时间',
modified_time datetime(6) comment '记录更新时间',
filename varchar(255) comment '文件名称',
md5 varchar(255) comment '文件的md5编码用于校验文件的完整性',
path varchar(255) comment '文件在主机上存储的实际路径',
size bigint comment '文件大小单位是byte',
type varchar(255) comment '文件类型,通常记录的是文件的后缀名',
primary key (id)
) comment ='记录上传的文件存储信息' charset = utf8mb4;
create table hudi_collect_build_b12.service_ai_flow_task
(
id bigint not null comment '记录唯一标记',
created_time datetime(6) comment '记录创建时间',
modified_time datetime(6) comment '记录更新时间',
error longtext comment '任务运行产生的报错',
input longtext comment '任务输入',
result longtext comment '任务运行结果',
status enum ('ERROR','FINISHED','RUNNING') not null comment '任务运行状态',
template_id bigint not null comment '流程任务对应的模板',
primary key (id)
) comment ='流程任务记录' charset = utf8mb4;
create table hudi_collect_build_b12.service_ai_flow_task_template
(
id bigint not null comment '记录唯一标记',
created_time datetime(6) comment '记录创建时间',
modified_time datetime(6) comment '记录更新时间',
description varchar(255) comment '模板功能、内容说明',
flow_graph longtext not null comment '前端流程图数据',
input_schema longtext not null comment '模板入参Schema',
name varchar(255) not null comment '模板名称',
primary key (id)
) comment ='流程任务模板' charset = utf8mb4;
create table hudi_collect_build_b12.service_ai_group
(
id bigint not null comment '记录唯一标记',
created_time datetime(6) comment '记录创建时间',
modified_time datetime(6) comment '记录更新时间',
name varchar(255) not null comment '分组名称',
status enum ('FINISHED','RUNNING') not null comment '分组处理状态',
knowledge_id bigint not null,
primary key (id)
) comment ='知识库下包含的分组' charset = utf8mb4;
create table hudi_collect_build_b12.service_ai_knowledge
(
id bigint not null comment '记录唯一标记',
created_time datetime(6) comment '记录创建时间',
modified_time datetime(6) comment '记录更新时间',
description longtext not null comment '知识库说明',
name varchar(255) not null comment '知识库名称',
strategy enum ('Cosine','Euclid') not null comment '知识库策略',
vector_source_id bigint not null comment '知识库对应的向量库名',
primary key (id)
) comment ='知识库' charset = utf8mb4;

View File

@@ -1,18 +0,0 @@
CREATE TABLE `service_ai_feedback`
(
`id` bigint NOT NULL,
`created_time` datetime(6) DEFAULT NULL,
`modified_time` datetime(6) DEFAULT NULL,
`analysis` longtext,
`conclusion` longtext,
`source` longtext NOT NULL,
`status` tinyint NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET = utf8mb4;
CREATE TABLE `service_ai_feedback_pictures`
(
`feedback_id` bigint NOT NULL,
`pictures_id` bigint NOT NULL,
PRIMARY KEY (`feedback_id`, `pictures_id`)
) DEFAULT CHARSET = utf8mb4;

View File

@@ -1,12 +0,0 @@
CREATE TABLE `service_ai_file`
(
`id` bigint NOT NULL,
`created_time` datetime(6) DEFAULT NULL,
`modified_time` datetime(6) DEFAULT NULL,
`filename` varchar(255) DEFAULT NULL,
`md5` varchar(255) DEFAULT NULL,
`path` varchar(255) DEFAULT NULL,
`size` bigint DEFAULT NULL,
`type` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET = utf8mb4;

View File

@@ -1,10 +0,0 @@
CREATE TABLE `service_ai_group`
(
`id` bigint NOT NULL,
`created_time` datetime(6) DEFAULT NULL,
`modified_time` datetime(6) DEFAULT NULL,
`name` varchar(255) NOT NULL,
`status` tinyint NOT NULL,
`knowledge_id` bigint NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8mb4;

View File

@@ -1,11 +0,0 @@
CREATE TABLE `service_ai_knowledge`
(
`id` bigint NOT NULL,
`created_time` datetime(6) DEFAULT NULL,
`modified_time` datetime(6) DEFAULT NULL,
`description` longtext NOT NULL,
`name` varchar(255) NOT NULL,
`strategy` tinyint NOT NULL,
`vector_source_id` bigint NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET = utf8mb4;

View File

@@ -30,7 +30,6 @@ public class SecurityConfig {
configuration.addAllowedHeader("*"); configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*"); configuration.addAllowedMethod("*");
configuration.setMaxAge(7200L); configuration.setMaxAge(7200L);
configuration.setAllowPrivateNetwork(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration); source.registerCorsConfiguration("/**", configuration);
return new CorsFilter(source); return new CorsFilter(source);

View File

@@ -82,6 +82,13 @@
<groupId>org.noear</groupId> <groupId>org.noear</groupId>
<artifactId>solon-ai-dialect-openai</artifactId> <artifactId>solon-ai-dialect-openai</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-ant</artifactId>
<version>6.6.8.Final</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@@ -2,15 +2,12 @@ package com.lanyuanxiaoyao.service.ai.web;
import com.blinkfox.fenix.EnableFenix; import com.blinkfox.fenix.EnableFenix;
import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties; import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
import org.springframework.beans.BeansException;
import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner; import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.retry.annotation.EnableRetry; import org.springframework.retry.annotation.EnableRetry;
import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.EnableScheduling;
@@ -27,27 +24,13 @@ import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling @EnableScheduling
@EnableFenix @EnableFenix
@EnableJpaAuditing @EnableJpaAuditing
public class WebApplication implements ApplicationRunner, ApplicationContextAware { public class WebApplication implements ApplicationRunner {
private static ApplicationContext context;
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args); SpringApplication.run(WebApplication.class, args);
} }
public static <T> T getBean(Class<T> clazz) {
return context.getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) {
return context.getBean(name, clazz);
}
@Override @Override
public void run(ApplicationArguments args) { public void run(ApplicationArguments args) {
} }
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
WebApplication.context = context;
}
} }

View File

@@ -7,6 +7,7 @@ import jakarta.persistence.MappedSuperclass;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import org.hibernate.annotations.Comment;
import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@@ -22,6 +23,7 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@MappedSuperclass @MappedSuperclass
@EntityListeners(AuditingEntityListener.class) @EntityListeners(AuditingEntityListener.class)
public class IdOnlyEntity { public class IdOnlyEntity {
@Comment("记录唯一标记")
@Id @Id
@GeneratedValue(generator = "snowflake") @GeneratedValue(generator = "snowflake")
@GenericGenerator(name = "snowflake", strategy = "com.lanyuanxiaoyao.service.ai.web.configuration.SnowflakeIdGenerator") @GenericGenerator(name = "snowflake", strategy = "com.lanyuanxiaoyao.service.ai.web.configuration.SnowflakeIdGenerator")

View File

@@ -6,6 +6,7 @@ import java.time.LocalDateTime;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import org.hibernate.annotations.Comment;
import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@@ -22,8 +23,10 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@MappedSuperclass @MappedSuperclass
@EntityListeners(AuditingEntityListener.class) @EntityListeners(AuditingEntityListener.class)
public class SimpleEntity extends IdOnlyEntity { public class SimpleEntity extends IdOnlyEntity {
@Comment("记录创建时间")
@CreatedDate @CreatedDate
private LocalDateTime createdTime; private LocalDateTime createdTime;
@Comment("记录更新时间")
@LastModifiedDate @LastModifiedDate
private LocalDateTime modifiedTime; private LocalDateTime modifiedTime;
} }

View File

@@ -0,0 +1,24 @@
package com.lanyuanxiaoyao.service.ai.web.configuration;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringBeanGetter implements ApplicationContextAware {
private static ApplicationContext context;
public static <T> T getBean(Class<T> clazz) {
return context.getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) {
return context.getBean(name, clazz);
}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
SpringBeanGetter.context = context;
}
}

View File

@@ -1,13 +1,22 @@
package com.lanyuanxiaoyao.service.ai.web.controller.task; 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.AmisResponse;
import com.lanyuanxiaoyao.service.ai.web.base.controller.SimpleControllerSupport; import com.lanyuanxiaoyao.service.ai.web.base.controller.SimpleControllerSupport;
import com.lanyuanxiaoyao.service.ai.web.base.entity.SimpleItem; import com.lanyuanxiaoyao.service.ai.web.base.entity.SimpleItem;
import com.lanyuanxiaoyao.service.ai.web.entity.FlowTaskTemplate; import com.lanyuanxiaoyao.service.ai.web.entity.FlowTaskTemplate;
import com.lanyuanxiaoyao.service.ai.web.service.task.FlowTaskTemplateService; import com.lanyuanxiaoyao.service.ai.web.service.task.FlowTaskTemplateService;
import java.util.Map;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.mapstruct.Context;
import org.mapstruct.factory.Mappers; 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.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@@ -15,13 +24,25 @@ import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@RequestMapping("flow_task/template") @RequestMapping("flow_task/template")
public class TaskTemplateController extends SimpleControllerSupport<FlowTaskTemplate, TaskTemplateController.SaveItem, TaskTemplateController.ListItem, TaskTemplateController.DetailItem> { public class TaskTemplateController extends SimpleControllerSupport<FlowTaskTemplate, TaskTemplateController.SaveItem, TaskTemplateController.ListItem, TaskTemplateController.DetailItem> {
public TaskTemplateController(FlowTaskTemplateService flowTaskTemplateService) { private final FlowTaskTemplateService flowTaskTemplateService;
private final ObjectMapper mapper;
public TaskTemplateController(FlowTaskTemplateService flowTaskTemplateService, Jackson2ObjectMapperBuilder builder) {
super(flowTaskTemplateService); super(flowTaskTemplateService);
this.flowTaskTemplateService = flowTaskTemplateService;
this.mapper = builder.build();
}
@PostMapping("update_flow_graph")
public AmisResponse<?> updateFlowGraph(@RequestBody UpdateGraphItem item) throws JsonProcessingException {
flowTaskTemplateService.updateFlowGraph(item.getId(), mapper.writeValueAsString(item.getGraph()));
return AmisResponse.responseSuccess();
} }
@Override @Override
protected SaveItemMapper<FlowTaskTemplate, SaveItem> saveItemMapper() { protected SaveItemMapper<FlowTaskTemplate, SaveItem> saveItemMapper() {
return Mappers.getMapper(SaveItem.Mapper.class); SaveItem.Mapper map = Mappers.getMapper(SaveItem.Mapper.class);
return item -> map.from(item, mapper);
} }
@Override @Override
@@ -31,18 +52,24 @@ public class TaskTemplateController extends SimpleControllerSupport<FlowTaskTemp
@Override @Override
protected DetailItemMapper<FlowTaskTemplate, DetailItem> detailItemMapper() { protected DetailItemMapper<FlowTaskTemplate, DetailItem> detailItemMapper() {
return Mappers.getMapper(DetailItem.Mapper.class); DetailItem.Mapper map = Mappers.getMapper(DetailItem.Mapper.class);
return template -> map.from(template, mapper);
} }
@Data @Data
public static final class SaveItem { public static final class SaveItem {
private Long id;
private String name; private String name;
private String description; private String description;
private String inputSchema; private Map<String, Object> inputSchema;
private String flow;
@org.mapstruct.Mapper @org.mapstruct.Mapper
public interface Mapper extends SaveItemMapper<FlowTaskTemplate, SaveItem> { public static abstract class Mapper {
public abstract FlowTaskTemplate from(SaveItem saveItem, @Context ObjectMapper mapper) throws Exception;
protected String mapInputSchema(Map<String, Object> inputSchema, @Context ObjectMapper mapper) throws JsonProcessingException {
return mapper.writeValueAsString(inputSchema);
}
} }
} }
@@ -62,11 +89,23 @@ public class TaskTemplateController extends SimpleControllerSupport<FlowTaskTemp
public static class DetailItem extends SimpleItem { public static class DetailItem extends SimpleItem {
private String name; private String name;
private String description; private String description;
private String inputSchema; private Map<String, Object> inputSchema;
private String flow; private Map<String, Object> flowGraph;
@org.mapstruct.Mapper @org.mapstruct.Mapper
public interface Mapper extends DetailItemMapper<FlowTaskTemplate, DetailItem> { public static abstract class Mapper {
public abstract DetailItem from(FlowTaskTemplate template, @Context ObjectMapper mapper) throws Exception;
public Map<String, Object> mapJson(String source, @Context ObjectMapper mapper) throws Exception {
return mapper.readValue(source, new TypeReference<>() {
});
}
} }
} }
@Data
public static class UpdateGraphItem {
private Long id;
private Map<String, Object> graph;
}
} }

View File

@@ -0,0 +1,27 @@
package com.lanyuanxiaoyao.service.ai.web.engine;
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowGraph;
import com.lanyuanxiaoyao.service.ai.web.engine.store.FlowStore;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.collections.api.map.ImmutableMap;
/**
* 流程执行器
*
* @author lanyuanxiaoyao
* @version 20250630
*/
public class FlowExecutor {
private final FlowStore flowStore;
private final ImmutableMap<String, Class<? extends FlowNodeRunner>> runnerMap;
public FlowExecutor(FlowStore flowStore, ImmutableMap<String, Class<? extends FlowNodeRunner>> runnerMap) {
this.flowStore = flowStore;
this.runnerMap = runnerMap;
}
public void execute(FlowGraph graph) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
var runner = new FlowGraphRunner(graph, flowStore, runnerMap);
runner.run();
}
}

View File

@@ -0,0 +1,107 @@
package com.lanyuanxiaoyao.service.ai.web.engine;
import cn.hutool.core.util.StrUtil;
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowContext;
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowEdge;
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowGraph;
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowNode;
import com.lanyuanxiaoyao.service.ai.web.engine.store.FlowStore;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.Queue;
import org.eclipse.collections.api.map.ImmutableMap;
import org.eclipse.collections.api.multimap.set.ImmutableSetMultimap;
/**
* Graph执行器
*
* @author lanyuanxiaoyao
* @version 20250701
*/
public final class FlowGraphRunner {
private final FlowGraph flowGraph;
private final FlowStore flowStore;
private final ImmutableMap<String, Class<? extends FlowNodeRunner>> nodeRunnerClass;
private final Queue<FlowNode> executionQueue = new LinkedList<>();
private final ImmutableSetMultimap<String, FlowEdge> nodeInputMap;
private final ImmutableSetMultimap<String, FlowEdge> nodeOutputMap;
private final ImmutableMap<String, FlowNode> nodeMap;
public FlowGraphRunner(FlowGraph flowGraph, FlowStore flowStore, ImmutableMap<String, Class<? extends FlowNodeRunner>> nodeRunnerClass) {
this.flowGraph = flowGraph;
this.flowStore = flowStore;
this.nodeRunnerClass = nodeRunnerClass;
nodeInputMap = flowGraph.edges().groupBy(FlowEdge::target);
nodeOutputMap = flowGraph.edges().groupBy(FlowEdge::source);
nodeMap = flowGraph.nodes().toImmutableMap(FlowNode::id, node -> node);
}
public void run() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
flowStore.init(flowGraph);
var context = new FlowContext();
for (FlowNode node : flowGraph.nodes()) {
executionQueue.offer(node);
}
while (!executionQueue.isEmpty()) {
var node = executionQueue.poll();
process(node, context);
}
}
private void process(FlowNode node, FlowContext context) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
if (
(
// 没有入节点,即开始节点
!nodeInputMap.containsKey(node.id())
// 或者所有入的边状态都已经完成
|| nodeInputMap.get(node.id()).allSatisfy(edge -> flowStore.checkEdgeStatus(flowGraph.id(), edge.id(), FlowEdge.Status.EXECUTE, FlowEdge.Status.SKIP))
)
// 当前节点还未执行
&& flowStore.checkNodeStatus(flowGraph.id(), node.id(), FlowNode.Status.INITIAL)
) {
// 是开始节点或入的边有至少一条是「执行」
if (
!nodeInputMap.containsKey(node.id())
|| nodeInputMap.get(node.id()).anySatisfy(edge -> flowStore.checkEdgeStatus(flowGraph.id(), edge.id(), FlowEdge.Status.EXECUTE))
) {
flowStore.updateNodeToRunning(flowGraph.id(), node.id());
var runnerClazz = nodeRunnerClass.get(node.type());
var runner = runnerClazz.getDeclaredConstructor().newInstance();
runner.setNodeId(node.id());
runner.setContext(context);
runner.run();
if (runner instanceof FlowNodeOptionalRunner) {
var targetPoint = ((FlowNodeOptionalRunner) runner).getTargetPoint();
for (FlowEdge edge : nodeOutputMap.get(node.id())) {
if (StrUtil.equals(targetPoint, edge.sourcePoint())) {
flowStore.updateEdgeToExecute(flowGraph.id(), edge.id());
} else {
flowStore.updateEdgeToSkip(flowGraph.id(), edge.id());
}
executionQueue.offer(nodeMap.get(edge.target()));
}
} else {
for (FlowEdge edge : nodeOutputMap.get(node.id())) {
flowStore.updateEdgeToExecute(flowGraph.id(), edge.id());
executionQueue.offer(nodeMap.get(edge.target()));
}
}
flowStore.updateNodeToFinished(flowGraph.id(), node.id());
}
// 所有入的边都是跳过,当前节点就跳过
else {
flowStore.updateNodeToSkipped(flowGraph.id(), node.id());
for (FlowEdge edge : nodeOutputMap.get(node.id())) {
flowStore.updateEdgeToSkip(flowGraph.id(), edge.id());
executionQueue.offer(nodeMap.get(edge.target()));
}
}
}
}
}

View File

@@ -0,0 +1,15 @@
package com.lanyuanxiaoyao.service.ai.web.engine;
import lombok.Getter;
public abstract class FlowNodeOptionalRunner extends FlowNodeRunner {
@Getter
private String targetPoint;
public abstract String runOptional();
@Override
public void run() {
this.targetPoint = runOptional();
}
}

View File

@@ -0,0 +1,31 @@
package com.lanyuanxiaoyao.service.ai.web.engine;
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowContext;
import lombok.Getter;
public abstract class FlowNodeRunner {
@Getter
private String nodeId;
@Getter
private FlowContext context;
public abstract void run();
void setNodeId(String nodeId) {
this.nodeId = nodeId;
}
void setContext(FlowContext context) {
this.context = context;
}
protected <T> T getData(String key) {
var data = context.get(nodeId);
return (T) data.get(key);
}
protected <T> void setData(String key, T value) {
var data = context.get(nodeId);
data.put(key, value);
}
}

View File

@@ -0,0 +1,17 @@
package com.lanyuanxiaoyao.service.ai.web.engine.entity;
import lombok.Data;
import org.eclipse.collections.api.factory.Maps;
import org.eclipse.collections.api.map.MutableMap;
@Data
public class FlowContext {
private MutableMap<String, MutableMap<String, Object>> data = Maps.mutable.<String, MutableMap<String, Object>>empty().asSynchronized();
public MutableMap<String, Object> get(String key) {
if (!data.containsKey(key)) {
data.put(key, Maps.mutable.<String, Object>empty().asSynchronized());
}
return data.get(key);
}
}

View File

@@ -0,0 +1,36 @@
package com.lanyuanxiaoyao.service.ai.web.engine.entity;
import java.time.LocalDateTime;
/**
* 流程图中的边
*
* @author lanyuanxiaoyao
* @version 20250630
*/
public record FlowEdge(
String id,
String source,
String target,
String sourcePoint,
String targetPoint
) {
public enum Status {
INITIAL, EXECUTE, SKIP
}
public record State(
String id,
Status status,
LocalDateTime startingTime,
LocalDateTime finishedTime
) {
public State(String edgeId) {
this(edgeId, Status.INITIAL, LocalDateTime.now(), null);
}
public State(String edgeId, Status status) {
this(edgeId, status, LocalDateTime.now(), null);
}
}
}

View File

@@ -0,0 +1,16 @@
package com.lanyuanxiaoyao.service.ai.web.engine.entity;
import org.eclipse.collections.api.set.ImmutableSet;
/**
* 流程图
*
* @author lanyuanxiaoyao
* @version 20250630
*/
public record FlowGraph(
String id,
ImmutableSet<FlowNode> nodes,
ImmutableSet<FlowEdge> edges
) {
}

View File

@@ -0,0 +1,33 @@
package com.lanyuanxiaoyao.service.ai.web.engine.entity;
import java.time.LocalDateTime;
/**
* 流程图中的节点
*
* @author lanyuanxiaoyao
* @version 20250630
*/
public record FlowNode(
String id,
String type
) {
public enum Status {
INITIAL, RUNNING, FINISHED, SKIPPED
}
public record State(
String id,
Status status,
LocalDateTime startingTime,
LocalDateTime finishedTime
) {
public State(String nodeId) {
this(nodeId, Status.INITIAL, LocalDateTime.now(), null);
}
public State(String nodeId, Status status) {
this(nodeId, status, LocalDateTime.now(), null);
}
}
}

View File

@@ -0,0 +1,31 @@
package com.lanyuanxiaoyao.service.ai.web.engine.store;
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowEdge;
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowGraph;
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowNode;
/**
* 存储状态
*
* @author lanyuanxiaoyao
* @version 20250701
*/
public interface FlowStore {
void init(FlowGraph flowGraph);
void updateNodeToRunning(String graphId, String nodeId);
void updateNodeToSkipped(String graphId, String nodeId);
void updateNodeToFinished(String graphId, String nodeId);
void updateEdgeToExecute(String graphId, String edgeId);
void updateEdgeToSkip(String graphId, String edgeId);
boolean checkNodeStatus(String graphId, String nodeId, FlowNode.Status... statuses);
boolean checkEdgeStatus(String graphId, String edgeId, FlowEdge.Status... statuses);
void print();
}

View File

@@ -0,0 +1,107 @@
package com.lanyuanxiaoyao.service.ai.web.engine.store;
import cn.hutool.core.util.ArrayUtil;
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowEdge;
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowGraph;
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowNode;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.collections.api.factory.Maps;
import org.eclipse.collections.api.map.MutableMap;
/**
* 基于内存的流程状态存储
*
* @author lanyuanxiaoyao
* @version 20250701
*/
@Slf4j
public class InMemoryFlowStore implements FlowStore {
private static final MutableMap<String, FlowNode.State> flowNodeStateMap = Maps.mutable.<String, FlowNode.State>empty().asSynchronized();
private static final MutableMap<String, FlowEdge.State> flowEdgeStateMap = Maps.mutable.<String, FlowEdge.State>empty().asSynchronized();
private String multiKey(String... key) {
return String.join("-", key);
}
@Override
public void init(FlowGraph flowGraph) {
for (FlowNode node : flowGraph.nodes()) {
flowNodeStateMap.put(multiKey(flowGraph.id(), node.id()), new FlowNode.State(node.id()));
}
for (FlowEdge edge : flowGraph.edges()) {
flowEdgeStateMap.put(multiKey(flowGraph.id(), edge.id()), new FlowEdge.State(edge.id()));
}
}
@Override
public void updateNodeToRunning(String graphId, String nodeId) {
flowNodeStateMap.updateValue(
multiKey(graphId, nodeId),
() -> new FlowNode.State(nodeId, FlowNode.Status.RUNNING),
old -> new FlowNode.State(nodeId, FlowNode.Status.RUNNING, old.startingTime(), old.finishedTime())
);
}
@Override
public void updateNodeToSkipped(String graphId, String nodeId) {
flowNodeStateMap.updateValue(
multiKey(graphId, nodeId),
() -> new FlowNode.State(nodeId, FlowNode.Status.SKIPPED),
old -> new FlowNode.State(nodeId, FlowNode.Status.SKIPPED, old.startingTime(), old.finishedTime())
);
}
@Override
public void updateNodeToFinished(String graphId, String nodeId) {
flowNodeStateMap.updateValue(
multiKey(graphId, nodeId),
() -> new FlowNode.State(nodeId, FlowNode.Status.FINISHED),
old -> new FlowNode.State(nodeId, FlowNode.Status.FINISHED, old.startingTime(), old.finishedTime())
);
}
@Override
public void updateEdgeToExecute(String graphId, String edgeId) {
flowEdgeStateMap.updateValue(
multiKey(graphId, edgeId),
() -> new FlowEdge.State(edgeId, FlowEdge.Status.EXECUTE),
old -> new FlowEdge.State(edgeId, FlowEdge.Status.EXECUTE, old.startingTime(), old.finishedTime())
);
}
@Override
public void updateEdgeToSkip(String graphId, String edgeId) {
flowEdgeStateMap.updateValue(
multiKey(graphId, edgeId),
() -> new FlowEdge.State(edgeId, FlowEdge.Status.SKIP),
old -> new FlowEdge.State(edgeId, FlowEdge.Status.SKIP, old.startingTime(), old.finishedTime())
);
}
@Override
public boolean checkNodeStatus(String graphId, String nodeId, FlowNode.Status... statuses) {
String key = multiKey(graphId, nodeId);
if (flowNodeStateMap.containsKey(key)) {
return ArrayUtil.contains(statuses, flowNodeStateMap.get(key).status());
}
return false;
}
@Override
public boolean checkEdgeStatus(String graphId, String edgeId, FlowEdge.Status... statuses) {
String key = multiKey(graphId, edgeId);
if (flowEdgeStateMap.containsKey(key)) {
return ArrayUtil.contains(statuses, flowEdgeStateMap.get(key).status());
}
return false;
}
@Override
public void print() {
log.info("====== Flow Store ======");
log.info("====== Flow Node ======");
flowNodeStateMap.forEachKeyValue((key, value) -> log.info("{}: {}", key, value.status()));
log.info("====== Flow Edge ======");
flowEdgeStateMap.forEachKeyValue((key, value) -> log.info("{}: {}", key, value.status()));
}
}

View File

@@ -8,6 +8,7 @@ import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import org.hibernate.annotations.Comment;
import org.hibernate.annotations.DynamicUpdate; import org.hibernate.annotations.DynamicUpdate;
/** /**
@@ -23,11 +24,17 @@ import org.hibernate.annotations.DynamicUpdate;
@DynamicUpdate @DynamicUpdate
@Table(catalog = Constants.DATABASE_NAME, name = "service_ai_file") @Table(catalog = Constants.DATABASE_NAME, name = "service_ai_file")
@NoArgsConstructor @NoArgsConstructor
@Comment("记录上传的文件存储信息")
public class DataFile extends SimpleEntity { public class DataFile extends SimpleEntity {
@Comment("文件名称")
private String filename; private String filename;
@Comment("文件大小单位是byte")
private Long size; private Long size;
@Comment("文件的md5编码用于校验文件的完整性")
private String md5; private String md5;
@Comment("文件在主机上存储的实际路径")
private String path; private String path;
@Comment("文件类型,通常记录的是文件的后缀名")
private String type; private String type;
public DataFile(String filename) { public DataFile(String filename) {

View File

@@ -6,6 +6,8 @@ import jakarta.persistence.Column;
import jakarta.persistence.ConstraintMode; import jakarta.persistence.ConstraintMode;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners; import jakarta.persistence.EntityListeners;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType; import jakarta.persistence.FetchType;
import jakarta.persistence.ForeignKey; import jakarta.persistence.ForeignKey;
import jakarta.persistence.JoinTable; import jakarta.persistence.JoinTable;
@@ -17,6 +19,7 @@ import java.util.Set;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import org.hibernate.annotations.Comment;
import org.hibernate.annotations.DynamicUpdate; import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@@ -30,18 +33,25 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@NamedEntityGraph(name = "feedback.detail", attributeNodes = { @NamedEntityGraph(name = "feedback.detail", attributeNodes = {
@NamedAttributeNode("pictures") @NamedAttributeNode("pictures")
}) })
@Comment("报障信息记录")
public class Feedback extends SimpleEntity { public class Feedback extends SimpleEntity {
@Comment("原始报障说明")
@Column(nullable = false, columnDefinition = "longtext") @Column(nullable = false, columnDefinition = "longtext")
private String source; private String source;
@Comment("报障相关截图")
@OneToMany(fetch = FetchType.EAGER) @OneToMany(fetch = FetchType.EAGER)
@JoinTable(catalog = Constants.DATABASE_NAME, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) @JoinTable(catalog = Constants.DATABASE_NAME, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude @ToString.Exclude
private Set<DataFile> pictures; private Set<DataFile> pictures;
@Comment("AI的分析结果")
@Column(columnDefinition = "longtext") @Column(columnDefinition = "longtext")
private String analysis; private String analysis;
@Comment("AI的解决方案")
@Column(columnDefinition = "longtext") @Column(columnDefinition = "longtext")
private String conclusion; private String conclusion;
@Comment("报障处理状态")
@Column(nullable = false) @Column(nullable = false)
@Enumerated(EnumType.STRING)
private Status status = Status.ANALYSIS_PROCESSING; private Status status = Status.ANALYSIS_PROCESSING;
public enum Status { public enum Status {

View File

@@ -6,6 +6,8 @@ import jakarta.persistence.Column;
import jakarta.persistence.ConstraintMode; import jakarta.persistence.ConstraintMode;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners; import jakarta.persistence.EntityListeners;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.ForeignKey; import jakarta.persistence.ForeignKey;
import jakarta.persistence.JoinColumn; import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne; import jakarta.persistence.ManyToOne;
@@ -13,6 +15,7 @@ import jakarta.persistence.Table;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import org.hibernate.annotations.Comment;
import org.hibernate.annotations.DynamicUpdate; import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@@ -23,16 +26,23 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@DynamicUpdate @DynamicUpdate
@EntityListeners(AuditingEntityListener.class) @EntityListeners(AuditingEntityListener.class)
@Table(catalog = Constants.DATABASE_NAME, name = "service_ai_flow_task") @Table(catalog = Constants.DATABASE_NAME, name = "service_ai_flow_task")
@Comment("流程任务记录")
public class FlowTask extends SimpleEntity { public class FlowTask extends SimpleEntity {
@Comment("流程任务对应的模板")
@ManyToOne @ManyToOne
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private FlowTaskTemplate template; private FlowTaskTemplate template;
@Comment("任务输入")
@Column(columnDefinition = "longtext") @Column(columnDefinition = "longtext")
private String input; private String input;
@Comment("任务运行状态")
@Column(nullable = false) @Column(nullable = false)
@Enumerated(EnumType.STRING)
private Status status = Status.RUNNING; private Status status = Status.RUNNING;
@Comment("任务运行产生的报错")
@Column(columnDefinition = "longtext") @Column(columnDefinition = "longtext")
private String error; private String error;
@Comment("任务运行结果")
@Column(columnDefinition = "longtext") @Column(columnDefinition = "longtext")
private String result; private String result;

View File

@@ -9,6 +9,7 @@ import jakarta.persistence.Table;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import org.hibernate.annotations.Comment;
import org.hibernate.annotations.DynamicUpdate; import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@@ -19,14 +20,17 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@DynamicUpdate @DynamicUpdate
@EntityListeners(AuditingEntityListener.class) @EntityListeners(AuditingEntityListener.class)
@Table(catalog = Constants.DATABASE_NAME, name = "service_ai_flow_task_template") @Table(catalog = Constants.DATABASE_NAME, name = "service_ai_flow_task_template")
@Comment("流程任务模板")
public class FlowTaskTemplate extends SimpleEntity { public class FlowTaskTemplate extends SimpleEntity {
@Comment("模板名称")
@Column(nullable = false) @Column(nullable = false)
private String name; private String name;
@Comment("模板功能、内容说明")
private String description; private String description;
@Comment("模板入参Schema")
@Column(nullable = false, columnDefinition = "longtext") @Column(nullable = false, columnDefinition = "longtext")
private String inputSchema; private String inputSchema;
@Column(nullable = false, columnDefinition = "text") @Comment("前端流程图数据")
private String flow; @Column(nullable = false, columnDefinition = "longtext")
@Column(columnDefinition = "longtext") private String flowGraph = "{}";
private String flowGraph;
} }

View File

@@ -6,6 +6,8 @@ import jakarta.persistence.Column;
import jakarta.persistence.ConstraintMode; import jakarta.persistence.ConstraintMode;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners; import jakarta.persistence.EntityListeners;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType; import jakarta.persistence.FetchType;
import jakarta.persistence.ForeignKey; import jakarta.persistence.ForeignKey;
import jakarta.persistence.JoinColumn; import jakarta.persistence.JoinColumn;
@@ -14,6 +16,7 @@ import jakarta.persistence.Table;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import org.hibernate.annotations.Comment;
import org.hibernate.annotations.DynamicUpdate; import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@@ -28,10 +31,14 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@DynamicUpdate @DynamicUpdate
@EntityListeners(AuditingEntityListener.class) @EntityListeners(AuditingEntityListener.class)
@Table(catalog = Constants.DATABASE_NAME, name = "service_ai_group") @Table(catalog = Constants.DATABASE_NAME, name = "service_ai_group")
@Comment("知识库内的逻辑分组,比如一个文件是一个分组或一次上传的所有文本是一个分组,可以自由使用而不是限于文件范畴")
public class Group extends SimpleEntity { public class Group extends SimpleEntity {
@Comment("分组名称")
@Column(nullable = false) @Column(nullable = false)
private String name; private String name;
@Comment("分组处理状态")
@Column(nullable = false) @Column(nullable = false)
@Enumerated(EnumType.STRING)
private Status status = Status.RUNNING; private Status status = Status.RUNNING;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)

View File

@@ -6,6 +6,8 @@ import jakarta.persistence.CascadeType;
import jakarta.persistence.Column; import jakarta.persistence.Column;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners; import jakarta.persistence.EntityListeners;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType; import jakarta.persistence.FetchType;
import jakarta.persistence.OneToMany; import jakarta.persistence.OneToMany;
import jakarta.persistence.Table; import jakarta.persistence.Table;
@@ -13,6 +15,7 @@ import java.util.Set;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import org.hibernate.annotations.Comment;
import org.hibernate.annotations.DynamicUpdate; import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@@ -27,16 +30,23 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@DynamicUpdate @DynamicUpdate
@EntityListeners(AuditingEntityListener.class) @EntityListeners(AuditingEntityListener.class)
@Table(catalog = Constants.DATABASE_NAME, name = "service_ai_knowledge") @Table(catalog = Constants.DATABASE_NAME, name = "service_ai_knowledge")
@Comment("知识库")
public class Knowledge extends SimpleEntity { public class Knowledge extends SimpleEntity {
@Comment("知识库对应的向量库名")
@Column(nullable = false) @Column(nullable = false)
private Long vectorSourceId; private Long vectorSourceId;
@Comment("知识库名称")
@Column(nullable = false) @Column(nullable = false)
private String name; private String name;
@Comment("知识库说明")
@Column(nullable = false, columnDefinition = "longtext") @Column(nullable = false, columnDefinition = "longtext")
private String description; private String description;
@Comment("知识库策略")
@Column(nullable = false) @Column(nullable = false)
@Enumerated(EnumType.STRING)
private Strategy strategy = Strategy.Cosine; private Strategy strategy = Strategy.Cosine;
@Comment("知识库下包含的分组")
@OneToMany(fetch = FetchType.LAZY, mappedBy = "knowledge", cascade = CascadeType.ALL) @OneToMany(fetch = FetchType.LAZY, mappedBy = "knowledge", cascade = CascadeType.ALL)
@ToString.Exclude @ToString.Exclude
private Set<Group> groups; private Set<Group> groups;

View File

@@ -5,6 +5,7 @@ import com.lanyuanxiaoyao.service.ai.web.entity.FlowTaskTemplate;
import com.lanyuanxiaoyao.service.ai.web.repository.FlowTaskTemplateRepository; import com.lanyuanxiaoyao.service.ai.web.repository.FlowTaskTemplateRepository;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Slf4j @Slf4j
@Service @Service
@@ -12,4 +13,11 @@ public class FlowTaskTemplateService extends SimpleServiceSupport<FlowTaskTempla
public FlowTaskTemplateService(FlowTaskTemplateRepository flowTaskTemplateRepository) { public FlowTaskTemplateService(FlowTaskTemplateRepository flowTaskTemplateRepository) {
super(flowTaskTemplateRepository); super(flowTaskTemplateRepository);
} }
@Transactional(rollbackFor = Exception.class)
public void updateFlowGraph(Long id, String flowGraph) {
FlowTaskTemplate template = detailOrThrow(id);
template.setFlowGraph(flowGraph);
save(template);
}
} }

View File

@@ -1,6 +1,6 @@
package com.lanyuanxiaoyao.service.ai.web.tools; package com.lanyuanxiaoyao.service.ai.web.tools;
import com.lanyuanxiaoyao.service.ai.web.WebApplication; import com.lanyuanxiaoyao.service.ai.web.configuration.SpringBeanGetter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient; import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.tool.annotation.Tool; import org.springframework.ai.tool.annotation.Tool;
@@ -44,7 +44,7 @@ public class ChartTool {
""") String request """) String request
) { ) {
log.info("Enter method: mermaid[request]. request:{}", request); log.info("Enter method: mermaid[request]. request:{}", request);
ChatClient.Builder builder = WebApplication.getBean("chat", ChatClient.Builder.class); ChatClient.Builder builder = SpringBeanGetter.getBean("chat", ChatClient.Builder.class);
ChatClient client = builder.build(); ChatClient client = builder.build();
return client.prompt() return client.prompt()
// language=TEXT // language=TEXT

View File

@@ -2,7 +2,7 @@ package com.lanyuanxiaoyao.service.ai.web.tools;
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.lanyuanxiaoyao.service.ai.web.WebApplication; import com.lanyuanxiaoyao.service.ai.web.configuration.SpringBeanGetter;
import com.lanyuanxiaoyao.service.forest.service.KnowledgeService; import com.lanyuanxiaoyao.service.forest.service.KnowledgeService;
import org.springframework.ai.tool.annotation.Tool; import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam; import org.springframework.ai.tool.annotation.ToolParam;
@@ -27,7 +27,7 @@ public class KnowledgeTool {
""") """)
String query String query
) { ) {
KnowledgeService knowledgeService = WebApplication.getBean(KnowledgeService.class); KnowledgeService knowledgeService = SpringBeanGetter.getBean(KnowledgeService.class);
var documents = knowledgeService.query(knowledgeId, query, 10, 0.5); var documents = knowledgeService.query(knowledgeId, query, 10, 0.5);
if (ObjectUtil.isNotEmpty(documents)) { if (ObjectUtil.isNotEmpty(documents)) {
return StrUtil.format(""" return StrUtil.format("""

View File

@@ -1,7 +1,7 @@
package com.lanyuanxiaoyao.service.ai.web.tools; package com.lanyuanxiaoyao.service.ai.web.tools;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.lanyuanxiaoyao.service.ai.web.WebApplication; import com.lanyuanxiaoyao.service.ai.web.configuration.SpringBeanGetter;
import com.lanyuanxiaoyao.service.forest.service.InfoService; import com.lanyuanxiaoyao.service.forest.service.InfoService;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
@@ -27,7 +27,7 @@ public class TableTool {
""") String sql """) String sql
) { ) {
log.info("Enter method: executeJdbc[sql]. sql:{}", sql); log.info("Enter method: executeJdbc[sql]. sql:{}", sql);
InfoService infoService = WebApplication.getBean(InfoService.class); InfoService infoService = SpringBeanGetter.getBean(InfoService.class);
String result = infoService.jdbc(sql) String result = infoService.jdbc(sql)
.collect(map -> map.valuesView().makeString(",")) .collect(map -> map.valuesView().makeString(","))
.makeString("\n"); .makeString("\n");
@@ -48,7 +48,7 @@ public class TableTool {
""") String type """) String type
) { ) {
log.info("Enter method: tableCount[type]. type:{}", type); log.info("Enter method: tableCount[type]. type:{}", type);
var infoService = WebApplication.getBean(InfoService.class); var infoService = SpringBeanGetter.getBean(InfoService.class);
return switch (type) { return switch (type) {
case "logic" -> StrUtil.format(""" case "logic" -> StrUtil.format("""
逻辑表共{}张,其中重点表{}张 逻辑表共{}张,其中重点表{}张
@@ -83,7 +83,7 @@ public class TableTool {
String type String type
) { ) {
log.info("Enter method: version[date, type]. date:{},type:{}", date, type); log.info("Enter method: version[date, type]. date:{},type:{}", date, type);
InfoService infoService = WebApplication.getBean(InfoService.class); InfoService infoService = SpringBeanGetter.getBean(InfoService.class);
String version = date; String version = date;
if (StrUtil.isBlank(version)) { if (StrUtil.isBlank(version)) {
version = LocalDateTime.now().minusDays(1).format(FORMATTER); version = LocalDateTime.now().minusDays(1).format(FORMATTER);

View File

@@ -1,7 +1,7 @@
package com.lanyuanxiaoyao.service.ai.web.tools; package com.lanyuanxiaoyao.service.ai.web.tools;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.lanyuanxiaoyao.service.ai.web.WebApplication; import com.lanyuanxiaoyao.service.ai.web.configuration.SpringBeanGetter;
import com.lanyuanxiaoyao.service.configuration.entity.yarn.YarnApplication; import com.lanyuanxiaoyao.service.configuration.entity.yarn.YarnApplication;
import com.lanyuanxiaoyao.service.configuration.entity.yarn.YarnQueue; import com.lanyuanxiaoyao.service.configuration.entity.yarn.YarnQueue;
import com.lanyuanxiaoyao.service.configuration.entity.yarn.YarnRootQueue; import com.lanyuanxiaoyao.service.configuration.entity.yarn.YarnRootQueue;
@@ -27,7 +27,7 @@ public class YarnTool {
""") String cluster """) String cluster
) { ) {
log.info("Enter method: yarnStatus[cluster]. cluster:{}", cluster); log.info("Enter method: yarnStatus[cluster]. cluster:{}", cluster);
YarnService yarnService = WebApplication.getBean(YarnService.class); YarnService yarnService = SpringBeanGetter.getBean(YarnService.class);
YarnRootQueue status = yarnService.cluster(cluster); YarnRootQueue status = yarnService.cluster(cluster);
return (status.getUsedCapacity() * 100.0) / status.getCapacity(); return (status.getUsedCapacity() * 100.0) / status.getCapacity();
} }
@@ -45,7 +45,7 @@ public class YarnTool {
""") String queue """) String queue
) { ) {
log.info("Enter method: yarnQueueStatus[cluster, queue]. cluster:{},queue:{}", cluster, queue); log.info("Enter method: yarnQueueStatus[cluster, queue]. cluster:{},queue:{}", cluster, queue);
YarnService yarnService = WebApplication.getBean(YarnService.class); YarnService yarnService = SpringBeanGetter.getBean(YarnService.class);
YarnQueue status = yarnService.queueDetail(cluster, queue); YarnQueue status = yarnService.queueDetail(cluster, queue);
return (status.getAbsoluteCapacity() * 100.0) / status.getAbsoluteMaxCapacity(); return (status.getAbsoluteCapacity() * 100.0) / status.getAbsoluteMaxCapacity();
} }
@@ -66,7 +66,7 @@ public class YarnTool {
""") String type """) String type
) { ) {
log.info("Enter method: yarnTaskStatus[cluster, type]. cluster:{},type:{}", cluster, type); log.info("Enter method: yarnTaskStatus[cluster, type]. cluster:{},type:{}", cluster, type);
YarnService yarnService = WebApplication.getBean(YarnService.class); YarnService yarnService = SpringBeanGetter.getBean(YarnService.class);
ImmutableList<YarnApplication> applications = yarnService.jobList(cluster).select(app -> StrUtil.isNotBlank(type) && StrUtil.contains(app.getName(), type)); ImmutableList<YarnApplication> applications = yarnService.jobList(cluster).select(app -> StrUtil.isNotBlank(type) && StrUtil.contains(app.getName(), type));
return StrUtil.format( return StrUtil.format(
""" """

View File

@@ -0,0 +1,51 @@
package com.lanyuanxiaoyao.service.ai.web;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ClassUtil;
import jakarta.persistence.Entity;
import java.util.EnumSet;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.dialect.MySQLDialect;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
import org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy;
/**
* JPA直接生成建表语句
*
* @author lanyuanxiaoyao
* @version 20250702
*/
public class GenerateDDL {
public static void main(String[] args) {
String root = "/Users/lanyuanxiaoyao/Project/IdeaProjects/hudi-service/service-ai/target/sql";
FileUtil.mkdir(root);
/* ClassUtil.scanPackageBySuper("org.hibernate.dialect", Dialect.class)
.stream()
.filter(clazz -> StrUtil.startWith(clazz.getSimpleName(), "MySQL"))
.filter(clazz -> !StrUtil.startWith(clazz.getSimpleName(), "Abstract"))
.filter(clazz -> !StrUtil.startWith(clazz.getSimpleName(), "Dialect"))
.forEach(dialectClazz -> generateDDL(root, dialectClazz)); */
generateDDL(root, MySQLDialect.class);
}
private static void generateDDL(String path, Class<?> dialect) {
var metadataSources = new MetadataSources(
new StandardServiceRegistryBuilder()
.applySetting("hibernate.dialect", dialect.getName())
.applySetting("hibernate.physical_naming_strategy", CamelCaseToUnderscoresNamingStrategy.class.getName())
.applySetting("hibernate.implicit_naming_strategy", SpringImplicitNamingStrategy.class.getName())
.build()
);
var classes = ClassUtil.scanPackageByAnnotation("com.lanyuanxiaoyao.service.ai.web.entity", Entity.class);
classes.forEach(metadataSources::addAnnotatedClass);
var export = new SchemaExport();
export.setFormat(true);
export.setDelimiter(";");
export.setOutputFile(path + "/" + dialect.getSimpleName() + ".sql");
export.setOverrideOutputFileContent();
export.execute(EnumSet.of(TargetType.SCRIPT), SchemaExport.Action.CREATE, metadataSources.buildMetadata());
}
}

View File

@@ -0,0 +1,80 @@
package com.lanyuanxiaoyao.service.ai.web;
import com.lanyuanxiaoyao.service.ai.web.engine.FlowExecutor;
import com.lanyuanxiaoyao.service.ai.web.engine.FlowNodeOptionalRunner;
import com.lanyuanxiaoyao.service.ai.web.engine.FlowNodeRunner;
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowEdge;
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowGraph;
import com.lanyuanxiaoyao.service.ai.web.engine.entity.FlowNode;
import com.lanyuanxiaoyao.service.ai.web.engine.store.InMemoryFlowStore;
import java.lang.reflect.InvocationTargetException;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.collections.api.factory.Maps;
import org.eclipse.collections.api.factory.Sets;
/**
* @author lanyuanxiaoyao
* @version 20250701
*/
@Slf4j
public class TestFlow {
public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
var store = new InMemoryFlowStore();
var executor = new FlowExecutor(
store,
Maps.immutable.of(
"plain-node", PlainNode.class,
"option-node", PlainOptionNode.class
)
);
/*
* 4 6 7
* 1 2 5 8---3
* \9/
*/
var graph = new FlowGraph(
"graph-1",
Sets.immutable.of(
new FlowNode("node-1", "plain-node"),
new FlowNode("node-2", "plain-node"),
new FlowNode("node-4", "plain-node"),
new FlowNode("node-6", "plain-node"),
new FlowNode("node-7", "plain-node"),
new FlowNode("node-5", "plain-node"),
new FlowNode("node-8", "option-node"),
new FlowNode("node-9", "plain-node"),
new FlowNode("node-3", "plain-node")
),
Sets.immutable.of(
new FlowEdge("edge-1", "node-1", "node-2", null, null),
new FlowEdge("edge-2", "node-2", "node-4", null, null),
new FlowEdge("edge-3", "node-2", "node-5", null, null),
new FlowEdge("edge-4", "node-5", "node-8", null, null),
new FlowEdge("edge-5", "node-8", "node-9", "yes", null),
new FlowEdge("edge-6", "node-8", "node-3", "no", null),
new FlowEdge("edge-7", "node-9", "node-3", null, null),
new FlowEdge("edge-8", "node-4", "node-6", null, null),
new FlowEdge("edge-9", "node-6", "node-7", null, null),
new FlowEdge("edge-10", "node-7", "node-3", null, null)
)
);
executor.execute(graph);
store.print();
}
public static class PlainNode extends FlowNodeRunner {
@Override
public void run() {
log.info("run node id: {}", getNodeId());
}
}
public static class PlainOptionNode extends FlowNodeOptionalRunner {
@Override
public String runOptional() {
log.info("run node id: {}", getNodeId());
// yes / no
return "no";
}
}
}

View File

@@ -1,16 +0,0 @@
package com.lanyuanxiaoyao.service.ai.web.flow;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.extern.slf4j.Slf4j;
/**
* @author lanyuanxiaoyao
* @version 20250625
*/
@Slf4j
public abstract class BaseNode extends NodeComponent {
@Override
public void process() throws Exception {
log.info(getClass().getName());
}
}

View File

@@ -1,12 +0,0 @@
package com.lanyuanxiaoyao.service.ai.web.flow;
/**
* @author lanyuanxiaoyao
* @version 20250625
*/
public class EndNode extends BaseNode {
@Override
public void process() throws Exception {
}
}

View File

@@ -1,304 +0,0 @@
package com.lanyuanxiaoyao.service.ai.web.flow;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.eclipsecollections.EclipseCollectionsModule;
import com.yomahub.liteflow.builder.LiteFlowNodeBuilder;
import com.yomahub.liteflow.core.NodeComponent;
import com.yomahub.liteflow.enums.NodeTypeEnum;
import java.util.LinkedList;
import java.util.Queue;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.collections.api.factory.Lists;
import org.eclipse.collections.api.factory.Maps;
import org.eclipse.collections.api.list.ImmutableList;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.api.map.ImmutableMap;
/**
* @author lanyuanxiaoyao
* @version 20250625
*/
@Slf4j
public class LiteFlowService {
public LiteFlowService() {
createNode("start-amis-node", NodeTypeEnum.COMMON, StartNode.class);
createNode("end-amis-node", NodeTypeEnum.COMMON, EndNode.class);
createNode("llm-amis-node", NodeTypeEnum.COMMON, LlmNode.class);
}
private static void createNode(String name, NodeTypeEnum type, Class<? extends NodeComponent> clazz) {
LiteFlowNodeBuilder.createNode()
.setId(name)
.setName(name)
.setType(type)
.setClazz(clazz)
.build();
}
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new EclipseCollectionsModule());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// language=JSON
String source = """
{
"nodes": [
{
"id": "A",
"type": "start",
"position": {
"x": 8,
"y": 272
},
"data": {},
"measured": {
"width": 256,
"height": 75
},
"selected": false,
"dragging": false
},
{
"id": "F",
"type": "end",
"position": {
"x": 1439.5556937134281,
"y": 282.2797340760818
},
"data": {},
"measured": {
"width": 256,
"height": 75
},
"selected": false,
"dragging": false
},
{
"id": "C",
"type": "normal",
"position": {
"x": 902.6781018665707,
"y": 115.31234529524048
},
"data": {},
"measured": {
"width": 256,
"height": 75
},
"selected": false,
"dragging": false
},
{
"id": "B",
"type": "normal",
"position": {
"x": 338,
"y": 287
},
"data": {},
"measured": {
"width": 256,
"height": 75
},
"selected": false,
"dragging": false
},
{
"id": "E",
"type": "normal",
"position": {
"x": 1086.6322978498904,
"y": 371.3061114283591
},
"data": {},
"measured": {
"width": 256,
"height": 75
},
"selected": true,
"dragging": false
},
{
"id": "D",
"type": "normal",
"position": {
"x": 700.0944461714178,
"y": 369.84258971430364
},
"data": {},
"measured": {
"width": 256,
"height": 75
},
"selected": false,
"dragging": false
}
],
"edges": [
{
"source": "A",
"target": "B",
"id": "xy-edge__A-B"
},
{
"source": "B",
"target": "C",
"id": "xy-edge__B-C"
},
{
"source": "C",
"target": "F",
"id": "xy-edge__C-F"
},
{
"source": "D",
"target": "E",
"id": "xy-edge__D-E"
},
{
"source": "B",
"target": "D",
"id": "xy-edge__B-D"
},
{
"source": "E",
"target": "F",
"id": "xy-edge__E-F"
}
],
"data": {
"A": {
"inputs": {
"name": {
"type": "text"
},
"description": {
"type": "text",
"description": "文件描述"
}
}
},
"C": {
"model": "qwen3",
"outputs": {
"text": {
"type": "string"
}
},
"systemPrompt": "你是个沙雕"
},
"B": {
"count": 3,
"score": 0.75,
"knowledgeId": 3585368238960640,
"query": "hello world"
},
"E": {
"type": "python",
"content": "code='hello'\\nprint(code)"
},
"D": {
"model": "qwen3",
"outputs": {
"text": {
"type": "string"
}
},
"systemPrompt": "你是个聪明人"
}
}
}
""";
FlowData root = mapper.readValue(StrUtil.trim(source), FlowData.class);
log.info("\n{}", buildEl(root.nodes, root.edges));
}
public static String buildEl(ImmutableList<FlowData.Node> nodes, ImmutableList<FlowData.Edge> edges) {
var nodeMap = nodes.toMap(FlowData.Node::getId, node -> node);
var adjacencyGraph = Maps.mutable.<String, MutableList<String>>empty();
var reverseAdjacencyGraph = Maps.mutable.<String, MutableList<String>>empty();
var inDegree = Maps.mutable.<String, Integer>empty();
nodes.forEach(node -> {
adjacencyGraph.put(node.getId(), Lists.mutable.empty());
reverseAdjacencyGraph.put(node.getId(), Lists.mutable.empty());
inDegree.put(node.getId(), 0);
});
edges.forEach(edge -> {
adjacencyGraph.get(edge.getSource()).add(edge.getTarget());
reverseAdjacencyGraph.get(edge.getTarget()).add(edge.getSource());
inDegree.put(edge.getTarget(), inDegree.get(edge.getTarget()) + 1);
});
Queue<String> queue = new LinkedList<>();
var topologicalSortedList = Lists.mutable.<String>empty();
inDegree.forEachKeyValue((id, count) -> {
if (count == 0) {
queue.offer(id);
}
});
while (!queue.isEmpty()) {
String id = queue.poll();
topologicalSortedList.add(id);
for (var neighborId : adjacencyGraph.get(id)) {
inDegree.put(neighborId, inDegree.get(neighborId) - 1);
if (inDegree.get(neighborId) == 0) {
queue.offer(neighborId);
}
}
}
topologicalSortedList.forEach(id -> log.info("{} {}", id, adjacencyGraph.get(id)));
topologicalSortedList.forEach(id -> log.info("{} {}", id, reverseAdjacencyGraph.get(id)));
var nodeQueue = new LinkedList<>(topologicalSortedList);
var chains = Lists.mutable.<MutableList<String>>empty();
while (!nodeQueue.isEmpty()) {
String currentId = nodeQueue.poll();
var subChain = Lists.mutable.<String>empty();
while (true) {
subChain.add(currentId);
nodeQueue.remove(currentId);
if (adjacencyGraph.get(currentId).size() != 1) {
break;
}
String nextId = adjacencyGraph.get(currentId).get(0);
if (reverseAdjacencyGraph.get(nextId).size() > 1) {
break;
}
currentId = nextId;
}
chains.add(subChain);
}
log.info("{}", chains);
return StrUtil.join(",", topologicalSortedList);
}
@Data
public static class FlowData {
private ImmutableList<Node> nodes;
private ImmutableList<Edge> edges;
private ImmutableMap<String, Object> data;
@Data
public static class Node {
private String id;
private String type;
}
@Data
public static class Edge {
private String id;
private String source;
private String target;
}
}
}

View File

@@ -1,12 +0,0 @@
package com.lanyuanxiaoyao.service.ai.web.flow;
/**
* @author lanyuanxiaoyao
* @version 20250625
*/
public class LlmNode extends BaseNode {
@Override
public void process() throws Exception {
}
}

View File

@@ -1,12 +0,0 @@
package com.lanyuanxiaoyao.service.ai.web.flow;
/**
* @author lanyuanxiaoyao
* @version 20250625
*/
public class StartNode extends BaseNode {
@Override
public void process() throws Exception {
}
}

View File

@@ -2,11 +2,15 @@ package com.lanyuanxiaoyao.service.configuration;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/** /**
* Spring Security Config * Spring Security Config
@@ -25,6 +29,19 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
this.securityProperties = securityProperties; this.securityProperties = securityProperties;
} }
@Bean
public CorsFilter corsFilter() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowCredentials(true);
configuration.addAllowedOriginPattern("*");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
configuration.setMaxAge(7200L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return new CorsFilter(source);
}
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http.authorizeHttpRequests() http.authorizeHttpRequests()
@@ -36,7 +53,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.csrf() .csrf()
.disable() .disable()
.cors() .cors()
.disable() .and()
.formLogin() .formLogin()
.disable(); .disable();
} }

View File

@@ -10,7 +10,7 @@ import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.server.SecurityWebFilterChain; import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource; import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
/** /**
@@ -33,24 +33,12 @@ public class SecurityConfiguration {
.httpBasic() .httpBasic()
.disable() .disable()
.cors() .cors()
.configurationSource(corsConfigurationSource()) .disable()
.and()
.csrf() .csrf()
.disable() .disable()
.build(); .build();
} }
private CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowCredentials(true);
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
configuration.addAllowedOriginPattern("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean @Bean
public MapReactiveUserDetailsService userDetailsService(SecurityProperties securityProperties) { public MapReactiveUserDetailsService userDetailsService(SecurityProperties securityProperties) {
UserDetails user = User.builder() UserDetails user = User.builder()

View File

@@ -6,7 +6,8 @@
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "tsc -b && vite build", "build": "tsc -b && vite build",
"preview": "vite preview" "preview": "vite preview",
"test": "vitest run"
}, },
"dependencies": { "dependencies": {
"@ant-design/icons": "^6.0.0", "@ant-design/icons": "^6.0.0",
@@ -41,6 +42,7 @@
"sass": "^1.89.2", "sass": "^1.89.2",
"typescript": "~5.8.3", "typescript": "~5.8.3",
"vite": "^7.0.0", "vite": "^7.0.0",
"vite-plugin-javascript-obfuscator": "^3.1.0" "vite-plugin-javascript-obfuscator": "^3.1.0",
"vitest": "^3.2.4"
} }
} }

View File

@@ -102,6 +102,9 @@ importers:
vite-plugin-javascript-obfuscator: vite-plugin-javascript-obfuscator:
specifier: ^3.1.0 specifier: ^3.1.0
version: 3.1.0 version: 3.1.0
vitest:
specifier: ^3.2.4
version: 3.2.4(@types/debug@4.1.12)(sass@1.89.2)
packages: packages:
@@ -499,6 +502,9 @@ packages:
resolution: {integrity: sha512-CZFX7UZVN9VopGbjTx4UXaXsi9ewoM1buL0kY7j1ftYdSs7p2spv9opxFjHlQ/QGTgh4UqufYqJJ0WKLml7b6w==} resolution: {integrity: sha512-CZFX7UZVN9VopGbjTx4UXaXsi9ewoM1buL0kY7j1ftYdSs7p2spv9opxFjHlQ/QGTgh4UqufYqJJ0WKLml7b6w==}
engines: {node: '>=4.0'} engines: {node: '>=4.0'}
'@jridgewell/sourcemap-codec@1.5.0':
resolution: {integrity: sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==}
'@kurkle/color@0.3.4': '@kurkle/color@0.3.4':
resolution: {integrity: sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==} resolution: {integrity: sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==}
@@ -865,6 +871,9 @@ packages:
'@swc/types@0.1.23': '@swc/types@0.1.23':
resolution: {integrity: sha512-u1iIVZV9Q0jxY+yM2vw/hZGDNudsN85bBpTqzAQ9rzkxW9D+e3aEM4Han+ow518gSewkXgjmEK0BD79ZcNVgPw==} resolution: {integrity: sha512-u1iIVZV9Q0jxY+yM2vw/hZGDNudsN85bBpTqzAQ9rzkxW9D+e3aEM4Han+ow518gSewkXgjmEK0BD79ZcNVgPw==}
'@types/chai@5.2.2':
resolution: {integrity: sha512-8kB30R7Hwqf40JPiKhVzodJs2Qc1ZJ5zuT3uzw5Hq/dhNCl3G3l83jfpdI1e20BP348+fV7VIL/+FxaXkqBmWg==}
'@types/d3-array@3.2.1': '@types/d3-array@3.2.1':
resolution: {integrity: sha512-Y2Jn2idRrLzUfAKV2LyRImR+y4oa2AntrgID95SHJxuMUrkNXmanDSed71sRNZysveJVt1hLLemQZIady0FpEg==} resolution: {integrity: sha512-Y2Jn2idRrLzUfAKV2LyRImR+y4oa2AntrgID95SHJxuMUrkNXmanDSed71sRNZysveJVt1hLLemQZIady0FpEg==}
@@ -961,6 +970,9 @@ packages:
'@types/debug@4.1.12': '@types/debug@4.1.12':
resolution: {integrity: sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==} resolution: {integrity: sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==}
'@types/deep-eql@4.0.2':
resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
'@types/estree-jsx@1.0.5': '@types/estree-jsx@1.0.5':
resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==} resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==}
@@ -1033,6 +1045,35 @@ packages:
peerDependencies: peerDependencies:
vite: ^4 || ^5 || ^6 || ^7.0.0-beta.0 vite: ^4 || ^5 || ^6 || ^7.0.0-beta.0
'@vitest/expect@3.2.4':
resolution: {integrity: sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==}
'@vitest/mocker@3.2.4':
resolution: {integrity: sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ==}
peerDependencies:
msw: ^2.4.9
vite: ^5.0.0 || ^6.0.0 || ^7.0.0-0
peerDependenciesMeta:
msw:
optional: true
vite:
optional: true
'@vitest/pretty-format@3.2.4':
resolution: {integrity: sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA==}
'@vitest/runner@3.2.4':
resolution: {integrity: sha512-oukfKT9Mk41LreEW09vt45f8wx7DordoWUZMYdY/cyAk7w5TWkTRCNZYF7sX7n2wB7jyGAl74OxgwhPgKaqDMQ==}
'@vitest/snapshot@3.2.4':
resolution: {integrity: sha512-dEYtS7qQP2CjU27QBC5oUOxLE/v5eLkGqPE0ZKEIDGMs4vKWe7IjgLOeauHsR0D5YuuycGRO5oSRXnwnmA78fQ==}
'@vitest/spy@3.2.4':
resolution: {integrity: sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw==}
'@vitest/utils@3.2.4':
resolution: {integrity: sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA==}
'@xyflow/react@12.7.1': '@xyflow/react@12.7.1':
resolution: {integrity: sha512-uvIPQIZdf8tt0mDWvhkEpg/7t5E/e/KE4RWjNczAEhEYA+uvLc+4A5kIPJqCjJJbVHfMiAojT5JOB5mB7/EgFw==} resolution: {integrity: sha512-uvIPQIZdf8tt0mDWvhkEpg/7t5E/e/KE4RWjNczAEhEYA+uvLc+4A5kIPJqCjJJbVHfMiAojT5JOB5mB7/EgFw==}
peerDependencies: peerDependencies:
@@ -1162,6 +1203,10 @@ packages:
assert@2.0.0: assert@2.0.0:
resolution: {integrity: sha512-se5Cd+js9dXJnu6Ag2JFc00t+HmHOen+8Q+L7O9zI0PqQXr20uk2J0XQqMxZEeo5U50o8Nvmmx7dZrl+Ufr35A==} resolution: {integrity: sha512-se5Cd+js9dXJnu6Ag2JFc00t+HmHOen+8Q+L7O9zI0PqQXr20uk2J0XQqMxZEeo5U50o8Nvmmx7dZrl+Ufr35A==}
assertion-error@2.0.1:
resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
engines: {node: '>=12'}
async@3.2.6: async@3.2.6:
resolution: {integrity: sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==} resolution: {integrity: sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==}
@@ -1234,6 +1279,10 @@ packages:
resolution: {integrity: sha512-9q/rDEGSb/Qsvv2qvzIzdluL5k7AaJOTrw23z9reQthrbF7is4CtlT0DXyO1oei2DCp4uojjzQ7igaSHp1kAEQ==} resolution: {integrity: sha512-9q/rDEGSb/Qsvv2qvzIzdluL5k7AaJOTrw23z9reQthrbF7is4CtlT0DXyO1oei2DCp4uojjzQ7igaSHp1kAEQ==}
engines: {node: '>=0.2.0'} engines: {node: '>=0.2.0'}
cac@6.7.14:
resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==}
engines: {node: '>=8'}
call-bind-apply-helpers@1.0.2: call-bind-apply-helpers@1.0.2:
resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==}
engines: {node: '>= 0.4'} engines: {node: '>= 0.4'}
@@ -1260,6 +1309,10 @@ packages:
resolution: {integrity: sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==} resolution: {integrity: sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==}
engines: {node: '>=0.8'} engines: {node: '>=0.8'}
chai@5.2.0:
resolution: {integrity: sha512-mCuXncKXk5iCLhfhwTc0izo0gtEmpz5CtG2y8GiOINBlMVS6v8TMRc5TaLWKS6692m9+dVVfzgeVxR5UxWHTYw==}
engines: {node: '>=12'}
chainsaw@0.1.0: chainsaw@0.1.0:
resolution: {integrity: sha512-75kWfWt6MEKNC8xYXIdRpDehRYY/tNSgwKaJq+dbbDcxORuVrrQ+SEHoWsniVn9XPYfP4gmdWIeDk/4YNp1rNQ==} resolution: {integrity: sha512-75kWfWt6MEKNC8xYXIdRpDehRYY/tNSgwKaJq+dbbDcxORuVrrQ+SEHoWsniVn9XPYfP4gmdWIeDk/4YNp1rNQ==}
@@ -1293,6 +1346,10 @@ packages:
resolution: {integrity: sha512-aYeC/jDgSEx8SHWZvANYMioYMZ2KX02W6f6uVfyteuCGcadDLcYVHdfdygsTQkQ4TKn5lghoojAsPj5pu0SnvQ==} resolution: {integrity: sha512-aYeC/jDgSEx8SHWZvANYMioYMZ2KX02W6f6uVfyteuCGcadDLcYVHdfdygsTQkQ4TKn5lghoojAsPj5pu0SnvQ==}
engines: {pnpm: '>=8'} engines: {pnpm: '>=8'}
check-error@2.1.1:
resolution: {integrity: sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw==}
engines: {node: '>= 16'}
chevrotain-allstar@0.3.1: chevrotain-allstar@0.3.1:
resolution: {integrity: sha512-b7g+y9A0v4mxCW1qUhf3BSVPg+/NvGErk/dOkrDaHA0nQIQGAtrOjlX//9OQtRlSCy+x9rfB5N8yC71lH1nvMw==} resolution: {integrity: sha512-b7g+y9A0v4mxCW1qUhf3BSVPg+/NvGErk/dOkrDaHA0nQIQGAtrOjlX//9OQtRlSCy+x9rfB5N8yC71lH1nvMw==}
peerDependencies: peerDependencies:
@@ -1616,6 +1673,10 @@ packages:
resolution: {integrity: sha512-jOSne2qbyE+/r8G1VU+G/82LBs2Fs4LAsTiLSHOCOMZQl2OKZ6i8i4IyHemTe+/yIXOtTcRQMzPcgyhoFlqPkw==} resolution: {integrity: sha512-jOSne2qbyE+/r8G1VU+G/82LBs2Fs4LAsTiLSHOCOMZQl2OKZ6i8i4IyHemTe+/yIXOtTcRQMzPcgyhoFlqPkw==}
engines: {node: '>=8'} engines: {node: '>=8'}
deep-eql@5.0.2:
resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==}
engines: {node: '>=6'}
deep-is@0.1.4: deep-is@0.1.4:
resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==}
@@ -1705,6 +1766,9 @@ packages:
resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}
engines: {node: '>= 0.4'} engines: {node: '>= 0.4'}
es-module-lexer@1.7.0:
resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==}
es-object-atoms@1.1.1: es-object-atoms@1.1.1:
resolution: {integrity: sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==} resolution: {integrity: sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==}
engines: {node: '>= 0.4'} engines: {node: '>= 0.4'}
@@ -1748,6 +1812,9 @@ packages:
estree-util-is-identifier-name@3.0.0: estree-util-is-identifier-name@3.0.0:
resolution: {integrity: sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==} resolution: {integrity: sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==}
estree-walker@3.0.3:
resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}
esutils@2.0.3: esutils@2.0.3:
resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==}
engines: {node: '>=0.10.0'} engines: {node: '>=0.10.0'}
@@ -1756,6 +1823,10 @@ packages:
resolution: {integrity: sha512-XctvKaEMaj1Ii9oDOqbW/6e1gXknSY4g/aLCDicOXqBE4M0nRWkUu0PTp++UPNzoFY12BNHMfs/VadKIS6llvg==} resolution: {integrity: sha512-XctvKaEMaj1Ii9oDOqbW/6e1gXknSY4g/aLCDicOXqBE4M0nRWkUu0PTp++UPNzoFY12BNHMfs/VadKIS6llvg==}
engines: {node: '>=8.3.0'} engines: {node: '>=8.3.0'}
expect-type@1.2.1:
resolution: {integrity: sha512-/kP8CAwxzLVEeFrMm4kMmy4CCDlpipyA7MYLVrdJIkV0fYF0UaigQHRsxHiuY/GEea+bh4KSv3TIlgr+2UL6bw==}
engines: {node: '>=12.0.0'}
exsolve@1.0.5: exsolve@1.0.5:
resolution: {integrity: sha512-pz5dvkYYKQ1AHVrgOzBKWeP4u4FRb3a6DNK2ucr0OoNwYIU4QWsJ+NM36LLzORT+z845MzKHHhpXiUF5nvQoJg==} resolution: {integrity: sha512-pz5dvkYYKQ1AHVrgOzBKWeP4u4FRb3a6DNK2ucr0OoNwYIU4QWsJ+NM36LLzORT+z845MzKHHhpXiUF5nvQoJg==}
@@ -2058,6 +2129,9 @@ packages:
js-tokens@4.0.0: js-tokens@4.0.0:
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
js-tokens@9.0.1:
resolution: {integrity: sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==}
jsbarcode@3.12.1: jsbarcode@3.12.1:
resolution: {integrity: sha512-QZQSqIknC2Rr/YOUyOkCBqsoiBAOTYK+7yNN3JsqfoUtJtkazxNw1dmPpxuv7VVvqW13kA3/mKiLq+s/e3o9hQ==} resolution: {integrity: sha512-QZQSqIknC2Rr/YOUyOkCBqsoiBAOTYK+7yNN3JsqfoUtJtkazxNw1dmPpxuv7VVvqW13kA3/mKiLq+s/e3o9hQ==}
@@ -2179,6 +2253,12 @@ packages:
resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==} resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}
hasBin: true hasBin: true
loupe@3.1.4:
resolution: {integrity: sha512-wJzkKwJrheKtknCOKNEtDK4iqg/MxmZheEMtSTYvnzRdEYaZzmgH976nenp8WdJRdx5Vc1X/9MO0Oszl6ezeXg==}
magic-string@0.30.17:
resolution: {integrity: sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA==}
make-cancellable-promise@1.3.2: make-cancellable-promise@1.3.2:
resolution: {integrity: sha512-GCXh3bq/WuMbS+Ky4JBPW1hYTOU+znU+Q5m9Pu+pI8EoUqIHk9+tviOKC6/qhHh8C4/As3tzJ69IF32kdz85ww==} resolution: {integrity: sha512-GCXh3bq/WuMbS+Ky4JBPW1hYTOU+znU+Q5m9Pu+pI8EoUqIHk9+tviOKC6/qhHh8C4/As3tzJ69IF32kdz85ww==}
@@ -2518,6 +2598,10 @@ packages:
pathe@2.0.3: pathe@2.0.3:
resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
pathval@2.0.1:
resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==}
engines: {node: '>= 14.16'}
pdfjs-dist@4.3.136: pdfjs-dist@4.3.136:
resolution: {integrity: sha512-gzfnt1qc4yA+U46golPGYtU4WM2ssqP2MvFjKga8GEKOrEnzRPrA/9jogLLPYHiA3sGBPJ+p7BdAq+ytmw3jEg==} resolution: {integrity: sha512-gzfnt1qc4yA+U46golPGYtU4WM2ssqP2MvFjKga8GEKOrEnzRPrA/9jogLLPYHiA3sGBPJ+p7BdAq+ytmw3jEg==}
engines: {node: '>=18'} engines: {node: '>=18'}
@@ -3105,6 +3189,9 @@ packages:
resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==}
engines: {node: '>=8'} engines: {node: '>=8'}
siginfo@2.0.0:
resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
signal-exit@3.0.7: signal-exit@3.0.7:
resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==}
@@ -3141,6 +3228,12 @@ packages:
resolution: {integrity: sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==} resolution: {integrity: sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==}
engines: {node: '>=0.8'} engines: {node: '>=0.8'}
stackback@0.0.2:
resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
std-env@3.9.0:
resolution: {integrity: sha512-UGvjygr6F6tpH7o2qyqR6QYpwraIjKSdtzyBdyytFOHmPZY917kwdwLG0RbOjWOnKmnm3PeHjaoLLMie7kPLQw==}
string-convert@0.2.1: string-convert@0.2.1:
resolution: {integrity: sha512-u/1tdPl4yQnPBjnVrmdLo9gtuLvELKsAoRapekWggdiQNvvvum+jYF329d84NAa660KQw7pB2n36KrIKVoXa3A==} resolution: {integrity: sha512-u/1tdPl4yQnPBjnVrmdLo9gtuLvELKsAoRapekWggdiQNvvvum+jYF329d84NAa660KQw7pB2n36KrIKVoXa3A==}
@@ -3167,6 +3260,9 @@ packages:
resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}
engines: {node: '>=8'} engines: {node: '>=8'}
strip-literal@3.0.0:
resolution: {integrity: sha512-TcccoMhJOM3OebGhSBEmp3UZ2SfDMZUEBdRA/9ynfLi8yYajyWX3JiXArcJt4Umh4vISpspkQIY8ZZoCqjbviA==}
style-to-js@1.1.17: style-to-js@1.1.17:
resolution: {integrity: sha512-xQcBGDxJb6jjFCTzvQtfiPn6YvvP2O8U1MDIPNfJQlWMYfktPy+iGsHE7cssjs7y84d9fQaK4UF3RIJaAHSoYA==} resolution: {integrity: sha512-xQcBGDxJb6jjFCTzvQtfiPn6YvvP2O8U1MDIPNfJQlWMYfktPy+iGsHE7cssjs7y84d9fQaK4UF3RIJaAHSoYA==}
@@ -3210,9 +3306,15 @@ packages:
tiny-invariant@1.3.3: tiny-invariant@1.3.3:
resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==} resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==}
tinybench@2.9.0:
resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
tinycolor2@1.6.0: tinycolor2@1.6.0:
resolution: {integrity: sha512-XPaBkWQJdsf3pLKJV9p4qN/S+fm2Oj8AIPo1BTUhg5oxkvm9+SVEGFdhyOz7tTdUTfvxMiAs4sp6/eZO2Ew+pw==} resolution: {integrity: sha512-XPaBkWQJdsf3pLKJV9p4qN/S+fm2Oj8AIPo1BTUhg5oxkvm9+SVEGFdhyOz7tTdUTfvxMiAs4sp6/eZO2Ew+pw==}
tinyexec@0.3.2:
resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==}
tinyexec@1.0.1: tinyexec@1.0.1:
resolution: {integrity: sha512-5uC6DDlmeqiOwCPmK9jMSdOuZTh8bU39Ys6yidB+UTt5hfZUPGAypSgFRiEp+jbi9qH40BLDvy85jIU88wKSqw==} resolution: {integrity: sha512-5uC6DDlmeqiOwCPmK9jMSdOuZTh8bU39Ys6yidB+UTt5hfZUPGAypSgFRiEp+jbi9qH40BLDvy85jIU88wKSqw==}
@@ -3223,6 +3325,18 @@ packages:
tinymce@6.8.6: tinymce@6.8.6:
resolution: {integrity: sha512-++XYEs8lKWvZxDCjrr8Baiw7KiikraZ5JkLMg6EdnUVNKJui0IsrAADj5MsyUeFkcEryfn2jd3p09H7REvewyg==} resolution: {integrity: sha512-++XYEs8lKWvZxDCjrr8Baiw7KiikraZ5JkLMg6EdnUVNKJui0IsrAADj5MsyUeFkcEryfn2jd3p09H7REvewyg==}
tinypool@1.1.1:
resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==}
engines: {node: ^18.0.0 || >=20.0.0}
tinyrainbow@2.0.0:
resolution: {integrity: sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==}
engines: {node: '>=14.0.0'}
tinyspy@4.0.3:
resolution: {integrity: sha512-t2T/WLB2WRgZ9EpE4jgPJ9w+i66UZfDc8wHh0xrwiRNN+UwH98GIJkTeZqX9rg0i0ptwzqW+uYeIF0T4F8LR7A==}
engines: {node: '>=14.0.0'}
tmp@0.2.3: tmp@0.2.3:
resolution: {integrity: sha512-nZD7m9iCPC5g0pYmcaxogYKggSfLsdxl8of3Q/oIbqCqLLIO9IAF0GWjX1z9NZRHPiXv8Wex4yDCaZsgEw0Y8w==} resolution: {integrity: sha512-nZD7m9iCPC5g0pYmcaxogYKggSfLsdxl8of3Q/oIbqCqLLIO9IAF0GWjX1z9NZRHPiXv8Wex4yDCaZsgEw0Y8w==}
engines: {node: '>=14.14'} engines: {node: '>=14.14'}
@@ -3369,6 +3483,11 @@ packages:
react: ^15.0.0 || ^16.0.0 || ^17.0.0 react: ^15.0.0 || ^16.0.0 || ^17.0.0
react-dom: ^15.0.0 || ^16.0.0 || ^17.0.0 react-dom: ^15.0.0 || ^16.0.0 || ^17.0.0
vite-node@3.2.4:
resolution: {integrity: sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==}
engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}
hasBin: true
vite-plugin-javascript-obfuscator@3.1.0: vite-plugin-javascript-obfuscator@3.1.0:
resolution: {integrity: sha512-sf4JFlG1iUPl7bLXHGOy+bKWOQUFyXzJFWa+n2S2xMMvyfM+V9R40HhpZoIF1eAjifArM1SF7fbSFIaTuUIbPA==} resolution: {integrity: sha512-sf4JFlG1iUPl7bLXHGOy+bKWOQUFyXzJFWa+n2S2xMMvyfM+V9R40HhpZoIF1eAjifArM1SF7fbSFIaTuUIbPA==}
@@ -3412,6 +3531,34 @@ packages:
yaml: yaml:
optional: true optional: true
vitest@3.2.4:
resolution: {integrity: sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==}
engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}
hasBin: true
peerDependencies:
'@edge-runtime/vm': '*'
'@types/debug': ^4.1.12
'@types/node': ^18.0.0 || ^20.0.0 || >=22.0.0
'@vitest/browser': 3.2.4
'@vitest/ui': 3.2.4
happy-dom: '*'
jsdom: '*'
peerDependenciesMeta:
'@edge-runtime/vm':
optional: true
'@types/debug':
optional: true
'@types/node':
optional: true
'@vitest/browser':
optional: true
'@vitest/ui':
optional: true
happy-dom:
optional: true
jsdom:
optional: true
vscode-jsonrpc@8.2.0: vscode-jsonrpc@8.2.0:
resolution: {integrity: sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==} resolution: {integrity: sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==}
engines: {node: '>=14.0.0'} engines: {node: '>=14.0.0'}
@@ -3454,6 +3601,11 @@ packages:
engines: {node: '>= 8'} engines: {node: '>= 8'}
hasBin: true hasBin: true
why-is-node-running@2.3.0:
resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}
engines: {node: '>=8'}
hasBin: true
wide-align@1.1.5: wide-align@1.1.5:
resolution: {integrity: sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==} resolution: {integrity: sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==}
@@ -4007,6 +4159,8 @@ snapshots:
'@javascript-obfuscator/estraverse@5.4.0': {} '@javascript-obfuscator/estraverse@5.4.0': {}
'@jridgewell/sourcemap-codec@1.5.0': {}
'@kurkle/color@0.3.4': {} '@kurkle/color@0.3.4': {}
'@lightenna/react-mermaid-diagram@1.0.20(mermaid@11.7.0)(react@18.3.1)': '@lightenna/react-mermaid-diagram@1.0.20(mermaid@11.7.0)(react@18.3.1)':
@@ -4291,6 +4445,10 @@ snapshots:
dependencies: dependencies:
'@swc/counter': 0.1.3 '@swc/counter': 0.1.3
'@types/chai@5.2.2':
dependencies:
'@types/deep-eql': 4.0.2
'@types/d3-array@3.2.1': {} '@types/d3-array@3.2.1': {}
'@types/d3-axis@3.0.6': '@types/d3-axis@3.0.6':
@@ -4412,6 +4570,8 @@ snapshots:
dependencies: dependencies:
'@types/ms': 2.1.0 '@types/ms': 2.1.0
'@types/deep-eql@4.0.2': {}
'@types/estree-jsx@1.0.5': '@types/estree-jsx@1.0.5':
dependencies: dependencies:
'@types/estree': 1.0.8 '@types/estree': 1.0.8
@@ -4476,6 +4636,48 @@ snapshots:
transitivePeerDependencies: transitivePeerDependencies:
- '@swc/helpers' - '@swc/helpers'
'@vitest/expect@3.2.4':
dependencies:
'@types/chai': 5.2.2
'@vitest/spy': 3.2.4
'@vitest/utils': 3.2.4
chai: 5.2.0
tinyrainbow: 2.0.0
'@vitest/mocker@3.2.4(vite@7.0.0(sass@1.89.2))':
dependencies:
'@vitest/spy': 3.2.4
estree-walker: 3.0.3
magic-string: 0.30.17
optionalDependencies:
vite: 7.0.0(sass@1.89.2)
'@vitest/pretty-format@3.2.4':
dependencies:
tinyrainbow: 2.0.0
'@vitest/runner@3.2.4':
dependencies:
'@vitest/utils': 3.2.4
pathe: 2.0.3
strip-literal: 3.0.0
'@vitest/snapshot@3.2.4':
dependencies:
'@vitest/pretty-format': 3.2.4
magic-string: 0.30.17
pathe: 2.0.3
'@vitest/spy@3.2.4':
dependencies:
tinyspy: 4.0.3
'@vitest/utils@3.2.4':
dependencies:
'@vitest/pretty-format': 3.2.4
loupe: 3.1.4
tinyrainbow: 2.0.0
'@xyflow/react@12.7.1(@types/react@18.3.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': '@xyflow/react@12.7.1(@types/react@18.3.23)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)':
dependencies: dependencies:
'@xyflow/system': 0.0.63 '@xyflow/system': 0.0.63
@@ -4800,6 +5002,8 @@ snapshots:
object-is: 1.1.6 object-is: 1.1.6
util: 0.12.5 util: 0.12.5
assertion-error@2.0.1: {}
async@3.2.6: {} async@3.2.6: {}
asynckit@0.4.0: {} asynckit@0.4.0: {}
@@ -4870,6 +5074,8 @@ snapshots:
buffers@0.1.1: {} buffers@0.1.1: {}
cac@6.7.14: {}
call-bind-apply-helpers@1.0.2: call-bind-apply-helpers@1.0.2:
dependencies: dependencies:
es-errors: 1.3.0 es-errors: 1.3.0
@@ -4906,6 +5112,14 @@ snapshots:
adler-32: 1.3.1 adler-32: 1.3.1
crc-32: 1.2.2 crc-32: 1.2.2
chai@5.2.0:
dependencies:
assertion-error: 2.0.1
check-error: 2.1.1
deep-eql: 5.0.2
loupe: 3.1.4
pathval: 2.0.1
chainsaw@0.1.0: chainsaw@0.1.0:
dependencies: dependencies:
traverse: 0.3.9 traverse: 0.3.9
@@ -4933,6 +5147,8 @@ snapshots:
dependencies: dependencies:
'@kurkle/color': 0.3.4 '@kurkle/color': 0.3.4
check-error@2.1.1: {}
chevrotain-allstar@0.3.1(chevrotain@11.0.3): chevrotain-allstar@0.3.1(chevrotain@11.0.3):
dependencies: dependencies:
chevrotain: 11.0.3 chevrotain: 11.0.3
@@ -5267,6 +5483,8 @@ snapshots:
mimic-response: 2.1.0 mimic-response: 2.1.0
optional: true optional: true
deep-eql@5.0.2: {}
deep-is@0.1.4: {} deep-is@0.1.4: {}
define-data-property@1.1.4: define-data-property@1.1.4:
@@ -5361,6 +5579,8 @@ snapshots:
es-errors@1.3.0: {} es-errors@1.3.0: {}
es-module-lexer@1.7.0: {}
es-object-atoms@1.1.1: es-object-atoms@1.1.1:
dependencies: dependencies:
es-errors: 1.3.0 es-errors: 1.3.0
@@ -5421,6 +5641,10 @@ snapshots:
estree-util-is-identifier-name@3.0.0: {} estree-util-is-identifier-name@3.0.0: {}
estree-walker@3.0.3:
dependencies:
'@types/estree': 1.0.8
esutils@2.0.3: {} esutils@2.0.3: {}
exceljs@4.4.0: exceljs@4.4.0:
@@ -5435,6 +5659,8 @@ snapshots:
unzipper: 0.10.14 unzipper: 0.10.14
uuid: 8.3.2 uuid: 8.3.2
expect-type@1.2.1: {}
exsolve@1.0.5: {} exsolve@1.0.5: {}
extend@3.0.2: {} extend@3.0.2: {}
@@ -5771,6 +5997,8 @@ snapshots:
js-tokens@4.0.0: {} js-tokens@4.0.0: {}
js-tokens@9.0.1: {}
jsbarcode@3.12.1: {} jsbarcode@3.12.1: {}
json2mq@0.2.0: json2mq@0.2.0:
@@ -5877,6 +6105,12 @@ snapshots:
dependencies: dependencies:
js-tokens: 4.0.0 js-tokens: 4.0.0
loupe@3.1.4: {}
magic-string@0.30.17:
dependencies:
'@jridgewell/sourcemap-codec': 1.5.0
make-cancellable-promise@1.3.2: {} make-cancellable-promise@1.3.2: {}
make-dir@3.1.0: make-dir@3.1.0:
@@ -6359,6 +6593,8 @@ snapshots:
pathe@2.0.3: {} pathe@2.0.3: {}
pathval@2.0.1: {}
pdfjs-dist@4.3.136: pdfjs-dist@4.3.136:
optionalDependencies: optionalDependencies:
canvas: 2.11.2 canvas: 2.11.2
@@ -7130,6 +7366,8 @@ snapshots:
shebang-regex@3.0.0: {} shebang-regex@3.0.0: {}
siginfo@2.0.0: {}
signal-exit@3.0.7: signal-exit@3.0.7:
optional: true optional: true
@@ -7164,6 +7402,10 @@ snapshots:
dependencies: dependencies:
frac: 1.1.2 frac: 1.1.2
stackback@0.0.2: {}
std-env@3.9.0: {}
string-convert@0.2.1: {} string-convert@0.2.1: {}
string-template@1.0.0: {} string-template@1.0.0: {}
@@ -7197,6 +7439,10 @@ snapshots:
ansi-regex: 5.0.1 ansi-regex: 5.0.1
optional: true optional: true
strip-literal@3.0.0:
dependencies:
js-tokens: 9.0.1
style-to-js@1.1.17: style-to-js@1.1.17:
dependencies: dependencies:
style-to-object: 1.0.9 style-to-object: 1.0.9
@@ -7255,8 +7501,12 @@ snapshots:
tiny-invariant@1.3.3: {} tiny-invariant@1.3.3: {}
tinybench@2.9.0: {}
tinycolor2@1.6.0: {} tinycolor2@1.6.0: {}
tinyexec@0.3.2: {}
tinyexec@1.0.1: {} tinyexec@1.0.1: {}
tinyglobby@0.2.14: tinyglobby@0.2.14:
@@ -7266,6 +7516,12 @@ snapshots:
tinymce@6.8.6: {} tinymce@6.8.6: {}
tinypool@1.1.1: {}
tinyrainbow@2.0.0: {}
tinyspy@4.0.3: {}
tmp@0.2.3: {} tmp@0.2.3: {}
to-regex-range@5.0.1: to-regex-range@5.0.1:
@@ -7418,6 +7674,27 @@ snapshots:
react-dom: 18.3.1(react@18.3.1) react-dom: 18.3.1(react@18.3.1)
redux: 4.2.1 redux: 4.2.1
vite-node@3.2.4(sass@1.89.2):
dependencies:
cac: 6.7.14
debug: 4.4.1
es-module-lexer: 1.7.0
pathe: 2.0.3
vite: 7.0.0(sass@1.89.2)
transitivePeerDependencies:
- '@types/node'
- jiti
- less
- lightningcss
- sass
- sass-embedded
- stylus
- sugarss
- supports-color
- terser
- tsx
- yaml
vite-plugin-javascript-obfuscator@3.1.0: vite-plugin-javascript-obfuscator@3.1.0:
dependencies: dependencies:
anymatch: 3.1.3 anymatch: 3.1.3
@@ -7435,6 +7712,47 @@ snapshots:
fsevents: 2.3.3 fsevents: 2.3.3
sass: 1.89.2 sass: 1.89.2
vitest@3.2.4(@types/debug@4.1.12)(sass@1.89.2):
dependencies:
'@types/chai': 5.2.2
'@vitest/expect': 3.2.4
'@vitest/mocker': 3.2.4(vite@7.0.0(sass@1.89.2))
'@vitest/pretty-format': 3.2.4
'@vitest/runner': 3.2.4
'@vitest/snapshot': 3.2.4
'@vitest/spy': 3.2.4
'@vitest/utils': 3.2.4
chai: 5.2.0
debug: 4.4.1
expect-type: 1.2.1
magic-string: 0.30.17
pathe: 2.0.3
picomatch: 4.0.2
std-env: 3.9.0
tinybench: 2.9.0
tinyexec: 0.3.2
tinyglobby: 0.2.14
tinypool: 1.1.1
tinyrainbow: 2.0.0
vite: 7.0.0(sass@1.89.2)
vite-node: 3.2.4(sass@1.89.2)
why-is-node-running: 2.3.0
optionalDependencies:
'@types/debug': 4.1.12
transitivePeerDependencies:
- jiti
- less
- lightningcss
- msw
- sass
- sass-embedded
- stylus
- sugarss
- supports-color
- terser
- tsx
- yaml
vscode-jsonrpc@8.2.0: {} vscode-jsonrpc@8.2.0: {}
vscode-languageserver-protocol@3.17.5: vscode-languageserver-protocol@3.17.5:
@@ -7479,6 +7797,11 @@ snapshots:
dependencies: dependencies:
isexe: 2.0.0 isexe: 2.0.0
why-is-node-running@2.3.0:
dependencies:
siginfo: 2.0.0
stackback: 0.0.2
wide-align@1.1.5: wide-align@1.1.5:
dependencies: dependencies:
string-width: 4.2.3 string-width: 4.2.3

View File

@@ -0,0 +1,62 @@
import {type Connection, type Node} from '@xyflow/react'
import {expect, test} from 'vitest'
import {
checkAddConnection,
hasCycleError,
nodeToSelfError,
sourceNodeNotFoundError,
targetNodeNotFoundError,
} from './FlowChecker.tsx'
const createNode = (id: string, type: string): Node => {
return {
data: {},
position: {
x: 0,
y: 0
},
id,
type,
}
}
const createConnection = function (source: string, target: string, sourceHandle: string | null = null, targetHandle: string | null = null): Connection {
return {
source,
target,
sourceHandle,
targetHandle,
}
}
/* check add connection */
test(sourceNodeNotFoundError().message, () => {
expect(() => checkAddConnection(createConnection('a', 'b'), [], []))
})
test(targetNodeNotFoundError().message, () => {
expect(() => checkAddConnection(createConnection('a', 'b'), [createNode('a', 'normal-node')], []))
})
test(nodeToSelfError().message, () => {
expect(() => {
// language=JSON
const {
nodes,
edges
} = JSON.parse('{\n "nodes": [\n {\n "id": "P14abHl4uY",\n "type": "start-node",\n "position": {\n "x": 100,\n "y": 100\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 82\n }\n },\n {\n "id": "3YDRebKqCX",\n "type": "end-node",\n "position": {\n "x": 773.3027344262372,\n "y": 101.42648884412338\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 74\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "YXJ91nHVaz",\n "type": "llm-node",\n "position": {\n "x": 430.94541183662506,\n "y": 101.42648884412338\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 74\n },\n "selected": true,\n "dragging": false\n }\n ],\n "edges": [\n {\n "source": "P14abHl4uY",\n "target": "YXJ91nHVaz",\n "id": "xy-edge__P14abHl4uY-YXJ91nHVaz"\n },\n {\n "source": "YXJ91nHVaz",\n "target": "3YDRebKqCX",\n "id": "xy-edge__YXJ91nHVaz-3YDRebKqCX"\n }\n ],\n "data": {}\n}')
checkAddConnection(createConnection('YXJ91nHVaz', 'YXJ91nHVaz'), nodes, edges)
}).toThrowError(nodeToSelfError())
})
test(hasCycleError().message, () => {
expect(() => {
// language=JSON
const {
nodes,
edges,
} = JSON.parse('{\n "nodes": [\n {\n "id": "-DKfXm7r3f",\n "type": "start-node",\n "position": {\n "x": -75.45812782717618,\n "y": 14.410669352596976\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 82\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "2uL3Hw2CAW",\n "type": "end-node",\n "position": {\n "x": 734.7875356349059,\n "y": -1.2807079327602473\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 74\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "yp-yYfKUzC",\n "type": "llm-node",\n "position": {\n "x": 338.2236369686051,\n "y": -92.5759939566568\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 74\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "N4HQPN-NYZ",\n "type": "llm-node",\n "position": {\n "x": 332.51768159211156,\n "y": 114.26488844123382\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 74\n },\n "selected": true,\n "dragging": false\n }\n ],\n "edges": [\n {\n "source": "-DKfXm7r3f",\n "target": "yp-yYfKUzC",\n "id": "xy-edge__-DKfXm7r3f-yp-yYfKUzC"\n },\n {\n "source": "yp-yYfKUzC",\n "target": "2uL3Hw2CAW",\n "id": "xy-edge__yp-yYfKUzC-2uL3Hw2CAW"\n },\n {\n "source": "-DKfXm7r3f",\n "target": "N4HQPN-NYZ",\n "id": "xy-edge__-DKfXm7r3f-N4HQPN-NYZ"\n },\n {\n "source": "N4HQPN-NYZ",\n "target": "yp-yYfKUzC",\n "id": "xy-edge__N4HQPN-NYZ-yp-yYfKUzC"\n }\n ],\n "data": {}\n}')
// language=JSON
checkAddConnection(JSON.parse('{\n "source": "yp-yYfKUzC",\n "sourceHandle": null,\n "target": "N4HQPN-NYZ",\n "targetHandle": null\n}'), nodes, edges)
}).toThrowError(hasCycleError())
})

View File

@@ -0,0 +1,78 @@
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
constructor(
id: number,
message: string,
) {
super(message)
this.id = `E${lpad(toStr(id), 6, '0')}`
}
public toString(): string {
return `${this.id}: ${this.message}`
}
}
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) => {
}
export const sourceNodeNotFoundError = () => new CheckError(200, '连线起始节点未找到')
export const targetNodeNotFoundError = () => new CheckError(201, '连线目标节点未找到')
export const nodeToSelfError = () => new CheckError(203, '节点不能直连自身')
export const hasCycleError = () => new CheckError(204, '禁止流程循环')
const hasCycle = (sourceNode: Node, targetNode: Node, nodes: Node[], edges: Edge[], visited = new Set<string>()) => {
if (visited.has(targetNode.id)) return false
visited.add(targetNode.id)
for (const outgoer of getOutgoers(targetNode, nodes, edges)) {
if (isEqual(outgoer.id, sourceNode.id)) return true
if (hasCycle(sourceNode, outgoer, nodes, edges, visited)) return true
}
}
export const checkAddConnection: (connection: Connection, nodes: Node[], edges: Edge[]) => void = (connection, nodes, edges) => {
let sourceNode = getNodeById(connection.source, nodes)
if (!sourceNode) {
throw sourceNodeNotFoundError()
}
let targetNode = getNodeById(connection.target, nodes)
if (!targetNode) {
throw targetNodeNotFoundError()
}
// 禁止流程出现环,必须是有向无环图
if (isEqual(sourceNode.id, targetNode.id)) {
throw nodeToSelfError()
} else if (hasCycle(sourceNode, targetNode, nodes, edges)) {
throw hasCycleError()
}
// let newEdges = [...clone(edges), {...connection, id: uuid()}]
// let {hasAbnormalEdges} = getParallelInfo(nodes, newEdges)
// if (hasAbnormalEdges) {
// throw hasRedundantEdgeError()
// }
}
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 (isEmpty(nodes)) {
throw atLeastOneNode()
}
for (let node of nodes) {
if (!data[node.id] || !data[node.id]?.finished) {
throw hasUnfinishedNode(node.id)
}
}
}

View File

@@ -0,0 +1,322 @@
import {PlusCircleFilled, RollbackOutlined, SaveFilled} from '@ant-design/icons'
import {
Background,
BackgroundVariant,
Controls,
type Edge,
MiniMap,
type Node,
type NodeProps,
ReactFlow
} from '@xyflow/react'
import type {Schema} from 'amis'
import {Button, Drawer, Dropdown, message, Popconfirm, Space} from 'antd'
import {arrToMap, find, isEqual, isNil, randomId} from 'licia'
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 OutputNode from './node/OutputNode.tsx'
import KnowledgeNode from './node/KnowledgeNode.tsx'
import LlmNode from './node/LlmNode.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%;
.react-flow__node.selectable {
&:focus {
box-shadow: 0 0 20px 1px #e8e8e8;
border-radius: 8px;
}
}
.react-flow__handle.connectionindicator {
width: 10px;
height: 10px;
background-color: #ffffff;
border: 1px solid #000000;
&:hover {
background-color: #e8e8e8;
border: 1px solid #c6c6c6;
}
}
.toolbar {
position: absolute;
right: 20px;
top: 20px;
z-index: 10;
}
.node-card {
cursor: default;
.card-container {
}
}
`
export type GraphData = { nodes: Node[], edges: Edge[], data: any }
export type FlowEditorProps = {
graphData: GraphData,
onGraphDataChange: (graphData: GraphData) => void,
}
function FlowEditor(props: FlowEditorProps) {
const navigate = useNavigate()
const [messageApi, contextHolder] = message.useMessage()
const [nodeDef] = useState<{
key: string,
name: string,
component: MemoExoticComponent<(props: NodeProps) => JSX.Element>
}[]>([
{
key: 'output-node',
name: '输出',
component: OutputNode,
},
{
key: 'llm-node',
name: '大模型',
component: LlmNode,
},
{
key: 'knowledge-node',
name: '知识库',
component: KnowledgeNode,
},
{
key: 'code-node',
name: '代码执行',
component: CodeNode,
},
{
key: 'switch-node',
name: '条件分支',
component: SwitchNode,
},
])
const [open, setOpen] = useState(false)
const {data, setData, getDataById, setDataById} = useDataStore()
const {
nodes,
addNode,
removeNode,
setNodes,
onNodesChange,
edges,
setEdges,
onEdgesChange,
onConnect,
} = useFlowStore()
const [currentNodeForm, setCurrentNodeForm] = useState<JSX.Element>()
const editNode = (id: string, columnSchema?: Schema[]) => {
if (!isNil(columnSchema)) {
setCurrentNodeForm(
amisRender(
{
type: 'wrapper',
size: 'none',
body: [
{
debug: commonInfo.debug,
type: 'form',
...horizontalFormOptions(),
wrapWithPanel: false,
onEvent: {
submitSucc: {
actions: [
{
actionType: 'custom',
// @ts-ignore
script: (context, action, event) => {
setDataById(
id,
{
...context.props.data,
finished: true,
}
)
setOpen(false)
},
},
],
},
},
body: [
...(columnSchema ?? []),
{
type: 'wrapper',
size: 'none',
className: 'space-x-2 text-right',
body: [
{
type: 'action',
label: '取消',
onEvent: {
click: {
actions: [
{
actionType: 'custom',
// @ts-ignore
script: (context, action, event) => {
setOpen(false)
},
},
],
},
},
},
{
type: 'submit',
label: '保存',
level: 'primary',
},
],
},
],
},
],
},
getDataById(id),
),
)
setOpen(true)
}
}
// 用于透传node操作到主流程
const initialNodeHandlers = {
getDataById,
setDataById,
removeNode,
editNode,
}
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 = {}
let initialNodes = props.graphData?.nodes ?? []
let initialEdges = props.graphData?.edges ?? []
let initialNodeData = props.graphData?.data ?? {}
setData(initialNodeData)
for (let node of initialNodes) {
node.data = initialNodeHandlers
}
setNodes(initialNodes)
setEdges(initialEdges)
}, [props.graphData])
return (
<FlowableDiv>
{contextHolder}
<Space className="toolbar">
<Dropdown
menu={{
items: nodeDef.map(def => ({key: def.key, label: def.name})),
onClick: ({key}) => {
try {
if (commonInfo.debug) {
console.info('Add', key, JSON.stringify({nodes, edges, data}))
}
checkAddNode(key, nodes, edges)
addNode({
id: randomId(10),
type: key,
position: {x: 100, y: 100},
data: initialNodeHandlers,
})
} catch (e) {
// @ts-ignore
messageApi.error(e.toString())
}
},
}}
>
<Button type="default">
<PlusCircleFilled/>
</Button>
</Dropdown>
<Popconfirm
title="返回上一页"
description="未保存的流程图将会被丢弃,确认是否返回"
onConfirm={() => navigate(-1)}
>
<Button type="default">
<RollbackOutlined/>
</Button>
</Popconfirm>
<Button type="primary" onClick={() => {
try {
if (commonInfo.debug) {
console.info('Save', JSON.stringify({nodes, edges, data}))
}
checkSave(nodes, edges, data)
props.onGraphDataChange({nodes, edges, data})
} catch (e) {
// @ts-ignore
messageApi.error(e.toString())
}
}}>
<SaveFilled/>
</Button>
</Space>
<Drawer
title="节点编辑"
open={open}
closeIcon={false}
maskClosable={false}
destroyOnHidden
size="large"
>
{currentNodeForm}
</Drawer>
<ReactFlow
nodes={nodes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={(connection) => {
try {
if (commonInfo.debug) {
console.info('Connection', JSON.stringify(connection), JSON.stringify({nodes, edges, data}))
}
checkAddConnection(connection, nodes, edges)
onConnect(connection)
} catch (e) {
// @ts-ignore
messageApi.error(e.toString())
}
}}
// @ts-ignore
nodeTypes={arrToMap(
nodeDef.map(def => def.key),
key => find(nodeDef, def => isEqual(key, def.key))!.component)
}
fitView
>
<Controls/>
<MiniMap/>
<Background variant={BackgroundVariant.Cross} gap={20} size={3}/>
</ReactFlow>
</FlowableDiv>
)
}
export default FlowEditor

View File

@@ -4,7 +4,7 @@ import type {Schema} from 'amis'
import {Card, Dropdown} from 'antd' import {Card, Dropdown} from 'antd'
import {isEmpty, isEqual, isNil} from 'licia' import {isEmpty, isEqual, isNil} from 'licia'
import {type JSX} from 'react' import {type JSX} from 'react'
import {horizontalFormOptions} from '../../../../util/amis.tsx' import {horizontalFormOptions} from '../../../util/amis.tsx'
export type AmisNodeType = 'normal' | 'start' | 'end' export type AmisNodeType = 'normal' | 'start' | 'end'
@@ -187,9 +187,9 @@ const AmisNode: (props: AmisNodeProps) => JSX.Element = ({
{isNil(handlers) {isNil(handlers)
? <> ? <>
{isEqual(type, 'start') || isEqual(type, 'normal') {isEqual(type, 'start') || isEqual(type, 'normal')
? <Handle type="source" position={Position.Right}/> : undefined} ? <Handle type="source" position={Position.Right} id="source"/> : undefined}
{isEqual(type, 'end') || isEqual(type, 'normal') {isEqual(type, 'end') || isEqual(type, 'normal')
? <Handle type="target" position={Position.Left}/> : undefined} ? <Handle type="target" position={Position.Left} id="target"/> : undefined}
</> </>
: handlers?.(nodeData)} : handlers?.(nodeData)}
</div> </div>

View File

@@ -1,5 +1,6 @@
import type {NodeProps} from '@xyflow/react' import type {NodeProps} from '@xyflow/react'
import AmisNode, {inputsFormColumns, outputsFormColumns} from './AmisNode.tsx' import AmisNode, {inputsFormColumns, outputsFormColumns} from './AmisNode.tsx'
import React from 'react'
const CodeNode = (props: NodeProps) => AmisNode({ const CodeNode = (props: NodeProps) => AmisNode({
nodeProps: props, nodeProps: props,
@@ -48,4 +49,4 @@ const CodeNode = (props: NodeProps) => AmisNode({
], ],
}) })
export default CodeNode export default React.memo(CodeNode)

View File

@@ -1,6 +1,7 @@
import type {NodeProps} from '@xyflow/react' import type {NodeProps} from '@xyflow/react'
import {commonInfo} from '../../../../util/amis.tsx' import {commonInfo} from '../../../util/amis.tsx'
import AmisNode, {inputsFormColumns, outputsFormColumns} from './AmisNode.tsx' import AmisNode, {inputsFormColumns, outputsFormColumns} from './AmisNode.tsx'
import React from 'react'
const KnowledgeNode = (props: NodeProps) => AmisNode({ const KnowledgeNode = (props: NodeProps) => AmisNode({
nodeProps: props, nodeProps: props,
@@ -62,4 +63,4 @@ const KnowledgeNode = (props: NodeProps) => AmisNode({
], ],
}) })
export default KnowledgeNode export default React.memo(KnowledgeNode)

View File

@@ -1,6 +1,7 @@
import type {NodeProps} from '@xyflow/react' import type {NodeProps} from '@xyflow/react'
import {Tag} from 'antd' import {Tag} from 'antd'
import AmisNode, {inputsFormColumns, outputsFormColumns} from './AmisNode.tsx' import AmisNode, {inputsFormColumns, outputsFormColumns} from './AmisNode.tsx'
import React from 'react'
const modelMap: Record<string, string> = { const modelMap: Record<string, string> = {
qwen3: 'Qwen3', qwen3: 'Qwen3',
@@ -47,4 +48,4 @@ const LlmNode = (props: NodeProps) => AmisNode({
], ],
}) })
export default LlmNode export default React.memo(LlmNode)

View File

@@ -1,12 +1,13 @@
import type {NodeProps} from '@xyflow/react' import type {NodeProps} from '@xyflow/react'
import AmisNode, {outputsFormColumns} from './AmisNode.tsx' import AmisNode, {outputsFormColumns} from './AmisNode.tsx'
import React from 'react'
const EndNode = (props: NodeProps) => AmisNode({ const OutputNode = (props: NodeProps) => AmisNode({
nodeProps: props, nodeProps: props,
type: 'end', type: 'end',
defaultNodeName: '结束节点', defaultNodeName: '输出节点',
defaultNodeDescription: '定义输出变量', defaultNodeDescription: '定义输出变量',
columnSchema: outputsFormColumns(true), columnSchema: outputsFormColumns(true),
}) })
export default EndNode export default React.memo(OutputNode)

View File

@@ -0,0 +1,55 @@
import {Handle, type NodeProps, Position} from '@xyflow/react'
import {Tag} from 'antd'
import React from 'react'
import AmisNode from './AmisNode.tsx'
const cases = [
{
index: 1,
},
{
index: 2,
},
{
index: 3,
},
]
const SwitchNode = (props: NodeProps) => AmisNode({
nodeProps: props,
type: 'normal',
defaultNodeName: '分支节点',
defaultNodeDescription: '根据不同的情况前往不同的分支',
columnSchema: [],
// @ts-ignore
extraNodeDescription: nodeData => {
return (
<div className="mt-2">
{cases.map(item => (
<div key={item.index} className="mt-1">
<Tag className="m-0" color="blue"> {item.index}</Tag>
</div>
))}
</div>
)
},
// @ts-ignore
handlers: nodeData => {
return (
<>
<Handle type="target" position={Position.Left}/>
{cases.map((item, index) => (
<Handle
type="source"
position={Position.Right}
key={item.index}
id={`${item.index}`}
style={{top: 85 + (25 * index)}}
/>
))}
</>
)
},
})
export default React.memo(SwitchNode)

View File

@@ -1,7 +1,7 @@
import {createRoot} from 'react-dom/client' import {createRoot} from 'react-dom/client'
import {createHashRouter, RouterProvider} from 'react-router' import {createHashRouter, RouterProvider} from 'react-router'
import './index.scss' import './index.scss'
import './components/Registry.ts' import './components/amis/Registry.ts'
import {routes} from './route.tsx' import {routes} from './route.tsx'

View File

@@ -1,66 +1,128 @@
import {ProLayout} from '@ant-design/pro-components' import {type AppItemProps, ProLayout} from '@ant-design/pro-components'
import {ConfigProvider} from 'antd' import {ConfigProvider} from 'antd'
import React from 'react' import {dateFormat} from 'licia'
import React, {useMemo} from 'react'
import {Outlet, useLocation, useNavigate} from 'react-router' import {Outlet, useLocation, useNavigate} from 'react-router'
import styled from 'styled-components'
import {menus} from '../route.tsx' import {menus} from '../route.tsx'
const apps: { title: string, desc: string, url: string, icon?: string }[] = [ const ProLayoutDiv = styled.div`
position: relative;
width: 100%;
height: 100%;
padding: 0;
margin: 0;
.ant-menu-sub > .ant-menu-item {
padding-left: 16px !important;
}
`
const defaultAppIcon =
<img
src={'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAMAAAC7IEhfAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAMAUExURUdwTBR20EyHx1iq5EWJ1hNyy0mR1EhzwnbB/8P5/Fx/vVuj5zyO4lCY102P0L3u/3K88dz4/8v1/0fW/jLh/013ujN4wBliuEuEy0FrqT13wFmCvkaH0GSLyBVVqe38/0il4FKu7crr/eL3/7Ls/zd3t1WN1TZcnTloojx6whpYpTdfoDVwtVeS1WeOyiNhsTFyuy50wHCPxDFgqLjK5G2Ow2Gy5ylpvB9uxA5x03W/71Wh4E2U2tr2/i6C3G7J+Gex7KTI8eb9/cbz/yC+/srl++P7/Znf+MPv/cn3/rz6/dL8/2fe/8v+/s/6/knN87f5/jx5uRZtwjRppU6I1liM2Bhcrmyl2kZ5uA9vzjd0wj95yjVstqze9hiD2zOH1kqv7Wqv5K7S7LLn/YfT+sfp/bPf+4jb/YbX+735/SjQ/T7J+VjV9rTs+0ns/6Dk/mPJ7eD9/b/8/Q9YxA5Zxw5Zwg5dwg5byhdn0kSO2xFezg5gwg1XwRBjwkqW4EeT3kuY20mV2BBVtg5avxFoxQ9Yu0+g3xJYslWi5h2q9SKA4AtTwAxjzUGN2UiN0VOm4yKj8NX7/0WQ3RFtyUaR1h95zSOc706J0Bt34VCi5yqw9F6s6SOI5Bx02h2M6Rh13SCX7k2c3E6a4lCd5EeQ2iVtyCJ54BVt3ROV8x+0+jS9+hGq+Ra0/WK37sPy/iOR6R1w2A5p0y9nrjJ/1EaO1yV1yDt+zBaJ4hF83FuJyg5nyhei9hJ96BN35ByV5ymq8S151muu5UCr6hzE/xS+/47h/3/r/xyG5SKV6yJ43BlswBJivA5z2A9duw5s1C590CZXpDVvuhec9BGM7xJQrxKE61yo4DOF4DeZ64jG8bbp/h/Q/j2F0xpr1xliyROA4CRst1mc10d8whNQqDqb3Sig5qrh/qLW9iZ/5UeY5pDU9UWf6J7O9oju/mDV/aXp/orj/6P7/4z3/2Pr/iLa/kaDxnuw57rf9ZfW+2Sd5G3X/7LW9zyR51TI+Dao7Zno//A+0MwAAADpdFJOUwD7Lv/+/v4CAQIK/v7+/P7+b/7+/iKh/f5LjBv8z/4d/v5cNf6A5piF/Pts9PST/tP+Qd0Oc/72Pf5B/Pv0/vv7zqD6/4qU+5JjlCv7ff79/lz628SK/pmm+/5cnh/+/vPht/r+pPKX44z7+/z7/P7+wNL////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////+///////////////////////+1awirQAAA+BJREFUOMtjYCAXcMIAAVW4OKjKgJjDW8nXyytT0NOKCyjAgUudt29RwMdPb48dO/b2aEa6MkQvpjrlQqCqz3ki/j4+2VnCv44+S5XHVAm0xHPixHXuOSIiX4TfHeo87OJin/IjTYmBgwNdndvEibkF/sIiX26/+7f6yJo1K/fPtL/53BXDPKeJQkLvPx87Knz79qzOI2tWr959acFaAYE3rii2cwDVOQutU8k/+uHv4cNrQMpWrFgxTXHtWoc3gkgqORkEJzqvW3fr/f8Paye4rFzZufvSisuXr95QVJw9W+C3MlwlB4O87Tp+fn6VV2sVgOo6wequ7tkz4zWP3QHrm45IBroJJd/if37w0CygaZ0Tpi1YMO/qnr17b7yeMePFAZufSlAjQQbeyle5qbBq1apZIGUn1s87DlS3/DrPsj8vr/McdES48Lv7q4NPVq3avx+sbP2cOV0zZsxfftfuZcdsbm6Bb1YM7BATk64pPHk6C6hqGljVnK6uZSfnzl2+bObMmR3csx0OhkIUMpgkHgKatW/fvO3HjwMVdXWdPHly7oYNd3mA6jo6uLm5Q0ABDcSxCU/37du+/f79HfPnz507dwNQ0Ya7dyuudyzu6Fi8eNGiOjUukEp2BqZDcXE7dpw5c+bcuY0bK+CgbtEioLK6+kmVLKIQhRZP4iwtgWp6gKCqpwoCyivqQACorLeXhQnkSKDC83a7dgEVlfeUw0BJScm9SfVAAFTHwjIdqpBpafyuspISIEICxSWV9ZMmLQGr0wVbzcEgbb518+YDFcWlxUAAUgMGNXfqKisrl1QCFaqZgL3NwGkgzsbb2LC5u7sYAUprWu/UL2HZto1FZrosJGbYGWIMbdjYpjRuvtddU1MDVAMB3U3bljZdubJNZqceJMDZGSQv8vX1TZnS2HCguwaqqrS5ubm1CQiuRE3faQSNGQYu469glVMalnZ315SBAUghUGX7Y/3psrD0yM6gvQmoEGh5Y0Pv+Xs1pdUQlUCF7e2PzXeawgwEGQm0nI2tsaFhYdvC3qVl1WClZ1vb2+XkHskisgLQlRc0IeoWtrUxn2+urT5dXVt99ixQ4UWEC8EqNS5o8jaClLX191bXQsDps+1hWo+QLAYnIfULMrxAdf39s6dWt4BB7enT4lqb9Bg40DK2+iZea2tmZub+qbsmA0HLqZZT4vqbpBgYMIoKbZ2H166Z1U9mhYKgUw+CJdHVgd0pGvHwmllvJCMYsJ56oKPBheI+hEoGpnDdrVungsBWQwNVaQas6oCWAIWlo6WkxMTEVAOZQFo5cJW57Mgm4FYGMRUGyK0tAGzv0vrmaa6xAAAAAElFTkSuQmCC'}
/>
const apps: AppItemProps[] = [
{
icon: 'http://132.121.223.12:7001/static/webssh/favicon2.ico',
title: '运营数据汇聚平台',
desc: '企业全融合数字化平台',
url: 'http://132.121.223.12:7001/index.html/#/login',
},
{ {
icon: 'http://132.126.207.124:8686/udal-manager/static/favicon.ico', icon: 'http://132.126.207.124:8686/udal-manager/static/favicon.ico',
title: 'CSV-HUDI处理平台', title: 'CSV-HUDI处理平台',
desc: 'Hudi 批量割接、稽核任务管理平台', desc: 'Hudi 批量割接、稽核任务管理平台',
url: 'http://132.126.207.124:8686/udal-manager/', url: 'http://132.126.207.124:8686/udal-manager/',
}, },
{
icon: defaultAppIcon,
title: '汇聚平台辅助工具',
desc: '辅助工具,用于帮助运营工作,不断改进中',
url: 'http://132.121.204.100:38080/tools/#/',
},
{
icon: defaultAppIcon,
title: 'B12-Yarn',
desc: 'B12集群Yarn页面',
url: 'http://132.126.207.125:8088/cluster/scheduler',
},
] ]
const App: React.FC = () => { const App: React.FC = () => {
const navigate = useNavigate() const navigate = useNavigate()
const location = useLocation() const location = useLocation()
const currentYear = useMemo(() => dateFormat(new Date(), 'yyyy'), [])
return ( return (
<ProLayout <ProLayoutDiv>
token={{ <ProLayout
colorTextAppListIcon: '#dfdfdf', siderWidth={180}
colorTextAppListIconHover: '#ffffff', token={{
header: { colorTextAppListIcon: '#dfdfdf',
colorBgHeader: '#292f33', colorTextAppListIconHover: '#ffffff',
colorHeaderTitle: '#ffffff', header: {
colorTextMenu: '#dfdfdf', colorBgHeader: '#292f33',
colorTextMenuSecondary: '#dfdfdf', colorHeaderTitle: '#ffffff',
colorTextMenuSelected: '#ffffff', colorTextMenu: '#dfdfdf',
colorTextMenuActive: '#ffffff', colorTextMenuSecondary: '#dfdfdf',
colorBgMenuItemSelected: '#22272b', colorTextMenuSelected: '#ffffff',
colorTextRightActionsItem: '#dfdfdf', colorTextMenuActive: '#ffffff',
}, colorBgMenuItemSelected: '#22272b',
}} colorTextRightActionsItem: '#dfdfdf',
appList={apps} },
disableMobile={true} pageContainer: {
logo={<img src="icon.png" alt="logo"/>} paddingBlockPageContainerContent: 0,
title="Hudi 服务总台" paddingInlinePageContainerContent: 0,
route={menus} marginBlockPageContainerContent: 0,
location={{pathname: location.pathname}} marginInlinePageContainerContent: 0,
menu={{type: 'sub'}}
menuItemRender={(item, dom) => {
return <div onClick={() => navigate(item.path || '/')}>{dom}</div>
}}
fixSiderbar={true}
layout="mix"
splitMenus={true}
style={{minHeight: '100vh'}}
contentStyle={{backgroundColor: 'white', padding: '10px 10px 10px 20px'}}
>
<ConfigProvider
theme={{
components: {
Card: {
bodyPadding: 0,
bodyPaddingSM: 0,
},
}, },
}} }}
appList={apps}
defaultCollapsed={false}
breakpoint={false}
disableMobile={true}
logo={<img src="icon.png" alt="logo"/>}
title="Hudi 服务总台"
route={menus}
location={{pathname: location.pathname}}
menu={{type: 'sub'}}
menuItemRender={(item) => {
return (
<div onClick={() => navigate(item.path || '/')}>
{item.icon}
<span className="ml-2">{item.name}</span>
</div>
)
}}
fixSiderbar={true}
layout="mix"
splitMenus={true}
style={{minHeight: '100vh'}}
contentStyle={{backgroundColor: 'white', padding: '10px 10px 10px 20px'}}
menuFooterRender={props => {
return (
<div className="text-sm text-center" style={{userSelect: 'none', msUserSelect: 'none'}}>
{props?.collapsed
? undefined
: <div>© 2023-{currentYear} </div>}
</div>
)
}}
> >
<Outlet/> <ConfigProvider
</ConfigProvider> theme={{
</ProLayout> components: {
Card: {
bodyPadding: 0,
bodyPaddingSM: 0,
},
},
}}
>
<Outlet/>
</ConfigProvider>
</ProLayout>
</ProLayoutDiv>
) )
} }

View File

@@ -1,76 +0,0 @@
import {type Edge, type Node} from '@xyflow/react'
export const buildEL = (nodes: Node[], edges: Edge[]): string => {
const nodeMap: Map<string, Node> = new Map<string, Node>()
// 构建邻接列表和内图
const adjList = new Map<string, string[]>()
const inDegree = new Map<string, number>()
for (const node of nodes) {
nodeMap.set(node.id, node)
adjList.set(node.id, [])
inDegree.set(node.id, 0)
}
for (const edge of edges) {
adjList.get(edge.source)!.push(edge.target)
inDegree.set(edge.target, inDegree.get(edge.target)! + 1)
}
// Compute levels (longest path from start)
const levelMap = new Map<string, number>()
function computeLevel(nodeId: string): number {
if (levelMap.has(nodeId)) return levelMap.get(nodeId)!
const preds = edges.filter(e => e.target === nodeId).map(e => e.source)
const level = preds.length === 0 ? 0 : Math.max(...preds.map(p => computeLevel(p))) + 1
levelMap.set(nodeId, level)
return level
}
for (const node of nodes) computeLevel(node.id)
// Group nodes by level
const maxLevel = Math.max(...Array.from(levelMap.values()))
const levels: string[][] = Array.from({length: maxLevel + 1}, () => [])
for (const node of nodes) levels[levelMap.get(node.id)!].push(node.id)
const covertNodeFromId = (id: string) => {
let node = nodeMap.get(id)!
return `node("${node.type}").bind("nodeId", ${node.id})`
}
// Build EL expression
const expressions: string[] = []
for (let i = 0; i <= maxLevel; i++) {
const nodesAtLevel = levels[i]
if (nodesAtLevel.length === 0) continue
// 识别从这个级别开始的串行链
const serialChains: string[] = []
for (const nodeId of nodesAtLevel) {
let chain = [nodeId]
let current = nodeId
while (adjList.get(current)?.length === 1) {
const next = adjList.get(current)![0]
if (inDegree.get(next) === 1 && levelMap.get(next) === i + chain.length) {
chain.push(next)
current = next
} else break
}
if (chain.length > 1) {
serialChains.push(`THEN(${chain.map(id => covertNodeFromId(id)).join(',')})`)
// Remove processed nodes from their levels
for (let j = 1; j < chain.length; j++) {
const level = levelMap.get(chain[j])!
levels[level] = levels[level].filter(n => n !== chain[j])
}
} else {
serialChains.push(covertNodeFromId(nodeId))
}
}
// Combine chains or nodes at this level
expressions.push(serialChains.length > 1 ? `WHEN(${serialChains.join(', ')})` : serialChains[0])
}
return `THEN(${expressions.join(',')})`
}

View File

@@ -1,366 +0,0 @@
import {PlusCircleFilled, SaveFilled} from '@ant-design/icons'
import {
Background,
BackgroundVariant,
type Connection,
Controls,
type Edge,
getOutgoers,
MiniMap,
type Node,
type NodeProps,
ReactFlow,
} from '@xyflow/react'
import {useMount} from 'ahooks'
import type {Schema} from 'amis'
import {Button, Drawer, Dropdown, message, Space} from 'antd'
import {arrToMap, find, findIdx, isEqual, isNil, randomId} from 'licia'
import {type JSX, useState} from 'react'
import styled from 'styled-components'
import '@xyflow/react/dist/style.css'
import {amisRender, commonInfo, horizontalFormOptions} from '../../../util/amis.tsx'
import {buildEL} from './ElParser.tsx'
import CodeNode from './node/CodeNode.tsx'
import EndNode from './node/EndNode.tsx'
import KnowledgeNode from './node/KnowledgeNode.tsx'
import LlmNode from './node/LlmNode.tsx'
import StartNode from './node/StartNode.tsx'
import {useDataStore} from './store/DataStore.ts'
import {useFlowStore} from './store/FlowStore.ts'
const FlowableDiv = styled.div`
height: 100%;
.react-flow__node.selectable {
&:focus {
box-shadow: 0 0 20px 1px #e8e8e8;
border-radius: 8px;
}
}
.react-flow__handle.connectionindicator {
width: 10px;
height: 10px;
background-color: #ffffff;
border: 1px solid #000000;
&:hover {
background-color: #e8e8e8;
border: 1px solid #c6c6c6;
}
}
.toolbar {
position: absolute;
right: 20px;
top: 20px;
z-index: 10;
}
.node-card {
cursor: default;
.card-container {
}
}
`
function FlowEditor() {
const [messageApi, contextHolder] = message.useMessage()
const [nodeDef] = useState<{
key: string,
name: string,
component: (props: NodeProps) => JSX.Element
}[]>([
{
key: 'start-node',
name: '开始',
component: StartNode,
},
{
key: 'end-node',
name: '结束',
component: EndNode,
},
{
key: 'llm-node',
name: '大模型',
component: LlmNode,
},
{
key: 'knowledge-node',
name: '知识库',
component: KnowledgeNode,
},
{
key: 'code-node',
name: '代码执行',
component: CodeNode,
},
])
const [open, setOpen] = useState(false)
const {data, setData, getDataById, setDataById} = useDataStore()
const {
nodes,
getNodeById,
addNode,
removeNode,
setNodes,
onNodesChange,
edges,
setEdges,
onEdgesChange,
onConnect,
} = useFlowStore()
const [currentNodeForm, setCurrentNodeForm] = useState<JSX.Element>()
const editNode = (id: string, columnSchema?: Schema[]) => {
if (!isNil(columnSchema)) {
setCurrentNodeForm(
amisRender(
{
type: 'wrapper',
size: 'none',
body: [
{
debug: commonInfo.debug,
type: 'form',
...horizontalFormOptions(),
wrapWithPanel: false,
onEvent: {
submitSucc: {
actions: [
{
actionType: 'custom',
// @ts-ignore
script: (context, action, event) => {
setDataById(id, context.props.data)
setOpen(false)
},
},
],
},
},
body: [
...(columnSchema ?? []),
{
type: 'wrapper',
size: 'none',
className: 'space-x-2 text-right',
body: [
{
type: 'action',
label: '取消',
onEvent: {
click: {
actions: [
{
actionType: 'custom',
// @ts-ignore
script: (context, action, event) => {
setOpen(false)
},
},
],
},
},
},
{
type: 'submit',
label: '保存',
level: 'primary',
},
],
},
],
},
],
},
getDataById(id),
),
)
setOpen(true)
}
}
const checkNode = (type: string) => {
if (isEqual(type, 'start-node') && findIdx(nodes, (node: Node) => isEqual(type, node.type)) > -1) {
throw new Error('只能存在1个开始节点')
}
if (isEqual(type, 'end-node') && findIdx(nodes, (node: Node) => isEqual(type, node.type)) > -1) {
throw new Error('只能存在1个结束节点')
}
}
const checkConnection = (connection: Connection) => {
let sourceNode = getNodeById(connection.source)
if (!sourceNode) {
throw new Error('连线起始节点未找到')
}
let targetNode = getNodeById(connection.target)
if (!targetNode) {
throw new Error('连线目标节点未找到')
}
// 禁止短路整个流程
if (isEqual('start-node', sourceNode.type) && isEqual('end-node', targetNode.type)) {
throw new Error('开始节点不能直连结束节点')
}
// 禁止流程出现环,必须是有向无环图
const hasCycle = (node: Node, visited = new Set<string>()) => {
if (visited.has(node.id)) return false
visited.add(node.id)
for (const outgoer of getOutgoers(node, nodes, edges)) {
if (isEqual(outgoer.id, sourceNode?.id)) return true
if (hasCycle(outgoer, visited)) return true
}
}
if (isEqual(sourceNode.id, targetNode.id)) {
throw new Error('节点不能直连自身')
} else if (hasCycle(targetNode)) {
throw new Error('禁止流程循环')
}
/*const hasRedundant = (source: Node, target: Node) => {
const visited = new Set<string>()
const queue = new Queue<Node>()
queue.enqueue(source)
visited.add(source.id)
while (queue.size > 0) {
const current = queue.dequeue()!
console.log(current.id)
for (const incomer of getIncomers(current, nodes, edges)) {
if (isEqual(incomer.id, target.id)) {
return true
}
if (!visited.has(incomer.id)) {
visited.add(incomer.id)
queue.enqueue(incomer)
}
}
}
return false
}
if (hasRedundant(sourceNode, targetNode)) {
throw new Error('出现冗余边')
}*/
}
// @ts-ignore
const checkSave = (nodes: Node[], edges: Edge[], data: any) => {
if (nodes.filter(n => isEqual('start-node', n.type)).length < 1) {
throw new Error('至少存在1个开始节点')
}
if (nodes.filter(n => isEqual('end-node', n.type)).length < 1) {
throw new Error('至少存在1个结束节点')
}
}
// 用于透传node操作到主流程
const initialNodeHandlers = {
getDataById,
setDataById,
removeNode,
editNode,
}
useMount(() => {
// language=JSON
let initialData = JSON.parse('{\n "nodes": [\n {\n "id": "ldoKAzHnKF",\n "type": "llm-node",\n "position": {\n "x": 207,\n "y": -38\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 105\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "1eJtMoJWs6",\n "type": "llm-node",\n "position": {\n "x": 207,\n "y": 172.5\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 105\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "7e5vQLDGTl",\n "type": "start-node",\n "position": {\n "x": -162.3520537805597,\n "y": 67.84901301708827\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 105\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "Wyqg_bXILg",\n "type": "knowledge-node",\n "position": {\n "x": 560.402133595296,\n "y": -38.892263766178665\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 75\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "7DaF-0G-yv",\n "type": "llm-node",\n "position": {\n "x": 634.9924233956513,\n "y": 172.01821084172227\n },\n "data": {},\n "measured": {\n "width": 256,\n "height": 75\n },\n "selected": false,\n "dragging": false\n },\n {\n "id": "mymIbw_W6k",\n "type": "end-node",\n "position": {\n "x": 953.9302142661356,\n "y": 172.0182108417223\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": "7e5vQLDGTl",\n "target": "ldoKAzHnKF",\n "id": "xy-edge__7e5vQLDGTl-ldoKAzHnKF"\n },\n {\n "source": "ldoKAzHnKF",\n "target": "Wyqg_bXILg",\n "id": "xy-edge__ldoKAzHnKF-Wyqg_bXILg"\n },\n {\n "source": "7e5vQLDGTl",\n "target": "1eJtMoJWs6",\n "id": "xy-edge__7e5vQLDGTl-1eJtMoJWs6"\n },\n {\n "source": "Wyqg_bXILg",\n "target": "7DaF-0G-yv",\n "id": "xy-edge__Wyqg_bXILg-7DaF-0G-yv"\n },\n {\n "source": "1eJtMoJWs6",\n "target": "7DaF-0G-yv",\n "id": "xy-edge__1eJtMoJWs6-7DaF-0G-yv"\n },\n {\n "source": "7DaF-0G-yv",\n "target": "mymIbw_W6k",\n "id": "xy-edge__7DaF-0G-yv-mymIbw_W6k"\n }\n ],\n "data": {\n "7e5vQLDGTl": {\n "inputs": {\n "question": {\n "type": "text",\n "description": "问题"\n }\n }\n },\n "ldoKAzHnKF": {\n "model": "qwen3",\n "outputs": {\n "text": {\n "type": "string"\n }\n },\n "systemPrompt": "你是个聪明人"\n },\n "1eJtMoJWs6": {\n "model": "deepseek",\n "outputs": {\n "text": {\n "type": "string"\n }\n },\n "systemPrompt": "你也是个好人"\n }\n }\n}')
let initialNodes = initialData['nodes'] ?? []
let initialEdges = initialData['edges'] ?? []
let initialNodeData = initialData['data'] ?? {}
setData(initialNodeData)
for (let node of initialNodes) {
node.data = initialNodeHandlers
}
setNodes(initialNodes)
setEdges(initialEdges)
})
return (
<FlowableDiv>
{contextHolder}
<Space className="toolbar">
<Dropdown
menu={{
items: nodeDef.map(def => ({key: def.key, label: def.name})),
onClick: ({key}) => {
try {
checkNode(key)
addNode({
id: randomId(10),
type: key,
position: {x: 100, y: 100},
data: initialNodeHandlers,
})
} catch (e) {
// @ts-ignore
messageApi.error(e.message)
}
},
}}
>
<Button type="default">
<PlusCircleFilled/>
</Button>
</Dropdown>
<Button type="primary" onClick={() => {
try {
checkSave(nodes, edges, data)
let saveData = {nodes, edges, data}
console.log(JSON.stringify(saveData, null, 2))
console.log(buildEL(nodes, edges))
} catch (e) {
// @ts-ignore
messageApi.error(e.message)
}
}}>
<SaveFilled/>
</Button>
</Space>
<Drawer
title="节点编辑"
open={open}
closeIcon={false}
maskClosable={false}
destroyOnHidden
size="large"
>
{currentNodeForm}
</Drawer>
<ReactFlow
nodes={nodes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={(connection) => {
try {
checkConnection(connection)
onConnect(connection)
} catch (e) {
// @ts-ignore
messageApi.error(e.message)
}
}}
// @ts-ignore
nodeTypes={arrToMap(
nodeDef.map(def => def.key),
key => find(nodeDef, def => isEqual(key, def.key))!.component)
}
fitView
>
<Controls/>
<MiniMap/>
<Background variant={BackgroundVariant.Cross} gap={20} size={3}/>
</ReactFlow>
</FlowableDiv>
)
}
export default FlowEditor

View File

@@ -1,68 +0,0 @@
import type {NodeProps} from '@xyflow/react'
import {Tag} from 'antd'
import {each} from 'licia'
import type {JSX} from 'react'
import {horizontalFormOptions} from '../../../../util/amis.tsx'
import AmisNode from './AmisNode.tsx'
const typeMap: Record<string, string> = {
text: '文本',
number: '数字',
files: '文件',
}
const StartNode = (props: NodeProps) => AmisNode({
nodeProps: props,
type: 'start',
defaultNodeName: '开始节点',
defaultNodeDescription: '定义输入变量',
extraNodeDescription: nodeData => {
const variables: JSX.Element[] = []
const inputs = (nodeData['inputs'] ?? {}) as Record<string, { type: string, description: string }>
each(inputs, (value, key) => {
variables.push(
<div className="mt-1 flex justify-between" key={key}>
<span>{key}</span>
<Tag className="m-0" color="blue">{typeMap[value.type]}</Tag>
</div>,
)
})
return (
<div className="mt-2">
{...variables}
</div>
)
},
columnSchema: [
{
type: 'input-kvs',
name: 'inputs',
label: '输入变量',
addButtonText: '新增入参',
draggable: false,
keyItem: {
label: '参数名称',
...horizontalFormOptions(),
},
valueItems: [
{
...horizontalFormOptions(),
type: 'input-text',
name: 'description',
label: '参数描述',
},
{
...horizontalFormOptions(),
type: 'select',
name: 'type',
label: '参数类型',
required: true,
selectFirst: true,
options: Object.keys(typeMap).map(key => ({label: typeMap[key], value: key})),
},
],
},
],
})
export default StartNode

View File

@@ -0,0 +1,48 @@
import type {Schema} from 'amis'
export const typeMap: Record<string, string> = {
text: '文本',
number: '数字',
files: '文件',
}
export type InputField = {
type: string
label: string
description?: string
}
export const generateInputForm: (inputSchema: Record<string, InputField>) => Schema = inputSchema => {
let items: Schema[] = []
for (const name of Object.keys(inputSchema)) {
let field = inputSchema[name]
// @ts-ignore
let formItem: Schema = {
name: name,
...field,
}
switch (field.type) {
case 'text':
formItem = {
...formItem,
type: 'input-text',
clearValueOnEmpty: true,
}
break
case 'number':
formItem.type = 'input-number'
break
case 'files':
formItem.type = 'input-file'
break
}
items.push(formItem)
}
return {
type: 'form',
title: '入参表单预览',
canAccessSuperData: false,
actions: [],
body: items,
}
}

View File

@@ -1,6 +1,6 @@
import React from 'react' import React from 'react'
import {amisRender, commonInfo, crudCommonOptions, paginationTemplate,} from '../../../../util/amis.tsx'
import {useNavigate} from 'react-router' import {useNavigate} from 'react-router'
import {amisRender, commonInfo, crudCommonOptions, paginationTemplate} from '../../../../util/amis.tsx'
const FlowTaskTemplate: React.FC = () => { const FlowTaskTemplate: React.FC = () => {
const navigate = useNavigate() const navigate = useNavigate()
@@ -20,8 +20,8 @@ const FlowTaskTemplate: React.FC = () => {
page: { page: {
index: '${page}', index: '${page}',
size: '${perPage}', size: '${perPage}',
} },
} },
}, },
...crudCommonOptions(), ...crudCommonOptions(),
...paginationTemplate( ...paginationTemplate(
@@ -32,6 +32,8 @@ const FlowTaskTemplate: React.FC = () => {
type: 'action', type: 'action',
label: '', label: '',
icon: 'fa fa-plus', icon: 'fa fa-plus',
tooltip: '新增',
tooltipPlacement: 'top',
size: 'sm', size: 'sm',
onEvent: { onEvent: {
click: { click: {
@@ -83,6 +85,25 @@ const FlowTaskTemplate: React.FC = () => {
}, },
}, },
}, },
{
type: 'action',
label: '编辑流程',
level: 'link',
size: 'sm',
onEvent: {
click: {
actions: [
{
actionType: 'custom',
// @ts-ignore
script: (context, doAction, event) => {
navigate(`/ai/flow_task_template/flow/edit/${context.props.data['id']}`)
},
},
],
},
},
},
{ {
type: 'action', type: 'action',
label: '删除', label: '删除',

View File

@@ -1,8 +1,9 @@
import {isEmpty, isEqual} from 'licia'
import React from 'react' import React from 'react'
import {useParams} from 'react-router'
import styled from 'styled-components' import styled from 'styled-components'
import {amisRender, commonInfo, horizontalFormOptions} from '../../../../util/amis.tsx' import {amisRender, commonInfo, horizontalFormOptions} from '../../../../util/amis.tsx'
import {isEqual} from 'licia' import {generateInputForm, typeMap} from '../InputSchema.tsx'
import { useParams } from 'react-router'
const TemplateEditDiv = styled.div` const TemplateEditDiv = styled.div`
.antd-EditorControl { .antd-EditorControl {
@@ -13,7 +14,6 @@ const TemplateEditDiv = styled.div`
const FlowTaskTemplateEdit: React.FC = () => { const FlowTaskTemplateEdit: React.FC = () => {
const {template_id} = useParams() const {template_id} = useParams()
const preloadTemplateId = isEqual(template_id, '-1') ? undefined : template_id const preloadTemplateId = isEqual(template_id, '-1') ? undefined : template_id
console.log('preloadTemplateId', preloadTemplateId)
return ( return (
<TemplateEditDiv className="task-template-edit h-full"> <TemplateEditDiv className="task-template-edit h-full">
{amisRender({ {amisRender({
@@ -26,73 +26,127 @@ const FlowTaskTemplateEdit: React.FC = () => {
method: 'POST', method: 'POST',
url: `${commonInfo.baseAiUrl}/flow_task/template/save`, url: `${commonInfo.baseAiUrl}/flow_task/template/save`,
data: { data: {
name: '${template.name}', id: '${id|default:undefined}',
description: '${template.description}', name: '${name}',
inputSchema: '${template.inputSchema}', description: '${description}',
flow: '${template.flow}', inputSchema: '${inputSchema|default:undefined}',
} },
}, },
initApi: preloadTemplateId initApi: preloadTemplateId
? { ? `get:${commonInfo.baseAiUrl}/flow_task/template/detail/${preloadTemplateId}`
method: 'GET',
url: `${commonInfo.baseAiUrl}/flow_task/template/detail/${preloadTemplateId}`,
// @ts-ignore
adaptor: (payload, response, api, context) => {
return {
...payload,
data: {
template: payload.data,
},
}
},
}
: undefined, : undefined,
wrapWithPanel: false, wrapWithPanel: false,
...horizontalFormOptions(), ...horizontalFormOptions(),
onEvent: {
change: {
actions: [
{
actionType: 'validate',
},
{
actionType: 'custom',
// @ts-ignore
script: (context, doAction, event) => {
let data = event?.data ?? {}
let inputSchema = data.inputSchema ?? []
if (!isEmpty(inputSchema) && isEmpty(data?.validateResult?.error ?? undefined)) {
doAction({
actionType: 'setValue',
args: {
value: {
inputPreview: generateInputForm(inputSchema),
},
},
})
}
},
},
],
},
},
body: [ body: [
{
type: 'hidden',
name: 'id',
},
{ {
type: 'input-text', type: 'input-text',
name: 'template.name', name: 'name',
label: '名称', label: '名称',
required: true, required: true,
clearable: true,
}, },
{ {
type: 'textarea', type: 'textarea',
name: 'template.description', name: 'description',
label: '描述', label: '描述',
required: true, required: true,
clearable: true,
}, },
{ {
type: 'group', type: 'group',
body: [ body: [
{ {
type: 'editor', type: 'wrapper',
required: true, size: 'none',
label: '入参表单', body: [
description: '使用amis代码编写入参表单结构流程会解析所有name对应的变量传入流程开始阶段只需要编写form的columns部分', {
name: 'template.inputSchema', type: 'input-kvs',
value: '[]', name: 'inputSchema',
language: 'json', label: '输入变量',
options: { addButtonText: '新增入参',
wordWrap: 'bounded', draggable: false,
}, keyItem: {
label: '参数名称',
...horizontalFormOptions(),
validations: {
isAlphanumeric: true,
},
},
valueItems: [
{
...horizontalFormOptions(),
type: 'input-text',
name: 'label',
required: true,
label: '中文名称',
clearValueOnEmpty: true,
clearable: true,
},
{
...horizontalFormOptions(),
type: 'input-text',
name: 'description',
label: '参数描述',
clearValueOnEmpty: true,
clearable: true,
},
{
...horizontalFormOptions(),
type: 'select',
name: 'type',
label: '参数类型',
required: true,
selectFirst: true,
options: Object.keys(typeMap).map(key => ({label: typeMap[key], value: key})),
},
{
...horizontalFormOptions(),
type: 'switch',
name: 'required',
label: '是否必填',
required: true,
value: true,
},
],
},
],
}, },
{ {
type: 'amis', type: 'amis',
name: 'template.inputSchema', name: 'inputPreview',
} },
] ],
},
{
type: 'editor',
required: true,
label: '任务流程',
name: 'template.flow',
description: '使用标准的LiteFlow语法',
language: 'xml',
options: {
wordWrap: 'bounded',
},
}, },
{ {
type: 'button-toolbar', type: 'button-toolbar',

View File

@@ -0,0 +1,49 @@
import React, {useState} from 'react'
import styled from 'styled-components'
import {useNavigate, useParams} from 'react-router'
import {useMount} from 'ahooks'
import axios from 'axios'
import {commonInfo} from '../../../../util/amis.tsx'
import FlowEditor, {type GraphData} from '../../../../components/flow/FlowEditor.tsx'
const FlowTaskTemplateFlowEditDiv = styled.div`
`
const FlowTaskTemplateFlowEdit: React.FC = () => {
const navigate = useNavigate()
const {template_id} = useParams()
const [graphData, setGraphData] = useState<GraphData>({nodes: [], edges: [], data: {}})
useMount(async () => {
let {data} = await axios.get(
`${commonInfo.baseAiUrl}/flow_task/template/detail/${template_id}`,
{
headers: commonInfo.authorizationHeaders
}
)
setGraphData(data?.data?.flowGraph)
})
return (
<FlowTaskTemplateFlowEditDiv className="h-full w-full">
<FlowEditor
graphData={graphData}
onGraphDataChange={async data => {
await axios.post(
`${commonInfo.baseAiUrl}/flow_task/template/update_flow_graph`,
{
id: template_id,
graph: data
},
{
headers: commonInfo.authorizationHeaders
}
)
navigate(-1)
}}
/>
</FlowTaskTemplateFlowEditDiv>
)
}
export default FlowTaskTemplateFlowEdit

View File

@@ -22,6 +22,10 @@ import DataDetail from './pages/ai/knowledge/DataDetail.tsx'
import DataImport from './pages/ai/knowledge/DataImport.tsx' import DataImport from './pages/ai/knowledge/DataImport.tsx'
import DataSegment from './pages/ai/knowledge/DataSegment.tsx' import DataSegment from './pages/ai/knowledge/DataSegment.tsx'
import Knowledge from './pages/ai/knowledge/Knowledge.tsx' import Knowledge from './pages/ai/knowledge/Knowledge.tsx'
import FlowTask from './pages/ai/task/FlowTask.tsx'
import FlowTaskAdd from './pages/ai/task/FlowTaskAdd.tsx'
import FlowTaskTemplate from './pages/ai/task/template/FlowTaskTemplate.tsx'
import FlowTaskTemplateEdit from './pages/ai/task/template/FlowTaskTemplateEdit.tsx'
import App from './pages/App.tsx' import App from './pages/App.tsx'
import Cloud from './pages/overview/Cloud.tsx' import Cloud from './pages/overview/Cloud.tsx'
import Overview from './pages/overview/Overview.tsx' import Overview from './pages/overview/Overview.tsx'
@@ -34,11 +38,7 @@ import Yarn from './pages/overview/Yarn.tsx'
import YarnCluster from './pages/overview/YarnCluster.tsx' import YarnCluster from './pages/overview/YarnCluster.tsx'
import Test from './pages/Test.tsx' import Test from './pages/Test.tsx'
import {commonInfo} from './util/amis.tsx' import {commonInfo} from './util/amis.tsx'
import FlowEditor from './pages/ai/flow/FlowEditor.tsx' import FlowTaskTemplateFlowEdit from './pages/ai/task/template/FlowTaskTemplateFlowEdit.tsx'
import FlowTaskTemplate from './pages/ai/task/template/FlowTaskTemplate.tsx'
import FlowTaskTemplateEdit from './pages/ai/task/template/FlowTaskTemplateEdit.tsx'
import FlowTask from './pages/ai/task/FlowTask.tsx'
import FlowTaskAdd from './pages/ai/task/FlowTaskAdd.tsx'
export const routes: RouteObject[] = [ export const routes: RouteObject[] = [
{ {
@@ -133,9 +133,9 @@ export const routes: RouteObject[] = [
Component: FlowTaskTemplateEdit, Component: FlowTaskTemplateEdit,
}, },
{ {
path: 'flowable', path: 'flow_task_template/flow/edit/:template_id',
Component: FlowEditor, Component: FlowTaskTemplateFlowEdit,
}, }
], ],
}, },
{ {
@@ -238,15 +238,10 @@ export const menus = {
name: '知识库', name: '知识库',
icon: <DatabaseOutlined/>, icon: <DatabaseOutlined/>,
}, },
{
path: '/ai/flowable',
name: '流程编排',
icon: <GatewayOutlined/>,
},
{ {
path: '1089caa6-9477-44a5-99f1-a9c179f6cfd3', path: '1089caa6-9477-44a5-99f1-a9c179f6cfd3',
name: '任务', name: '流程任务',
icon: <FileTextOutlined/>, icon: <GatewayOutlined/>,
routes: [ routes: [
{ {
path: '/ai/flow_task', path: '/ai/flow_task',
@@ -255,7 +250,7 @@ export const menus = {
}, },
{ {
path: '/ai/flow_task_template', path: '/ai/flow_task_template',
name: '任务模板', name: '流程模板',
icon: <FileTextOutlined/>, icon: <FileTextOutlined/>,
}, },
] ]

View File

@@ -1 +1,3 @@
/// <reference types="vite/client" /> /// <reference types="vite/client" />
declare const __APP_VERSION__: string

View File

@@ -1,10 +1,14 @@
import react from '@vitejs/plugin-react-swc' import react from '@vitejs/plugin-react-swc'
import {defineConfig, type UserConfig} from 'vite' import {defineConfig, type UserConfig} from 'vite'
import obfuscatorPlugin from 'vite-plugin-javascript-obfuscator' import obfuscatorPlugin from 'vite-plugin-javascript-obfuscator'
import packageJson from './package.json'
// https://vite.dev/config/ // https://vite.dev/config/
export default defineConfig(({mode}) => { export default defineConfig(({mode}) => {
let config: UserConfig = { let config: UserConfig = {
define: {
__APP_VERSION__: JSON.stringify(packageJson.version) ?? '0.0.0',
},
plugins: [ plugins: [
react(), react(),
obfuscatorPlugin({ obfuscatorPlugin({