Commit af0db988 by Archer Committed by GitHub

fix: form input icon store (#6891)

* fix: ts

* fix review

* fix: form input icon store

* perf: variables

* perf: workflow file upload

* fix: test

* fix: icon refresh

* add time in preview

* perf: fix review

* fix: file selector reference
parent 0f815cc2
# 工作流全局变量与文件变量统一管理方案
## 1. 背景
工作流里的文件变量有两种天然形态:
- 运行时需要 `string[]`,也就是节点可直接消费的文件 URL。
- 存储和回显需要稳定对象,例如 `{ key, name, type }` 或 `{ url, name, type }`。
之前用 `variables + storeVariables + fileMetaMap` 三套数据一起传递,导致 child/parent、变量更新、最终保存之间需要反复同步。尤其是 file 变量从 store object 转成 runtime URL 后,再保存时反推 object,容易出现 `name/type` 丢失、preview URL 被错误落库、base64 混入数据库等问题。
最终方案是:工作流内部只保留一个全局变量管理入口,由 `packages/service/core/workflow/dispatch/utils/variables.ts` 统一管理变量读取、写入、运行态转换和存储态输出。
这里的 `variables.ts` 是文件命名,不表示只处理 `userId/appId/chatId` 这类系统字段;它负责管理整个工作流的 `variables`。
## 2. 目标
1. `runWorkflow` 内部只传 `variableState`,不再传 `variables`、`storeVariables`、`fileMetaMap`。
2. 变量读取统一返回 runtime value,节点仍然按现有方式消费 file URL。
3. 变量更新统一写入 store value,并同步刷新 runtime value。
4. 工作流最终返回和变量更新 SSE 都只输出 store record。
5. file/password 特殊逻辑集中在 `utils/variables.ts`。
6. 前端 `FileSelector` 对外只输出可存储字段,不输出内部渲染字段。
## 3. 非目标
1. 不修改 MongoDB schema。
2. 不做历史数据迁移。
3. 不改变普通 ChatBox 消息文件的历史结构。
4. 不要求所有 workflow 节点都改成直接消费文件对象;运行时仍然消费 URL。
## 4. 核心类型
### 4.1 文件存储值
```ts
type ChatFileStoreValue =
| {
key: string;
name: string;
type: ChatFileTypeEnum;
}
| {
url: string;
name: string;
type: ChatFileTypeEnum;
};
```
规则:
- `key` 和 `url` 二选一。
- `key` 文件不保存 preview `url`。
- `url` 文件保存外链原始 URL。
- `name/type` 必须进入数据库。
- `id/rawFile/icon/status/process/error` 不进入数据库。
- `data:` URL 不允许落库。
- 未知外部 URL 的 `type` 推断失败时,兜底为 `ChatFileTypeEnum.file`。
### 4.2 文件运行值
```ts
type FileRuntimeValue = string[];
```
规则:
- `{ key, name, type }` 在运行前签发 preview URL。
- `{ url, name, type }` 在运行时直接使用 `url`。
- 运行时 URL 到 store file 的映射保存在 `WorkflowVariableState` 内部。
### 4.3 变量状态项
```ts
type WorkflowVariableStateItem = {
key: string;
config?: VariableItemType;
storeValue: unknown;
runtimeValue: unknown;
runtimeOnly?: boolean;
};
```
规则:
- `storeValue` 是唯一可持久化事实源。
- `runtimeValue` 是运行缓存。
- `runtimeOnly` 变量可读取,但不会进入 `toStoreRecord()`。
## 5. variables.ts 设计
`packages/service/core/workflow/dispatch/utils/variables.ts` 提供 `WorkflowVariableState`。
`WorkflowVariableState.create()` 完全取代原来的 `getWorkflowVariableState`。旧函数不再保留兼容层,所有调用点都直接创建并传递 `WorkflowVariableState`,不再返回或解构 `runtimeVariables/storeVariables/fileMetaMap`。
```ts
class WorkflowVariableState {
static create(props: WorkflowVariableStateCreateProps): Promise<WorkflowVariableState>;
get(key: string): unknown;
set(key: string, value: unknown): Promise<unknown>;
getStoreValue(key: string): unknown;
toRuntimeRecord(): Record<string, unknown>;
toStoreRecord(): Record<string, unknown>;
}
```
创建参数:
```ts
type WorkflowVariableStateCreateProps = {
timezone: string;
runningAppInfo: ChatDispatchProps['runningAppInfo'];
uid: ChatDispatchProps['uid'];
chatId: ChatDispatchProps['chatId'];
responseChatItemId?: ChatDispatchProps['responseChatItemId'];
histories?: ChatDispatchProps['histories'];
variablesConfig?: VariableItemType[];
inputVariables?: Record<string, unknown>;
externalVariables?: Record<string, unknown>;
runtimeOnlyVariables?: Record<string, unknown>;
sourceVariableState?: WorkflowVariableStateLike;
};
```
职责:
- 根据变量配置读取 `inputVariables` 和默认值。
- 初始化 file/password/普通变量的 store/runtime 值。
- 根据 `timezone/runningAppInfo/uid/chatId/responseChatItemId/histories` 内部生成系统 runtime-only 变量,例如 `userId/appId/chatId/histories/cTime`。
- 注入 `externalVariables`,作为 runtime-only 变量。
- 注入额外 `runtimeOnlyVariables`,用于少量调用点补充特殊运行时变量。
- 维护 runtime URL 到 `ChatFileStoreValue` 的内部映射。
- 提供 child app 从 parent runtime URL 恢复 store file 的能力。
优先级:
```ts
变量配置默认值 < inputVariables < externalVariables < runtimeOnlyVariables
```
`externalVariables` 和 `runtimeOnlyVariables` 不进入 `toStoreRecord()`。
## 6. 转换规则
### 6.1 file
初始化或更新 store object:
```ts
ChatFileStoreValue[] -> normalize -> storeValue -> sign/return url -> runtimeValue
```
更新 runtime URL:
```ts
string[] -> current metadata -> source metadata -> infer external url -> storeValue
```
规则:
- 优先从当前 state 的 metadata 恢复 `{ key, name, type }`。
- 当前 state 没有时,从 `sourceVariableState` 恢复。
- 都没有时,按未知外链保存 `{ url, name, type }`。
- `data:` URL 过滤。
- 非数组 file 更新值直接抛错。
### 6.2 password
初始化:
```ts
storeValue: { value: '', secret } -> runtimeValue: plain string
```
更新:
```ts
plain string -> storeValue: { value: '', secret } + runtimeValue: plain string
```
### 6.3 普通变量
普通变量按 `valueType` 格式化:
```ts
storeValue === runtimeValue
```
## 7. 工作流链路
### 7.1 root workflow
`dispatchWorkFlow` 创建 root `WorkflowVariableState`:
```ts
const variableState = await WorkflowVariableState.create({
timezone,
runningAppInfo,
uid: data.uid,
chatId,
responseChatItemId: data.responseChatItemId,
histories,
variablesConfig: data.chatConfig?.variables,
inputVariables: data.variables,
externalVariables: externalProvider.externalWorkflowVariables
});
```
`runWorkflow` 只接收:
```ts
variableState
```
### 7.2 变量读取
全局变量读取统一走:
```ts
variableState.get(key)
```
需要改造的读取入口:
- `getReferenceVariableValue`:只接收 runtime variables record,不直接依赖完整 `WorkflowVariableState`
- `replaceEditorVariable`:只接收 runtime variables record,不直接依赖完整 `WorkflowVariableState`
- `WorkflowQueue` 节点参数解析
- `runIfElse`
- `http468`
- `loopRun/service.ts`
- 其他所有工作流运行路径上的 `variables[key]`
### 7.3 变量更新
全局变量更新统一走:
```ts
await variableState.set(varKey, value)
```
`runUpdateVar` 不再手动维护:
```ts
variables[varKey] = value;
storeVariables[varKey] = value;
fileMetaMap.set(url, file);
```
非全局变量更新仍然写对应 node output。
### 7.4 child / plugin / agent 子应用
child workflow 创建自己的 `WorkflowVariableState`:
```ts
const childVariableState = await WorkflowVariableState.create({
timezone: props.timezone,
runningAppInfo: childRunningAppInfo,
uid: props.uid,
chatId: props.chatId,
responseChatItemId: props.responseChatItemId,
histories: childHistories,
variablesConfig: childChatConfig.variables,
inputVariables: childInputVariables,
externalVariables,
sourceVariableState: parentVariableState
});
```
如果 parent 传给 child 的 file 输入是 runtime URL,child 通过 `sourceVariableState` 恢复原始 store file。
### 7.5 工作流返回
工作流返回统一使用:
```ts
newVariables: variableState.toStoreRecord()
```
变量更新 SSE 也使用:
```ts
variableState.toStoreRecord()
```
节点内部 `DispatchNodeResultType` 不再透传 `newVariables`,避免 `nodeResponse` 或子运行结果里携带一份过期变量快照。变量更新后的事实源始终是同一个 `variableState`。
## 8. 前端与回显
`FileSelector` 内部可以保留渲染字段:
```ts
id
rawFile
icon
status
process
error
url // key 文件的临时 preview url
```
但 `onChange` 对外只输出:
```ts
{ key, name, type }
```
或:
```ts
{ url, name, type }
```
DB 读取返回前端时:
- `{ key, name, type }` 响应阶段补 preview `url`。
- `{ url, name, type }` 原样返回。
- 补出来的 preview `url` 只用于前端预览,不回写数据库。
## 9. 需要修改的文件
| 文件 | 修改点 |
|---|---|
| `packages/service/core/workflow/dispatch/utils/variables.ts` | 新增 `WorkflowVariableState`,统一管理工作流全局变量,并内聚 file normalize、store/runtime 转换、URL 推断工具 |
| `packages/service/core/workflow/dispatch/utils/index.ts` | 删除 `getWorkflowVariableState` 和旧变量转换逻辑,保留无关通用工具 |
| `packages/global/core/workflow/runtime/type.ts` | 增加 `WorkflowVariableStateLike`,移除 dispatch props 中的旧变量字段 |
| `packages/global/core/workflow/runtime/utils.ts` | `getReferenceVariableValue`、`replaceEditorVariable` 改成通过 runtime variables record 读取全局变量 |
| `packages/service/core/workflow/dispatch/index.ts` | root 初始化 `WorkflowVariableState`,`runWorkflow` 入参和返回改造 |
| `packages/service/core/workflow/dispatch/type.ts` | `RunWorkflowProps` 改为接收 `variableState` |
| `packages/service/core/workflow/dispatch/tools/runUpdateVar.ts` | 全局变量更新改成 `variableState.get/set` |
| `packages/service/core/workflow/dispatch/tools/runIfElse.ts` | 条件变量读取改成使用 `variableState.toRuntimeRecord()` |
| `packages/service/core/workflow/dispatch/tools/http468.ts` | HTTP 变量替换改成使用 runtime variables record |
| `packages/service/core/workflow/dispatch/loopRun/service.ts` | 循环变量引用改成使用 `variableState.toRuntimeRecord()` |
| `packages/service/core/workflow/dispatch/child/runApp.ts` | child workflow 创建自己的 `WorkflowVariableState` |
| `packages/service/core/workflow/dispatch/abandoned/runApp.ts` | 废弃 runApp 节点仍需创建独立 child `WorkflowVariableState`,不能复用 parent state |
| `packages/service/core/workflow/dispatch/plugin/run.ts` | 工具工作流创建自己的 `WorkflowVariableState` |
| `packages/service/core/workflow/dispatch/ai/agent/sub/app/index.ts` | agent 子应用创建自己的 `WorkflowVariableState` |
| `projects/app/src/components/core/app/FileSelector/*` | 对外值只输出 store value,内部渲染字段不外泄 |
| `packages/service/core/chat/utils.ts` | 返回前端时给 `{ key }` 文件补 preview `url` |
| `packages/service/core/chat/fileStoreValue.ts` | 统一文件存储值清洗,复用到工作流变量和交互表单保存 |
| `packages/service/core/chat/saveChat.ts` | TTL 续期从 store file object 提取 key;交互表单 `fileSelect` 保存前清洗为 store value |
## 10. TODO
### 10.1 基础实现
- [x] 实现 `WorkflowVariableStateLike` 类型。
- [x] 实现 `WorkflowVariableStateItem`、`WorkflowVariableStateCreateProps`,入参覆盖 `getWorkflowVariableState` 原本需要的 `timezone/runningAppInfo/uid/chatId/responseChatItemId/histories`。
- [x] 在 `utils/variables.ts` 实现 `WorkflowVariableState.create()`。
- [x] 用 `WorkflowVariableState.create()` 完全替换 `getWorkflowVariableState`。
- [x] 实现 `get()`、`set()`、`getStoreValue()`、`toRuntimeRecord()`、`toStoreRecord()`。
- [x] 在 `WorkflowVariableState` 内部维护 runtime URL metadata。
- [x] 支持从 `sourceVariableState` 恢复 parent file metadata。
### 10.2 file/password 处理
- [x] 整理 file store value normalize 逻辑。
- [x] 整理 file store value 到 runtime URL 的转换逻辑。
- [x] 整理 runtime URL 到 store value 的转换逻辑。
- [x] file 更新非数组时抛错。
- [x] `data:` URL 不落库。
- [x] 未知外链 URL 推断 `name/type`。
- [x] password 初始化解密、更新加密。
### 10.3 工作流主链路
- [x] 从 `ChatDispatchProps` / `RunWorkflowProps` 移除 `variables`。
- [x] 从 `ChatDispatchProps` / `RunWorkflowProps` 移除 `storeVariables`。
- [x] 从 `ChatDispatchProps` / `RunWorkflowProps` 移除 `fileMetaMap`。
- [x] 增加 `variableState` 入参。
- [x] root `dispatchWorkFlow` 创建 root `WorkflowVariableState`。
- [x] `child/runApp.ts`、`ai/agent/sub/app/index.ts` 等旧 `getWorkflowVariableState` 调用点全部迁移为 `WorkflowVariableState.create()`。
- [x] `runWorkflow` 所有返回分支使用 `variableState.toStoreRecord()`。
- [x] `updateVariables` SSE 使用 `variableState.toStoreRecord()`。
- [x] 移除内部节点结果里的 `newVariables`,仅保留 `runWorkflow` 最终对外返回。
### 10.4 变量读取改造
- [x] 改造 `getReferenceVariableValue`。
- [x] 改造 `replaceEditorVariable`。
- [x] 改造 `WorkflowQueue` 节点参数解析。
- [x] 改造 `runIfElse`。
- [x] 改造 `http468`。
- [x] 改造 `loopRun/service.ts`。
- [x] 全仓搜索并清理工作流运行路径上的旧 `variables` 读取。
### 10.5 变量更新改造
- [x] `runUpdateVar` 旧值读取改成 `variableState.get(varKey)`。
- [x] `runUpdateVar` 全局变量写入改成 `await variableState.set(varKey, value)`。
- [x] 删除 `updateFileVariableValue`。
- [x] 删除或收敛 `getStoreVariableValue`。
- [x] 确认 array append/clear、number operator、boolean mode 行为不变。
### 10.6 子工作流
- [x] `child/runApp.ts` 创建 child `WorkflowVariableState`。
- [x] `abandoned/runApp.ts` 创建 child `WorkflowVariableState`,避免复用 parent state。
- [x] `plugin/run.ts` 创建子工作流 `WorkflowVariableState`。
- [x] `ai/agent/sub/app/index.ts` 创建 child `WorkflowVariableState`。
- [x] child 创建时传入 `sourceVariableState`。
- [x] 确认 child 返回值不混入 parent runtime record。
### 10.7 前端和回显
- [x] `FileSelector` 对外值移除 `id/rawFile/icon/status/process/error`。
- [x] 全局变量、PluginRunBox、工具输入 `fileSelect` 使用同一套输出协议。
- [x] DB file `{ key }` 返回前端时补 preview `url`。
- [x] 刷新历史对话后图片 icon 能正常渲染。
- [x] 交互表单 `fileSelect` 回填历史前再次清洗,避免 base64、preview url、UI 状态字段落库。
### 10.8 清理
- [x] 移除 `runtimeSystemVar2StoreType`。
- [x] 移除 `formatStoreVariables`。
- [x] 移除 `getWorkflowVariableState`。
- [x] 移除 `storeVariables`、`fileMetaMap` 在 dispatch props 中的所有传递。
- [x] 清理临时 `console.log`。
- [x] 清理迁移产生的无意义 `any`。
- [x] 合并重复函数到 `utils/variables.ts`。
## 11. 测试计划
### 11.1 单元测试
| 测试文件 | 用例 |
|---|---|
| `packages/service/test/core/workflow/dispatch/variables.test.ts` | 初始化普通变量、password、file、runtime-only、external runtime-only |
| `packages/service/test/core/workflow/dispatch/variables.test.ts` | file `key -> runtime URL`、runtime URL 还原 key、未知外链推断、base64 过滤、非数组更新抛错 |
| `packages/service/test/core/workflow/dispatch/variables.test.ts` | 通过 `sourceVariableState` 恢复 parent file |
| `packages/global/test/core/workflow/runtime/utils.test.ts` | `getReferenceVariableValue`、`replaceEditorVariable` 通过 runtime variables record 获取全局变量 |
| `packages/service/test/core/workflow/dispatch/tools/runUpdateVar.test.ts` | 变量更新节点只写 `variableState.set()`,file/password/数组操作结果正确 |
| `projects/app/test/components/core/app/FileSelector/utils.test.ts` | FileSelector 清洗输出不含内部渲染字段 |
| `packages/service/test/core/chat/utils.test.ts` | DB file `{ key }` 返回前端时补 preview url |
| `packages/service/test/core/chat/saveChat.test.ts` | TTL 从 store file object 提取 key;交互表单 `fileSelect` 保存前过滤多余字段和 `data:` URL |
### 11.2 回归命令
```bash
cd packages/service && pnpm test test/core/workflow/dispatch/variables.test.ts
cd packages/service && pnpm test test/core/workflow/dispatch/tools/runUpdateVar.test.ts
cd packages/service && pnpm test test/core/workflow/dispatch/loopRun/runLoopRun.test.ts
cd projects/app && pnpm test test/components/core/app/FileSelector/utils.test.ts
```
最终合并前按实际改动范围补跑 workflow dispatch 相关测试。
### 11.3 本轮验证记录
已通过:
```bash
cd packages/global && pnpm test test/core/workflow/runtime/utils.test.ts
cd packages/service && pnpm test test/core/workflow/dispatch/variables.test.ts
cd packages/service && pnpm test test/core/workflow/dispatch/utils.test.ts
cd packages/service && pnpm test test/core/workflow/dispatch/tools/runUpdateVar.test.ts
cd packages/service && pnpm test test/core/workflow/dispatch/loopRun/runLoopRun.test.ts
cd projects/app && pnpm test test/components/core/app/FileSelector/utils.test.ts
```
补充检查:
- `packages/service` 的 `tsc --noEmit -p tsconfig.json` 已清掉本次工作流变量改造相关类型错误;该命令仍会命中仓库既有测试路径 alias 解析问题,例如 `@fastgpt/service/...` 测试导入无法解析。
- 已搜索确认 `runtimeSystemVar2StoreType`、`formatStoreVariables`、`getWorkflowVariableState`、`getStoreVariableValue`、`updateFileVariableValue` 不再存在。
......@@ -58,6 +58,11 @@ jobs:
ghcr.io/${{ github.repository_owner }}/fastgpt-pr:admin_${SHA}
docker push ghcr.io/${{ github.repository_owner }}/fastgpt-pr:admin_${SHA}
- name: Format preview timestamp
id: preview_time
run: |
echo "value=$(TZ='Asia/Shanghai' date '+%Y-%m-%d %H:%M:%S (UTC+8)')" >> "$GITHUB_OUTPUT"
- name: Add PR comment on success
if: success() && steps.pr.outputs.number != ''
uses: actions/github-script@v7
......@@ -82,6 +87,8 @@ jobs:
\`\`\`
ghcr.io/${{ github.repository_owner }}/fastgpt-pr:admin_${{ steps.pr.outputs.sha }}
\`\`\`
🕒 Time: ${{ steps.preview_time.outputs.value }}
`;
if (existingComment) {
......
......@@ -74,6 +74,11 @@ jobs:
kubectl --kubeconfig "$KUBECONFIG_FILE" annotate deployment/fastgpt-docs-preview \
originImageName="ghcr.io/${{ github.repository_owner }}/fastgpt-docs-pr:${{ steps.pr.outputs.sha }}" --overwrite
- name: Format preview timestamp
id: preview_time
run: |
echo "value=$(TZ='Asia/Shanghai' date '+%Y-%m-%d %H:%M:%S (UTC+8)')" >> "$GITHUB_OUTPUT"
- name: Add PR comment on success
if: success() && steps.pr.outputs.number != ''
uses: actions/github-script@v7
......@@ -100,6 +105,8 @@ jobs:
\`\`\`
ghcr.io/${{ github.repository_owner }}/fastgpt-docs-pr:${{ steps.pr.outputs.sha }}
\`\`\`
🕒 Time: ${{ steps.preview_time.outputs.value }}
`;
if (existingComment) {
......
......@@ -75,6 +75,11 @@ jobs:
ghcr.io/${{ github.repository_owner }}/fastgpt-pr:${{ matrix.image }}_${SHA}
docker push ghcr.io/${{ github.repository_owner }}/fastgpt-pr:${{ matrix.image }}_${SHA}
- name: Format preview timestamp
id: preview_time
run: |
echo "value=$(TZ='Asia/Shanghai' date '+%Y-%m-%d %H:%M:%S (UTC+8)')" >> "$GITHUB_OUTPUT"
- name: Add PR comment on success
if: success() && steps.pr.outputs.number != ''
uses: actions/github-script@v7
......@@ -99,6 +104,8 @@ jobs:
\`\`\`
ghcr.io/${{ github.repository_owner }}/fastgpt-pr:${{ matrix.image }}_${{ steps.pr.outputs.sha }}
\`\`\`
🕒 Time: ${{ steps.preview_time.outputs.value }}
`;
if (existingComment) {
......
......@@ -4,6 +4,7 @@ export const CreatePostPresignedUrlResponseSchema = z.object({
url: z.string().nonempty(),
key: z.string().nonempty(),
headers: z.record(z.string(), z.string()),
previewUrl: z.string().nonempty(),
maxSize: z.number().positive().optional() // bytes
});
export type CreatePostPresignedUrlResponseType = z.infer<
......
......@@ -61,11 +61,7 @@ export const valToStr = (val: any) => {
};
// replace {{variable}} to value
export function replaceVariable(
text: any,
obj: Record<string, string | number | undefined>,
depth = 0
) {
export function replaceVariable(text: any, obj: Record<string, any>, depth = 0) {
if (typeof text !== 'string') return text;
if (checkStrOversize(text)) {
throw new Error('Text length exceeds 100,000,000 characters.');
......
......@@ -146,6 +146,18 @@ export const UserChatItemFileItemSchema = z.object({
});
export type UserChatItemFileItemType = z.infer<typeof UserChatItemFileItemSchema>;
export type ChatFileStoreValue =
| {
key: string;
name: string;
type: ChatFileTypeEnum;
}
| {
url: string;
name: string;
type: ChatFileTypeEnum;
};
export const UserChatItemValueItemSchema = z.object({
planId: z.string().nullish(),
text: z
......
......@@ -26,7 +26,7 @@ import type {
} from '../template/system/interactive/type';
import { SearchDataResponseItemSchema } from '../../dataset/type';
import type { localeType } from '../../../common/i18n/type';
import { type UserChatItemValueItemType } from '../../chat/type';
import { type ChatFileStoreValue, type UserChatItemValueItemType } from '../../chat/type';
import { DatasetSearchModeEnum } from '../../dataset/constants';
import { ChatRoleEnum } from '../../chat/constants';
import z from 'zod';
......@@ -48,6 +48,16 @@ export type ExternalProviderType = {
externalWorkflowVariables?: Record<string, string>;
};
export type WorkflowVariableStateLike = {
get: (key: string) => unknown;
set: (key: string, value: unknown) => Promise<unknown>;
getStoreValue: (key: string) => unknown;
getFileStoreValueByRuntimeUrl: (url: string) => ChatFileStoreValue | undefined;
toRuntimeRecord: () => Record<string, unknown>;
toStoreRecord: () => Record<string, unknown>;
clone: () => WorkflowVariableStateLike;
};
/* workflow props */
export type ChatDispatchProps = {
res?: NextApiResponse;
......@@ -78,7 +88,7 @@ export type ChatDispatchProps = {
chatId: string;
responseChatItemId?: string;
histories: ChatItemMiniType[];
variables: Record<string, any>; // global variable
variableState: WorkflowVariableStateLike; // global variable state
query: UserChatItemValueItemType[]; // trigger query
chatConfig: AppSchemaType['chatConfig'];
lastInteractive?: WorkflowInteractiveResponseType; // last interactive response
......@@ -360,7 +370,6 @@ export type DispatchNodeResultType<T = {}, ERR = { [NodeOutputKeyEnum.errorText]
[DispatchNodeResponseKeyEnum.assistantResponses]?: AIChatItemValueItemType[]; // Assistant response(Store to db)
[DispatchNodeResponseKeyEnum.rewriteHistories]?: ChatItemMiniType[];
[DispatchNodeResponseKeyEnum.runTimes]?: number;
[DispatchNodeResponseKeyEnum.newVariables]?: Record<string, any>;
[DispatchNodeResponseKeyEnum.memories]?: Record<string, any>;
[DispatchNodeResponseKeyEnum.interactive]?: InteractiveNodeResponseType;
[DispatchNodeResponseKeyEnum.customFeedbacks]?: string[];
......
......@@ -301,7 +301,7 @@ export const getReferenceVariableValue = ({
}: {
value?: ReferenceValueType;
nodesMap: Record<string, RuntimeNodeItemType> | Map<string, RuntimeNodeItemType>;
variables: Record<string, any>;
variables: Record<string, unknown>;
}) => {
if (!value) return value;
......@@ -394,7 +394,7 @@ export function replaceEditorVariable({
}: {
text: any;
nodesMap: Record<string, RuntimeNodeItemType> | Map<string, RuntimeNodeItemType>;
variables: Record<string, any>; // global variables
variables: Record<string, unknown>; // runtime global variables
depth?: number;
}) {
const getNode = (nodeId: string) => {
......
......@@ -278,7 +278,10 @@ export const appData2FlowNodeIO = ({
[VariableInputEnum.timeRangeSelect]: [FlowNodeInputTypeEnum.timeRangeSelect],
[VariableInputEnum.switch]: [FlowNodeInputTypeEnum.switch],
[VariableInputEnum.password]: [FlowNodeInputTypeEnum.password],
[VariableInputEnum.file]: [FlowNodeInputTypeEnum.fileSelect],
[VariableInputEnum.file]: [
FlowNodeInputTypeEnum.fileSelect,
FlowNodeInputTypeEnum.reference
],
[VariableInputEnum.llmSelect]: [FlowNodeInputTypeEnum.selectLLMModel],
[VariableInputEnum.datasetSelect]: [FlowNodeInputTypeEnum.selectDataset],
[VariableInputEnum.internal]: [FlowNodeInputTypeEnum.hidden],
......
......@@ -2,13 +2,11 @@ import { PaginationResponseSchema } from '../../../api';
import { PaginationSchema } from '../../../api';
import {
HelperBotChatItemSiteSchema,
type HelperBotChatItemSiteType,
HelperBotTypeEnum,
HelperBotTypeEnumSchema
} from '../../../../core/chat/helperBot/type';
import { topAgentParamsSchema } from '../../../../core/chat/helperBot/topAgent/type';
import { z } from 'zod';
import type { PaginationResponse } from '../../../api';
import { ChatFileTypeEnum } from '../../../../core/chat/constants';
// 分页获取记录
......
......@@ -2,7 +2,6 @@ import { z } from 'zod';
import { ObjectIdSchema } from '../../../../common/type/mongo';
import { DatasetSourceReadTypeEnum } from '../../../../core/dataset/constants';
import { ChunkSettingsSchema } from '../../../../core/dataset/type';
import { CreatePostPresignedUrlResponseSchema } from '../../../../common/file/s3/type';
/* ============================================================================
* API: 预览文件分块
......@@ -69,10 +68,3 @@ export const PresignDatasetFilePostUrlBodySchema = z.object({
})
});
export type PresignDatasetFilePostUrlBody = z.infer<typeof PresignDatasetFilePostUrlBodySchema>;
export const PresignDatasetFilePostUrlResponseSchema = CreatePostPresignedUrlResponseSchema.meta({
description: 'S3 预签名上传 URL 及相关头信息'
});
export type PresignDatasetFilePostUrlResponse = z.infer<
typeof PresignDatasetFilePostUrlResponseSchema
>;
......@@ -3,9 +3,9 @@ import { TagsMap } from '../../../tag';
import {
GetPreviewChunksBodySchema,
GetPreviewChunksResponseSchema,
PresignDatasetFilePostUrlBodySchema,
PresignDatasetFilePostUrlResponseSchema
PresignDatasetFilePostUrlBodySchema
} from './api';
import { CreatePostPresignedUrlResponseSchema } from '../../../../common/file/s3/type';
export const DatasetFilePath: OpenAPIPath = {
'/core/dataset/file/getPreviewChunks': {
......@@ -49,7 +49,7 @@ export const DatasetFilePath: OpenAPIPath = {
description: '成功返回预签名上传 URL、key、请求头和最大文件大小',
content: {
'application/json': {
schema: PresignDatasetFilePostUrlResponseSchema
schema: CreatePostPresignedUrlResponseSchema
}
}
}
......
......@@ -8,7 +8,7 @@ import {
getWorkflowEntryNodeIds,
storeNodes2RuntimeNodes,
filterWorkflowEdges,
getReferenceVariableValue,
getReferenceVariableValue as baseGetReferenceVariableValue,
formatVariableValByType,
replaceEditorVariable,
textAdaptGptResponse,
......@@ -34,6 +34,17 @@ import type {
import type { StoreNodeItemType } from '@fastgpt/global/core/workflow/type/node';
import type { ChatItemMiniType } from '@fastgpt/global/core/chat/type';
const getReferenceVariableValue = ({
variables = {},
...props
}: Omit<Parameters<typeof baseGetReferenceVariableValue>[0], 'variables'> & {
variables?: Record<string, unknown>;
}) =>
baseGetReferenceVariableValue({
...props,
variables
});
describe('extractDeepestInteractive', () => {
it('should return the same interactive when no childrenResponse', () => {
const interactive = {
......
......@@ -735,7 +735,8 @@ describe('appData2FlowNodeIO', () => {
{ key: 'textVar', label: 'Text', type: VariableInputEnum.input, description: '' },
{ key: 'numVar', label: 'Number', type: VariableInputEnum.numberInput, description: '' },
{ key: 'selectVar', label: 'Select', type: VariableInputEnum.select, description: '' },
{ key: 'switchVar', label: 'Switch', type: VariableInputEnum.switch, description: '' }
{ key: 'switchVar', label: 'Switch', type: VariableInputEnum.switch, description: '' },
{ key: 'fileVar', label: 'File', type: VariableInputEnum.file, description: '' }
]
}
});
......@@ -751,6 +752,12 @@ describe('appData2FlowNodeIO', () => {
const switchVar = result.inputs.find((i) => i.key === 'switchVar');
expect(switchVar?.renderTypeList).toContain(FlowNodeInputTypeEnum.switch);
const fileVar = result.inputs.find((i) => i.key === 'fileVar');
expect(fileVar?.renderTypeList).toEqual([
FlowNodeInputTypeEnum.fileSelect,
FlowNodeInputTypeEnum.reference
]);
});
it('should map text input variable with non-string valueType to JSONEditor', () => {
......
import {
Client,
type RemoveOptions,
type CopyConditions,
S3Error,
InvalidObjectNameError,
InvalidXMLError
} from 'minio';
import { S3Error, InvalidObjectNameError, InvalidXMLError } from 'minio';
import {
type CreatePostPresignedUrlOptions,
type CreatePostPresignedUrlParams,
......@@ -186,6 +179,11 @@ export class S3BaseBucket {
});
}
const { url: previewUrl } = await this.createExternalUrl({
key: params.rawKey,
expiredHours
});
return {
url: jwtSignS3UploadToken({
objectKey: params.rawKey,
......@@ -199,6 +197,7 @@ export class S3BaseBucket {
headers: {
'content-type': resolvedUploadConstraints.defaultContentType
},
previewUrl,
maxSize: formatMaxFileSize
};
} catch (error) {
......
......@@ -58,6 +58,7 @@ export const CreatePostPresignedUrlResultSchema = z.object({
url: z.string().nonempty(),
key: z.string().nonempty(),
headers: z.record(z.string(), z.string()),
previewUrl: z.string().nonempty(),
maxSize: z.number().positive().optional()
});
export type CreatePostPresignedUrlResult = z.infer<typeof CreatePostPresignedUrlResultSchema>;
......
......@@ -127,3 +127,19 @@ export function getS3ChatSource() {
global.chatBucket = new S3ChatSource();
return global.chatBucket;
}
export const createChatFilePreviewUrlGetter = (options?: {
expiredHours?: number;
mode?: 'proxy' | 'presigned';
}) => {
const s3ChatSource = getS3ChatSource();
return async (key: string) => {
const { url } = await s3ChatSource.createGetChatFileURL({
key,
external: true,
...options
});
return url;
};
};
import { imageFileType } from '@fastgpt/global/common/file/constants';
import { ChatFileTypeEnum } from '@fastgpt/global/core/chat/constants';
import type { ChatFileStoreValue } from '@fastgpt/global/core/chat/type';
import path from 'path';
export type RawChatFileValue = {
key?: string;
url?: string;
name?: string;
type?: ChatFileTypeEnum;
};
type ChatFileInputFieldValue = string | number | boolean | object | null | undefined;
export type ChatFileValueInput = {
key?: string;
url?: string;
name?: string;
type?: ChatFileTypeEnum;
[key: string]: ChatFileInputFieldValue;
};
export type ChatFileRuntimeValueItem = string | RawChatFileValue;
export type ChatFileRuntimeValue = ChatFileRuntimeValueItem[];
/** 根据文件名扩展名判断是否按图片类型处理。 */
const isImageFilename = (filename?: string) => {
if (!filename) return false;
return imageFileType.includes(path.extname(filename).toLowerCase());
};
/** 从文件名推断聊天文件类型,无法识别时统一兜底为普通文件。 */
const inferChatFileType = (filename?: string): ChatFileTypeEnum =>
isImageFilename(filename) ? ChatFileTypeEnum.image : ChatFileTypeEnum.file;
/** 从 S3 object key 中提取稳定文件名。 */
const inferChatFileNameFromKey = (key: string) => path.basename(key) || 'file';
/** 从外部 URL pathname 中提取文件名,非法 URL 则保留原始字符串。 */
const inferChatFileNameFromUrl = (url: string) => {
try {
const urlObj = new URL(url);
return path.basename(decodeURIComponent(urlObj.pathname)) || url;
} catch {
return url;
}
};
/** 判断值是否是可解析的文件对象,数组和空值不参与文件存储清洗。 */
const isChatFileValueInput = (value: unknown): value is ChatFileValueInput =>
!!value &&
typeof value === 'object' &&
!Array.isArray(value) &&
value !== null &&
(typeof (value as ChatFileValueInput).key === 'string' ||
typeof (value as ChatFileValueInput).url === 'string' ||
(value as ChatFileValueInput).type === ChatFileTypeEnum.image ||
(value as ChatFileValueInput).type === ChatFileTypeEnum.file);
/** 从前端/历史文件对象中只读取文件存储需要的字段。 */
export const parseRawChatFileValue = (file: ChatFileValueInput): RawChatFileValue => {
return {
key: typeof file.key === 'string' ? file.key : undefined,
url: typeof file.url === 'string' ? file.url : undefined,
name: typeof file.name === 'string' ? file.name : undefined,
type:
file.type === ChatFileTypeEnum.image || file.type === ChatFileTypeEnum.file
? file.type
: undefined
};
};
/** 校验工作流文件运行值必须是数组,并保留 string URL 或可识别文件对象。 */
export const assertChatFileRuntimeValue = (
value: ChatFileRuntimeValueItem[]
): ChatFileRuntimeValue => {
if (!Array.isArray(value)) {
throw new Error('File variable value must be an array');
}
return value
.map((item) => {
if (typeof item === 'string') return item;
return isChatFileValueInput(item) ? parseRawChatFileValue(item) : undefined;
})
.filter((item): item is ChatFileRuntimeValueItem => Boolean(item));
};
/** 归一化单个文件存储值,确保 key/url 二选一且不会把 data URL 落库。 */
export const normalizeChatFileStoreValue = (
file: RawChatFileValue
): ChatFileStoreValue | undefined => {
const key = file.key || undefined;
const rawUrl = file.url || undefined;
const url = rawUrl && !rawUrl.startsWith('data:') ? rawUrl : undefined;
if (!key && !url) return;
const rawName = file.name || undefined;
const rawType = file.type;
if (key) {
const name = rawName || inferChatFileNameFromKey(key);
return {
key,
name,
type: rawType || inferChatFileType(name || key)
};
}
if (url) {
const name = rawName || inferChatFileNameFromUrl(url);
return {
url,
name,
type: rawType || inferChatFileType(name)
};
}
};
/** 批量归一化文件存储值,过滤非法项和前端渲染字段。 */
export const normalizeChatFileStoreValues = (
value: ChatFileValueInput[],
options?: { throwOnInvalid?: boolean }
): ChatFileStoreValue[] => {
if (!Array.isArray(value)) {
if (options?.throwOnInvalid) {
throw new Error('File variable value must be an array');
}
return [];
}
return value
.map((file) => {
if (!isChatFileValueInput(file)) return;
return normalizeChatFileStoreValue(parseRawChatFileValue(file));
})
.filter((file): file is ChatFileStoreValue => Boolean(file));
};
......@@ -37,6 +37,7 @@ import type { WorkflowInteractiveResponseType } from '@fastgpt/global/core/workf
import { getFlatAppResponses } from '@fastgpt/global/core/chat/utils';
import { getErrText } from '@fastgpt/global/common/error/utils';
import { getNanoid } from '@fastgpt/global/common/string/tools';
import { normalizeChatFileStoreValues } from './fileStoreValue';
export type Props = {
chatId: string;
......@@ -73,6 +74,11 @@ const beforeProcess = (props: Props) => {
// Remove url
stripUserContentFileUrls(props.userContent);
};
/** 是否是文件对象,且包含 key */
const isFileValueWithKey = (file: unknown): file is { key: string } =>
!!file && typeof file === 'object' && 'key' in file && typeof file.key === 'string' && !!file.key;
const afterProcess = async ({
contents,
variables,
......@@ -84,6 +90,8 @@ const afterProcess = async ({
variableList?: VariableItemType[];
session: ClientSession;
}) => {
// 移除 s3 ttl
{
const contentFileKeys = contents
.map((item) => {
if (item.value && Array.isArray(item.value)) {
......@@ -95,7 +103,7 @@ const afterProcess = async ({
keys.push(valueItem.file.key);
}
// 2. plugin input
// 2. query 是特殊格式的(工作流工具 + 表单输入)
if ('text' in valueItem && valueItem.text?.content) {
try {
const parsed = JSON.parse(valueItem.text.content);
......@@ -115,13 +123,8 @@ const afterProcess = async ({
else if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
Object.values(parsed).forEach((fieldValue) => {
if (Array.isArray(fieldValue)) {
fieldValue.forEach((file: any) => {
if (
file &&
typeof file === 'object' &&
file.key &&
typeof file.key === 'string'
) {
fieldValue.forEach((file) => {
if (isFileValueWithKey(file)) {
keys.push(file.key);
}
});
......@@ -145,7 +148,11 @@ const afterProcess = async ({
if (varItem.type === VariableInputEnum.file) {
const varValue = variables[varItem.key];
if (Array.isArray(varValue)) {
variableFileKeys.push(...varValue.map((item) => item.key));
variableFileKeys.push(
...varValue
.map((item) => (isFileValueWithKey(item) ? item.key : undefined))
.filter((key): key is string => typeof key === 'string' && !!key)
);
}
}
});
......@@ -156,6 +163,7 @@ const afterProcess = async ({
if (allFileKeys.length > 0) {
await removeS3TTL({ key: allFileKeys, bucketName: 'private', session });
}
}
};
const formatAiContent = ({
......@@ -963,6 +971,13 @@ export const updateInteractiveChat = async ({
};
}
if (item.type === FlowNodeInputTypeEnum.fileSelect) {
return {
...item,
value: normalizeChatFileStoreValues(itemValue)
};
}
return {
...item,
value: itemValue
......
import { ChatRoleEnum } from '@fastgpt/global/core/chat/constants';
import type { ChatItemMiniType } from '@fastgpt/global/core/chat/type';
import { getS3ChatSource } from '../../common/s3/sources/chat';
import type { ChatItemMiniType, UserChatItemFileItemType } from '@fastgpt/global/core/chat/type';
import { createChatFilePreviewUrlGetter } from '../../common/s3/sources/chat';
import type { FlowNodeInputItemType } from '@fastgpt/global/core/workflow/type/io';
import { FlowNodeInputTypeEnum } from '@fastgpt/global/core/workflow/node/constant';
import type { VariableItemType } from '@fastgpt/global/core/app/type';
import { VariableInputEnum } from '@fastgpt/global/core/workflow/constants';
import { cloneDeep } from 'lodash';
import type { WorkflowInteractiveResponseType } from '@fastgpt/global/core/workflow/template/system/interactive/type';
type ChatFileValueWithPreview = Partial<UserChatItemFileItemType>;
type RuntimeValue = string | number | boolean | object | null | undefined;
type RuntimeVariableMap = Record<string, RuntimeValue>;
type InteractiveWithChildrenResponse = WorkflowInteractiveResponseType & {
params: {
childrenResponse?: WorkflowInteractiveResponseType;
};
};
const formatFileValueList = (value: RuntimeValue): ChatFileValueWithPreview[] => {
if (!Array.isArray(value)) return [];
return value.filter(
(file): file is ChatFileValueWithPreview => !!file && typeof file === 'object'
);
};
const hasChildrenResponse = (
interactive: WorkflowInteractiveResponseType
): interactive is InteractiveWithChildrenResponse =>
!!interactive.params &&
'childrenResponse' in interactive.params &&
!!interactive.params.childrenResponse;
export const addPreviewUrlToChatItems = async (
histories: ChatItemMiniType[],
type: 'chatFlow' | 'workflowTool'
) => {
const getPreviewUrl = createChatFilePreviewUrlGetter();
async function addPreviewUrlToFileValue(files: ChatFileValueWithPreview[]) {
await Promise.all(
files.map(async (file) => {
if (!file || typeof file !== 'object') return;
if (!file.key) return;
file.url = await getPreviewUrl(file.key);
})
);
}
async function addToInteractive(interactive: WorkflowInteractiveResponseType) {
if (
(interactive.type === 'userInput' || interactive.type === 'agentPlanAskUserForm') &&
Array.isArray(interactive.params?.inputForm)
) {
await Promise.all(
interactive.params.inputForm.map(async (input) => {
if (input.type === FlowNodeInputTypeEnum.fileSelect) {
const files = formatFileValueList(input.value);
await addPreviewUrlToFileValue(files);
}
})
);
}
if (hasChildrenResponse(interactive)) {
await addToInteractive(interactive.params.childrenResponse);
}
}
async function addToChatflow(item: ChatItemMiniType) {
for await (const value of item.value) {
await Promise.all(
item.value.map(async (value) => {
if ('file' in value && value.file && value.file.key) {
const { url } = await s3ChatSource.createGetChatFileURL({
key: value.file.key,
external: true
});
value.file.url = url;
await addPreviewUrlToFileValue([value.file]);
}
if ('interactive' in value && value.interactive) {
await addToInteractive(value.interactive);
}
})
);
}
async function addToWorkflowTool(item: ChatItemMiniType) {
if (item.obj !== ChatRoleEnum.Human || !Array.isArray(item.value)) return;
for (let j = 0; j < item.value.length; j++) {
const value = item.value[j];
if (!('text' in value)) continue;
await Promise.all(
item.value.map(async (value, index) => {
if (!('text' in value)) return;
const inputValueString = value.text?.content || '';
const parsedInputValue = JSON.parse(inputValueString) as FlowNodeInputItemType[];
for (const input of parsedInputValue) {
if (
input.renderTypeList[0] !== FlowNodeInputTypeEnum.fileSelect ||
!Array.isArray(input.value)
)
continue;
for (const file of input.value) {
if (!file.key) continue;
const { url } = await getS3ChatSource().createGetChatFileURL({
key: file.key,
external: true
});
file.url = url;
}
await Promise.all(
parsedInputValue.map(async (input) => {
if (!input.renderTypeList?.includes(FlowNodeInputTypeEnum.fileSelect)) {
return;
}
const files = formatFileValueList(input.value);
await addPreviewUrlToFileValue(files);
})
);
item.value[j].text = {
item.value[index].text = {
...value.text,
content: JSON.stringify(parsedInputValue)
};
}
})
);
}
// Presign file urls
const s3ChatSource = getS3ChatSource();
for await (const item of histories) {
await Promise.all(
histories.map(async (item) => {
if (type === 'chatFlow') {
await addToChatflow(item);
} else if (type === 'workflowTool') {
await addToWorkflowTool(item);
}
}
})
);
};
// Presign variables file urls
......@@ -72,34 +127,31 @@ export const presignVariablesFileUrls = async ({
variables,
variableConfig
}: {
variables?: Record<string, any>;
variables?: RuntimeVariableMap;
variableConfig?: VariableItemType[];
}) => {
if (!variables || !variableConfig) return variables;
const cloneVars = cloneDeep(variables);
const cloneVars: RuntimeVariableMap = { ...variables };
const getPreviewUrl = createChatFilePreviewUrlGetter();
await Promise.all(
variableConfig.map(async (item) => {
if (item.type === VariableInputEnum.file) {
const val = cloneVars[item.key];
if (Array.isArray(val)) {
const files = formatFileValueList(variables[item.key]);
cloneVars[item.key] = await Promise.all(
val.map(async (item) => {
if (!item.key) return item;
const { url } = await getS3ChatSource().createGetChatFileURL({
key: item.key,
external: true
});
files.map(async (file) => {
if (!file.key) {
return file;
}
return {
...item,
url
...file,
url: await getPreviewUrl(file.key)
};
})
).then((urls) => urls.filter(Boolean));
}
}
})
);
......
......@@ -14,10 +14,12 @@ import {
import type { NodeInputKeyEnum, NodeOutputKeyEnum } from '@fastgpt/global/core/workflow/constants';
import { DispatchNodeResponseKeyEnum } from '@fastgpt/global/core/workflow/runtime/constants';
import { getHistories } from '../utils';
import { WorkflowVariableState } from '../utils/variables';
import { chatValue2RuntimePrompt, runtimePrompt2ChatsValue } from '@fastgpt/global/core/chat/adapt';
import { type DispatchNodeResultType } from '@fastgpt/global/core/workflow/runtime/type';
import { authAppByTmbId } from '../../../../support/permission/app/auth';
import { ReadPermissionVal } from '@fastgpt/global/support/permission/constant';
import { getUserChatInfo } from '../../../../support/user/team/utils';
type Props = ModuleDispatchProps<{
[NodeInputKeyEnum.userChatInput]: string;
......@@ -35,6 +37,7 @@ export const dispatchAppRequest = async (props: Props): Promise<Response> => {
workflowStreamResponse,
histories,
query,
variableState,
params: { userChatInput, history, app }
} = props;
......@@ -58,26 +61,42 @@ export const dispatchAppRequest = async (props: Props): Promise<Response> => {
const chatHistories = getHistories(history, histories);
const { files } = chatValue2RuntimePrompt(query);
const { flowResponses, flowUsages, assistantResponses, system_memories } = await runWorkflow({
...props,
runningAppInfo: {
const childRunningAppInfo = {
id: String(appData._id),
name: appData.name,
teamId: String(appData.teamId),
tmbId: String(appData.tmbId)
},
tmbId: String(appData.tmbId),
isChildApp: true
};
const { externalProvider } = await getUserChatInfo(appData.tmbId);
const childVariableState = await WorkflowVariableState.create({
timezone: props.timezone,
runningAppInfo: childRunningAppInfo,
uid: props.uid,
chatId: props.chatId,
responseChatItemId: props.responseChatItemId,
histories: chatHistories,
variablesConfig: appData.chatConfig?.variables,
inputVariables: variableState.toStoreRecord(),
externalVariables: externalProvider?.externalWorkflowVariables,
sourceVariableState: variableState
});
const { flowResponses, flowUsages, assistantResponses, system_memories } = await runWorkflow({
...props,
runningAppInfo: childRunningAppInfo,
runtimeNodes: storeNodes2RuntimeNodes(
appData.modules,
getWorkflowEntryNodeIds(appData.modules)
),
runtimeEdges: storeEdges2RuntimeEdges(appData.edges),
variableState: childVariableState,
chatConfig: appData.chatConfig,
histories: chatHistories,
query: runtimePrompt2ChatsValue({
files,
text: userChatInput
}),
variables: props.variables
})
});
const completeMessages = chatHistories.concat([
......
......@@ -56,7 +56,6 @@ export const dispatchLoop = async (props: Props): Promise<Response> => {
let assistantResponses: AIChatItemValueItemType[] = [];
const customFeedbacks: string[] = [];
let totalPoints = 0;
let newVariables: Record<string, any> = props.variables;
let interactiveResponse: WorkflowInteractiveResponseType | undefined = undefined;
let index = 0;
......@@ -89,7 +88,6 @@ export const dispatchLoop = async (props: Props): Promise<Response> => {
const response = await runWorkflow({
...props,
lastInteractive: interactiveData?.childrenResponse,
variables: newVariables,
runtimeNodes,
runtimeEdges: cloneDeep(
storeEdges2RuntimeEdges(runtimeEdges, interactiveData?.childrenResponse)
......@@ -112,12 +110,6 @@ export const dispatchLoop = async (props: Props): Promise<Response> => {
collectResponseFeedbacks(response, customFeedbacks);
// Concat new variables
newVariables = {
...newVariables,
...response.newVariables
};
// handle interactive response
if (response.workflowInteractiveResponse) {
interactiveResponse = response.workflowInteractiveResponse;
......@@ -151,7 +143,6 @@ export const dispatchLoop = async (props: Props): Promise<Response> => {
loopDetail: loopResponseDetail,
mergeSignId: props.node.nodeId
},
[DispatchNodeResponseKeyEnum.newVariables]: newVariables,
[DispatchNodeResponseKeyEnum.customFeedbacks]:
customFeedbacks.length > 0 ? customFeedbacks : undefined
};
......
......@@ -80,7 +80,6 @@ export const masterCall = async ({
runningAppInfo,
chatId,
uid,
variables,
externalProvider,
stream,
workflowStreamResponse,
......
......@@ -19,6 +19,7 @@ import { serverGetWorkflowToolRunUserQuery } from '../../../../../../app/tool/wo
import { getWorkflowToolInputsFromStoreNodes } from '@fastgpt/global/core/app/tool/workflowTool/utils';
import type { RunWorkflowProps } from '../../../../../../../core/workflow/dispatch';
import { anyValueDecrypt } from '../../../../../../../common/secret/utils';
import { WorkflowVariableState } from '../../../../utils/variables';
type Props = Pick<
RunWorkflowProps,
......@@ -28,6 +29,9 @@ type Props = Pick<
| 'mode'
| 'timezone'
| 'externalProvider'
| 'uid'
| 'chatId'
| 'responseChatItemId'
| 'runningAppInfo'
| 'runningUserInfo'
| 'retainDatasetCite'
......@@ -35,7 +39,7 @@ type Props = Pick<
| 'workflowDispatchDeep'
| 'responseAllData'
| 'responseDetail'
| 'variables'
| 'variableState'
> & {
app: {
name: string;
......@@ -51,7 +55,7 @@ export const dispatchApp = async (props: Props): Promise<DispatchSubAppResponse>
runningAppInfo,
runningUserInfo,
app,
variables,
variableState,
customAppVariables,
userChatInput,
...data
......@@ -70,16 +74,25 @@ export const dispatchApp = async (props: Props): Promise<DispatchSubAppResponse>
// Rewrite children app variables
const { externalProvider } = await getUserChatInfo(appData.tmbId);
const childrenRunVariables = {
userId: variables.userId,
appId: String(appData._id),
chatId: variables.chatId,
responseChatItemId: variables.responseChatItemId,
histories: [],
cTime: variables.cTime,
...customAppVariables,
...(externalProvider ? externalProvider.externalWorkflowVariables : {})
const childRunningAppInfo = {
id: String(appData._id),
teamId: String(appData.teamId),
tmbId: String(appData.tmbId),
name: appData.name,
isChildApp: true
};
const childrenVariableState = await WorkflowVariableState.create({
timezone: data.timezone,
runningAppInfo: childRunningAppInfo,
chatId: data.chatId,
responseChatItemId: data.responseChatItemId,
histories: [],
uid: data.uid,
variablesConfig: chatConfig.variables,
inputVariables: customAppVariables,
externalVariables: externalProvider?.externalWorkflowVariables,
sourceVariableState: variableState
});
const runtimeNodes = rewriteNodeOutputByHistories(
storeNodes2RuntimeNodes(nodes, getWorkflowEntryNodeIds(nodes))
......@@ -88,9 +101,6 @@ export const dispatchApp = async (props: Props): Promise<DispatchSubAppResponse>
const { assistantResponses, flowUsages } = await runWorkflow({
...data,
uid: variables.userId,
chatId: variables.chatId,
responseChatItemId: variables.responseChatItemId,
runningAppInfo: {
id: String(appData._id),
name: appData.name,
......@@ -103,7 +113,7 @@ export const dispatchApp = async (props: Props): Promise<DispatchSubAppResponse>
runtimeEdges,
chatConfig,
histories: [],
variables: childrenRunVariables,
variableState: childrenVariableState,
query: [
{
text: {
......@@ -138,7 +148,7 @@ export const dispatchPlugin = async (props: Props): Promise<DispatchSubAppRespon
runningAppInfo,
runningUserInfo,
app,
variables,
variableState,
customAppVariables,
userChatInput,
...data
......@@ -157,16 +167,26 @@ export const dispatchPlugin = async (props: Props): Promise<DispatchSubAppRespon
// Rewrite children app variables
const { externalProvider } = await getUserChatInfo(appData.tmbId);
const childrenRunVariables: Record<string, any> = {
userId: variables.userId,
appId: String(appData._id),
chatId: variables.chatId,
responseChatItemId: variables.responseChatItemId,
histories: [],
cTime: variables.cTime,
...customAppVariables,
...(externalProvider ? externalProvider.externalWorkflowVariables : {})
const childRunningAppInfo = {
id: String(appData._id),
teamId: String(appData.teamId || runningAppInfo.teamId),
tmbId: String(appData.tmbId || runningAppInfo.tmbId),
name: appData.name,
isChildApp: true
};
const childrenVariableState = await WorkflowVariableState.create({
timezone: data.timezone,
runningAppInfo: childRunningAppInfo,
chatId: data.chatId,
responseChatItemId: data.responseChatItemId,
histories: [],
uid: data.uid,
variablesConfig: chatConfig.variables,
inputVariables: customAppVariables,
externalVariables: externalProvider?.externalWorkflowVariables,
sourceVariableState: variableState
});
const childrenRunVariables = childrenVariableState.toRuntimeRecord();
const runtimeNodes = storeNodes2RuntimeNodes(nodes, getWorkflowEntryNodeIds(nodes)).map(
(node) => {
// Update plugin input value
......@@ -213,9 +233,6 @@ export const dispatchPlugin = async (props: Props): Promise<DispatchSubAppRespon
const { flowResponses, flowUsages, runTimes } = await runWorkflow({
...data,
uid: variables.userId,
chatId: variables.chatId,
responseChatItemId: variables.responseChatItemId,
runningAppInfo: {
id: String(appData._id),
// 如果系统插件有 teamId 和 tmbId,则使用系统插件的 teamId 和 tmbId(管理员指定了插件作为系统插件)
......@@ -229,7 +246,7 @@ export const dispatchPlugin = async (props: Props): Promise<DispatchSubAppRespon
runtimeEdges,
chatConfig,
histories: [],
variables: childrenRunVariables,
variableState: childrenVariableState,
query: serverGetWorkflowToolRunUserQuery({
pluginInputs: getWorkflowToolInputsFromStoreNodes(nodes),
variables: childrenRunVariables
......
......@@ -43,7 +43,7 @@ export type Props = {
runningAppInfo: ChatDispatchProps['runningAppInfo'];
chatId: ChatDispatchProps['chatId'];
uid: ChatDispatchProps['uid'];
variables: ChatDispatchProps['variables'];
variableState: ChatDispatchProps['variableState'];
workflowStreamResponse: ChatDispatchProps['workflowStreamResponse'];
};
......@@ -54,7 +54,7 @@ export const dispatchTool = async ({
runningAppInfo,
chatId,
uid,
variables,
variableState,
workflowStreamResponse
}: Props): Promise<DispatchSubAppResponse> => {
const getNodeResponse = ({
......@@ -115,7 +115,7 @@ export const dispatchTool = async ({
inputs,
systemVar: {
user: {
id: variables.userId,
id: uid,
username: runningUserInfo.username,
contact: runningUserInfo.contact,
membername: runningUserInfo.memberName,
......@@ -136,7 +136,7 @@ export const dispatchTool = async ({
uId: uid
})
},
time: variables.cTime
time: String(variableState.get('cTime') ?? '')
},
onMessage: ({ type, content }) => {
if (workflowStreamResponse && content) {
......
......@@ -111,7 +111,7 @@ export type ToolDispatchContext = Pick<
| 'runningAppInfo'
| 'chatId'
| 'uid'
| 'variables'
| 'variableState'
| 'externalProvider'
| 'lang'
| 'requestOrigin'
......@@ -144,7 +144,7 @@ export const getExecuteTool = ({
runningAppInfo,
chatId,
uid,
variables,
variableState,
externalProvider,
stream,
streamResponseFn,
......@@ -330,7 +330,7 @@ export const getExecuteTool = ({
runningAppInfo,
chatId,
uid,
variables,
variableState,
workflowStreamResponse: streamResponseFn
});
......@@ -356,12 +356,14 @@ export const getExecuteTool = ({
mode,
timezone,
externalProvider,
chatId,
uid,
runningAppInfo,
runningUserInfo,
retainDatasetCite,
maxRunTimes,
workflowDispatchDeep,
variables
variableState
});
return {
......@@ -384,12 +386,14 @@ export const getExecuteTool = ({
mode,
timezone,
externalProvider,
chatId,
uid,
runningAppInfo,
runningUserInfo,
retainDatasetCite,
maxRunTimes,
workflowDispatchDeep,
variables
variableState
});
return {
......
......@@ -13,7 +13,8 @@ import {
import type { NodeInputKeyEnum } from '@fastgpt/global/core/workflow/constants';
import { NodeOutputKeyEnum } from '@fastgpt/global/core/workflow/constants';
import { DispatchNodeResponseKeyEnum } from '@fastgpt/global/core/workflow/runtime/constants';
import { getSystemVariables, getNodeErrResponse, getHistories } from '../utils';
import { getNodeErrResponse, getHistories } from '../utils';
import { WorkflowVariableState } from '../utils/variables';
import { chatValue2RuntimePrompt, runtimePrompt2ChatsValue } from '@fastgpt/global/core/chat/adapt';
import { type DispatchNodeResultType } from '@fastgpt/global/core/workflow/runtime/type';
import { authAppByTmbId } from '../../../../support/permission/app/auth';
......@@ -44,7 +45,7 @@ export const dispatchRunAppNode = async (props: Props): Promise<Response> => {
node: { pluginId: appId, version },
workflowStreamResponse,
params,
variables
variableState
} = props;
const {
......@@ -101,24 +102,25 @@ export const dispatchRunAppNode = async (props: Props): Promise<Response> => {
// Rewrite children app variables
const { externalProvider } = await getUserChatInfo(appData.tmbId);
const childrenRunVariables = {
...(await getSystemVariables({
timezone: props.timezone,
runningAppInfo: {
const childRunningAppInfo = {
id: String(appData._id),
teamId: appData.teamId,
tmbId: appData.tmbId,
name: appData.name
},
name: appData.name,
isChildApp: true
};
const childrenVariableState = await WorkflowVariableState.create({
timezone: props.timezone,
runningAppInfo: childRunningAppInfo,
chatId: props.chatId,
responseChatItemId: props.responseChatItemId,
histories: chatHistories,
uid: props.uid,
chatConfig,
variables: childrenAppVariables
})),
...(externalProvider ? externalProvider.externalWorkflowVariables : {})
};
variablesConfig: chatConfig.variables,
inputVariables: childrenAppVariables,
externalVariables: externalProvider?.externalWorkflowVariables,
sourceVariableState: variableState
});
const childrenInteractive =
lastInteractive?.type === 'childrenInteractive'
......@@ -166,7 +168,7 @@ export const dispatchRunAppNode = async (props: Props): Promise<Response> => {
runtimeNodes,
runtimeEdges,
histories: chatHistories,
variables: childrenRunVariables,
variableState: childrenVariableState,
query: theQuery,
chatConfig
});
......
......@@ -48,10 +48,11 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo
params,
runningUserInfo,
runningAppInfo,
variables,
variableState,
workflowStreamResponse,
node: { name, avatar, toolConfig, version, catchError }
} = props;
const cTime = String(variableState.get('cTime') ?? '');
const {
uid: uId,
......@@ -101,7 +102,7 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo
inputs,
systemVar: {
user: {
id: variables.userId,
id: props.uid,
username: runningUserInfo.username,
contact: runningUserInfo.contact,
membername: runningUserInfo.memberName,
......@@ -118,7 +119,7 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo
version: version || tool.versionList?.[0]?.value || '',
prefix: getS3ChatSource().getToolFilePrefix({ appId, chatId, uId })
},
time: variables.cTime
time: cTime
},
onMessage: ({ type, content }) => {
if (workflowStreamResponse && content) {
......
......@@ -44,12 +44,8 @@ import type { ChatNodeUsageType } from '@fastgpt/global/support/wallet/bill/type
import { getLogger, LogCategories } from '../../../common/logger';
import { surrenderProcess } from '../../../common/system/tools';
import type { DispatchFlowResponse, WorkflowDebugResponse } from './type';
import {
rewriteRuntimeWorkFlow,
runtimeSystemVar2StoreType,
filterOrphanEdges,
getSystemVariables
} from './utils';
import { rewriteRuntimeWorkFlow, filterOrphanEdges } from './utils';
import { WorkflowVariableState } from './utils/variables';
import { getHandleId } from '@fastgpt/global/core/workflow/utils';
import { callbackMap } from './constants';
import { getUserChatInfo } from '../../../support/user/team/utils';
......@@ -57,7 +53,7 @@ import { checkTeamAIPoints } from '../../../support/permission/teamLimit';
import type { UsageSourceEnum } from '@fastgpt/global/support/wallet/usage/constants';
import { createChatUsageRecord, pushChatItemUsage } from '../../../support/wallet/usage/controller';
import type { RequireOnlyOne } from '@fastgpt/global/common/type/utils';
import { getS3ChatSource } from '../../../common/s3/sources/chat';
import { createChatFilePreviewUrlGetter } from '../../../common/s3/sources/chat';
import { addPreviewUrlToChatItems } from '../../chat/utils';
import { TeamErrEnum } from '@fastgpt/global/common/error/code/team';
import { i18nT } from '../../../../web/i18n/utils';
......@@ -72,8 +68,9 @@ const logger = getLogger(LogCategories.MODULE.WORKFLOW.DISPATCH);
type Props = Omit<
ChatDispatchProps,
'checkIsStopping' | 'workflowDispatchDeep' | 'timezone' | 'externalProvider'
'checkIsStopping' | 'workflowDispatchDeep' | 'timezone' | 'externalProvider' | 'variableState'
> & {
variables: Record<string, any>;
runtimeNodes: RuntimeNodeItemType[];
runtimeEdges: RuntimeEdgeItemType[];
defaultSkipNodeQueue?: WorkflowDebugResponse['skipNodeQueue'];
......@@ -188,6 +185,8 @@ export async function dispatchWorkFlow({
// Check point
await checkTeamAIPoints(runningUserInfo.teamId);
const getPreviewUrl = createChatFilePreviewUrlGetter();
const [{ timezone, externalProvider }, newUsageId] = await Promise.all([
getUserChatInfo(runningUserInfo.tmbId),
(() => {
......@@ -206,15 +205,11 @@ export async function dispatchWorkFlow({
return usageId;
})(),
// Add preview url to chat items
await addPreviewUrlToChatItems(histories, 'chatFlow'),
addPreviewUrlToChatItems(histories, 'chatFlow'),
// Add preview url to query
...query.map(async (item) => {
if (!item.file?.key) return;
const { url } = await getS3ChatSource().createGetChatFileURL({
key: item.file.key,
external: true
});
item.file.url = url;
item.file.url = await getPreviewUrl(item.file.key);
}),
// Remove stopping sign
delAgentRuntimeStopSign({
......@@ -252,20 +247,17 @@ export async function dispatchWorkFlow({
}
}
// Get default variables
const defaultVariables = {
...externalProvider.externalWorkflowVariables,
...(await getSystemVariables({
runningAppInfo: runningAppInfo,
chatId: chatId,
responseChatItemId: data.responseChatItemId,
histories: histories,
const variableState = await WorkflowVariableState.create({
timezone,
runningAppInfo,
uid: data.uid,
chatConfig: data.chatConfig,
variables: data.variables,
timezone: timezone
}))
};
chatId,
responseChatItemId: data.responseChatItemId,
histories,
variablesConfig: data.chatConfig?.variables,
inputVariables: data.variables,
externalVariables: externalProvider.externalWorkflowVariables
});
// Stop sign(没有 apiVersion,说明不会有暂停)
let stopping = false;
......@@ -309,7 +301,7 @@ export async function dispatchWorkFlow({
histories,
timezone,
externalProvider,
variables: defaultVariables,
variableState,
workflowDispatchDeep: 0,
usageId: newUsageId,
concatUsage
......@@ -838,6 +830,7 @@ export class WorkflowQueue {
}
: {};
const runtimeVariables = this.data.variableState.toRuntimeRecord();
node.inputs.forEach((input) => {
// Special input, not format
if (input.key === dynamicInput?.key) return;
......@@ -856,14 +849,14 @@ export class WorkflowQueue {
let value = replaceEditorVariable({
text: input.value,
nodesMap: this.runtimeNodesMap,
variables: this.data.variables
variables: runtimeVariables
});
// replace reference variables
value = getReferenceVariableValue({
value,
nodesMap: this.runtimeNodesMap,
variables: this.data.variables
variables: runtimeVariables
});
// Dynamic input is stored in the dynamic key
......@@ -897,7 +890,6 @@ export class WorkflowQueue {
lastInteractive: this.data.lastInteractive?.entryNodeIds?.includes(node.nodeId)
? this.data.lastInteractive
: undefined,
variables: this.data.variables,
histories: this.data.histories,
retainDatasetCite: this.data.retainDatasetCite,
node,
......@@ -1035,14 +1027,6 @@ export class WorkflowQueue {
});
}
// Update new variables
if (dispatchRes[DispatchNodeResponseKeyEnum.newVariables]) {
this.data.variables = {
...this.data.variables,
...dispatchRes[DispatchNodeResponseKeyEnum.newVariables]
};
}
// Error
if (dispatchRes?.responseData?.error) {
if (stepSpan) {
......@@ -1519,11 +1503,7 @@ export const runWorkflow = async (data: RunWorkflowProps): Promise<DispatchFlowR
[DispatchNodeResponseKeyEnum.runTimes]: 1,
[DispatchNodeResponseKeyEnum.assistantResponses]: [],
[DispatchNodeResponseKeyEnum.toolResponses]: null,
[DispatchNodeResponseKeyEnum.newVariables]: runtimeSystemVar2StoreType({
variables: data.variables,
removeObj: data.externalProvider.externalWorkflowVariables,
userVariablesConfigs: data.chatConfig?.variables
}),
[DispatchNodeResponseKeyEnum.newVariables]: data.variableState.toStoreRecord(),
durationSeconds: 0
};
}
......@@ -1639,11 +1619,7 @@ export const runWorkflow = async (data: RunWorkflowProps): Promise<DispatchFlowR
workflowQueue.chatAssistantResponse
),
[DispatchNodeResponseKeyEnum.toolResponses]: workflowQueue.toolRunResponse,
[DispatchNodeResponseKeyEnum.newVariables]: runtimeSystemVar2StoreType({
variables: data.variables,
removeObj: data.externalProvider.externalWorkflowVariables,
userVariablesConfigs: data.chatConfig?.variables
}),
[DispatchNodeResponseKeyEnum.newVariables]: data.variableState.toStoreRecord(),
[DispatchNodeResponseKeyEnum.memories]:
Object.keys(workflowQueue.system_memories).length > 0
? workflowQueue.system_memories
......
export const dispatchSystemConfig = (props: Record<string, any>) => {
const { variables } = props;
return variables;
return props.variableState.toRuntimeRecord();
};
......@@ -17,7 +17,7 @@ type Response = DispatchNodeResultType<{
export const dispatchWorkflowStart = async (props: Record<string, any>): Promise<Response> => {
const {
query,
variables,
variableState,
params: { userChatInput }
} = props as UserChatInputProps;
......@@ -28,9 +28,8 @@ export const dispatchWorkflowStart = async (props: Record<string, any>): Promise
return item?.url ?? '';
})
.filter(Boolean);
const variablesFiles: string[] = Array.isArray(variables?.fileUrlList)
? variables.fileUrlList
: [];
const fileUrlList = variableState.get('fileUrlList');
const variablesFiles: string[] = Array.isArray(fileUrlList) ? fileUrlList : [];
return {
[DispatchNodeResponseKeyEnum.nodeResponse]: {},
......
......@@ -10,6 +10,7 @@ import type { UserInputFormItemType } from '@fastgpt/global/core/workflow/templa
import { FlowNodeInputTypeEnum } from '@fastgpt/global/core/workflow/node/constant';
import { anyValueDecrypt } from '../../../../common/secret/utils';
import { getLogger, LogCategories } from '../../../../common/logger';
import { createChatFilePreviewUrlGetter } from '../../../../common/s3/sources/chat';
const logger = getLogger(LogCategories.MODULE.WORKFLOW.INTERACTIVE);
......@@ -17,11 +18,36 @@ type Props = ModuleDispatchProps<{
[NodeInputKeyEnum.description]: string;
[NodeInputKeyEnum.userInputForms]: UserInputFormItemType[];
}>;
type FormInputValueMap = Record<string, unknown>;
type FormInputResponse = DispatchNodeResultType<{
[NodeOutputKeyEnum.formInputResult]?: Record<string, any>;
[key: string]: any;
[NodeOutputKeyEnum.formInputResult]?: FormInputValueMap;
[key: string]: unknown;
}>;
const isFileSelectObject = (value: unknown): value is { key?: unknown; url?: unknown } =>
!!value && typeof value === 'object' && !Array.isArray(value);
const formatFileSelectRuntimeValue = async (
value: unknown,
getPreviewUrl: (key: string) => Promise<string>
) => {
if (!Array.isArray(value)) return value;
const urls = await Promise.all(
value.map(async (file) => {
if (typeof file === 'string') return file;
if (!isFileSelectObject(file)) return;
if (typeof file.url === 'string' && file.url) return file.url;
if (typeof file.key !== 'string' || !file.key) return;
return getPreviewUrl(file.key);
})
);
return urls.filter((url): url is string => typeof url === 'string' && !!url);
};
/*
用户输入都内容,将会以 JSON 字符串格式进入工作流,可以从 query 的 text 中获取。
*/
......@@ -51,7 +77,7 @@ export const dispatchFormInput = async (props: Props): Promise<FormInputResponse
node.isEntry = false;
const { text } = chatValue2RuntimePrompt(query);
const rawUserInputVal: Record<string, any> = (() => {
const rawUserInputVal: FormInputValueMap = (() => {
try {
return JSON.parse(text);
} catch (error) {
......@@ -60,31 +86,22 @@ export const dispatchFormInput = async (props: Props): Promise<FormInputResponse
}
})();
const userInputVal = Object.entries(rawUserInputVal).reduce(
(acc, [key, value]) => {
const inputConfig = userInputForms.find((form) => form.key === key);
const getPreviewUrl = createChatFilePreviewUrlGetter({ expiredHours: 1 });
const inputConfigMap = new Map(userInputForms.map((form) => [form.key, form]));
const userInputEntries = await Promise.all(
Object.entries(rawUserInputVal).map(async ([key, value]) => {
const inputConfig = inputConfigMap.get(key);
if (inputConfig?.type === FlowNodeInputTypeEnum.password) {
acc[key] = anyValueDecrypt(value);
} else if (inputConfig?.type === FlowNodeInputTypeEnum.fileSelect) {
if (Array.isArray(value)) {
acc[key] = value.map((file: any) => {
if (typeof file === 'object' && file.url) {
return file.url;
}
return file;
});
} else {
acc[key] = value;
return [key, anyValueDecrypt(value)] as const;
}
} else {
acc[key] = value;
if (inputConfig?.type === FlowNodeInputTypeEnum.fileSelect) {
return [key, await formatFileSelectRuntimeValue(value, getPreviewUrl)] as const;
}
return acc;
},
{} as Record<string, any>
return [key, value] as const;
})
);
const userInputVal = Object.fromEntries(userInputEntries) as FormInputValueMap;
return {
data: {
......
......@@ -104,7 +104,6 @@ export const dispatchLoopRun = async (props: Props): Promise<Response> => {
const assistantResponses: AIChatItemValueItemType[] = [];
const customFeedbacks: string[] = [];
let totalPoints = 0;
let newVariables: Record<string, any> = props.variables;
let interactiveResponse: WorkflowInteractiveResponseType | undefined;
// Pre-interrupt children of the in-flight iteration survive across resume here,
// so pushIterationDetail can stitch them back with the resumed iteration's
......@@ -163,7 +162,6 @@ export const dispatchLoopRun = async (props: Props): Promise<Response> => {
const response = await runWorkflow({
...props,
lastInteractive: interactiveData?.childrenResponse,
variables: newVariables,
runtimeNodes: isolatedNodes,
runtimeEdges: cloneDeep(
storeEdges2RuntimeEdges(isolatedEdges, interactiveData?.childrenResponse)
......@@ -190,7 +188,6 @@ export const dispatchLoopRun = async (props: Props): Promise<Response> => {
});
totalPoints += iterationTotalPoints;
collectResponseFeedbacks(response, customFeedbacks);
newVariables = { ...newVariables, ...response.newVariables };
// Pause: stash accumulated children so the next resume still sees pre-interrupt
// nodes (supports multiple interrupts in the same iteration).
......@@ -206,7 +203,7 @@ export const dispatchLoopRun = async (props: Props): Promise<Response> => {
const customOutputs = readCustomOutputSnapshot({
customOutputInputs,
runtimeNodes: isolatedNodes,
variables: newVariables,
variableState: props.variableState,
finishedNodeIds,
childrenNodeIdList
});
......@@ -292,7 +289,6 @@ export const dispatchLoopRun = async (props: Props): Promise<Response> => {
}
}
: undefined,
[DispatchNodeResponseKeyEnum.newVariables]: newVariables,
[DispatchNodeResponseKeyEnum.nodeResponse]: {
totalPoints,
loopRunInput: mode === LoopRunModeEnum.array ? inputArray : undefined,
......
......@@ -7,7 +7,10 @@ import {
formatVariableValByType,
getReferenceVariableValue
} from '@fastgpt/global/core/workflow/runtime/utils';
import type { RuntimeNodeItemType } from '@fastgpt/global/core/workflow/runtime/type';
import type {
RuntimeNodeItemType,
WorkflowVariableStateLike
} from '@fastgpt/global/core/workflow/runtime/type';
import type {
FlowNodeInputItemType,
FlowNodeOutputItemType
......@@ -54,13 +57,13 @@ export const extractFinishedNodeIds = (flowResponses: ChatHistoryItemResType[]):
export const readCustomOutputSnapshot = ({
customOutputInputs,
runtimeNodes,
variables,
variableState,
finishedNodeIds,
childrenNodeIdList
}: {
customOutputInputs: FlowNodeInputItemType[];
runtimeNodes: RuntimeNodeItemType[];
variables: Record<string, any>;
variableState: WorkflowVariableStateLike;
finishedNodeIds?: Set<string>;
childrenNodeIdList?: string[];
}): Record<string, any> => {
......@@ -98,7 +101,7 @@ export const readCustomOutputSnapshot = ({
const resolved = getReferenceVariableValue({
value: refValue,
nodesMap,
variables
variables: variableState.toRuntimeRecord()
});
snapshot[item.key] = formatVariableValByType(resolved, item.valueType);
}
......
......@@ -9,7 +9,6 @@ import {
import { serviceEnv } from '../../../../env';
import { runWorkflow } from '..';
import { cloneDeep } from 'lodash';
import {
clampParallelConcurrency,
clampParallelRetryTimes,
......@@ -84,7 +83,7 @@ export const dispatchParallelRun = async (props: Props): Promise<Response> => {
try {
const response = await runWorkflow({
...props,
variables: cloneDeep(props.variables),
variableState: props.variableState.clone(),
runtimeNodes: taskRuntimeNodes,
runtimeEdges: taskRuntimeEdges
});
......
......@@ -17,7 +17,7 @@ import { type DispatchNodeResultType } from '@fastgpt/global/core/workflow/runti
import { authWorkflowToolByTmbId } from '../../../../support/permission/app/auth';
import { ReadPermissionVal } from '@fastgpt/global/support/permission/constant';
import { computedAppToolUsage } from '../../../app/tool/runtime/utils';
import { filterSystemVariables, getNodeErrResponse } from '../utils';
import { getNodeErrResponse } from '../utils';
import { serverGetWorkflowToolRunUserQuery } from '../../../app/tool/workflowTool/utils';
import {
type NodeInputKeyEnum,
......@@ -31,6 +31,7 @@ import { anyValueDecrypt } from '../../../../common/secret/utils';
import { getAppVersionById } from '../../../app/version/controller';
import { parseI18nString } from '@fastgpt/global/common/i18n/utils';
import { getSystemToolByIdAndVersionId } from '../../../app/tool/controller';
import { WorkflowVariableState } from '../utils/variables';
type RunPluginProps = ModuleDispatchProps<{
[NodeInputKeyEnum.forbidStream]?: boolean;
......@@ -176,11 +177,26 @@ export const dispatchRunPlugin = async (props: RunPluginProps): Promise<RunPlugi
});
const { externalProvider } = await getUserChatInfo(runningAppInfo.tmbId);
const runtimeVariables = {
...filterSystemVariables(props.variables),
appId: String(workflowTool.id),
...(externalProvider ? externalProvider.externalWorkflowVariables : {})
const childRunningAppInfo = {
id: String(workflowTool.id),
name: workflowTool.name,
teamId: workflowTool.teamId || runningAppInfo.teamId,
tmbId: workflowTool.tmbId || runningAppInfo.tmbId,
isChildApp: true
};
const childVariableState = await WorkflowVariableState.create({
timezone: props.timezone,
runningAppInfo: childRunningAppInfo,
uid: props.uid,
chatId: props.chatId,
responseChatItemId: props.responseChatItemId,
histories: props.histories,
variablesConfig: [],
inputVariables: {},
externalVariables: externalProvider?.externalWorkflowVariables,
sourceVariableState: props.variableState
});
const runtimeVariables = childVariableState.toRuntimeRecord();
const {
flowResponses,
flowUsages,
......@@ -205,7 +221,7 @@ export const dispatchRunPlugin = async (props: RunPluginProps): Promise<RunPlugi
tmbId: workflowTool.tmbId || runningAppInfo.tmbId,
isChildApp: true
},
variables: runtimeVariables,
variableState: childVariableState,
query: serverGetWorkflowToolRunUserQuery({
pluginInputs: getWorkflowToolInputsFromStoreNodes(workflowTool.nodes),
variables: runtimeVariables,
......
......@@ -6,7 +6,7 @@ import type {
DispatchNodeResultType,
ModuleDispatchProps
} from '@fastgpt/global/core/workflow/runtime/type';
import { getS3ChatSource } from '../../../../common/s3/sources/chat';
import { createChatFilePreviewUrlGetter } from '../../../../common/s3/sources/chat';
export type PluginInputProps = ModuleDispatchProps<{
[key: string]: any;
......@@ -16,11 +16,24 @@ export type PluginInputResponse = DispatchNodeResultType<{
[key: string]: any;
}>;
type PluginFileItem = {
type: ChatFileTypeEnum;
key?: string;
url?: string;
};
const isPluginFileItem = (item: unknown): item is PluginFileItem =>
!!item &&
typeof item === 'object' &&
((item as PluginFileItem).type === ChatFileTypeEnum.file ||
(item as PluginFileItem).type === ChatFileTypeEnum.image);
export const dispatchPluginInput = async (
props: PluginInputProps
): Promise<PluginInputResponse> => {
const { params, query } = props;
const { files } = chatValue2RuntimePrompt(query);
const getPreviewUrl = createChatFilePreviewUrlGetter({ expiredHours: 1 });
/*
对 params 中文件类型数据进行处理
......@@ -30,29 +43,22 @@ export const dispatchPluginInput = async (
TODO: 需要 filter max files
*/
for (const key in params) {
await Promise.all(
Object.keys(params).map(async (key) => {
const val = params[key];
if (
Array.isArray(val) &&
val.every(
(item) => item.type === ChatFileTypeEnum.file || item.type === ChatFileTypeEnum.image
)
) {
if (Array.isArray(val) && val.every(isPluginFileItem)) {
// 为文件对象重新签发 URL(如果有 key 但没有 url)
for (let i = 0; i < val.length; i++) {
const fileItem = val[i];
await Promise.all(
val.map(async (fileItem) => {
if (fileItem.key && !fileItem.url) {
const { url } = await getS3ChatSource().createGetChatFileURL({
key: fileItem.key,
external: true,
expiredHours: 1
});
val[i].url = url;
}
fileItem.url = await getPreviewUrl(fileItem.key);
}
})
);
params[key] = val.map((item) => item.url);
}
}
})
);
return {
data: {
......
......@@ -8,7 +8,6 @@ import {
WorkflowIOValueTypeEnum
} from '@fastgpt/global/core/workflow/constants';
import { DispatchNodeResponseKeyEnum } from '@fastgpt/global/core/workflow/runtime/constants';
import { valueTypeFormat } from '@fastgpt/global/core/workflow/runtime/utils';
import { type DispatchNodeResultType } from '@fastgpt/global/core/workflow/runtime/type';
import type {
ModuleDispatchProps,
......@@ -17,7 +16,8 @@ import type {
import {
formatVariableValByType,
getReferenceVariableValue,
replaceEditorVariable
replaceEditorVariable,
valueTypeFormat
} from '@fastgpt/global/core/workflow/runtime/utils';
import json5 from 'json5';
import { JSONPath } from 'jsonpath-plus';
......@@ -66,7 +66,7 @@ export const dispatchHttp468Request = async (props: HttpRequestProps): Promise<H
runningAppInfo: { id: appId },
chatId,
responseChatItemId,
variables,
variableState,
node,
runtimeNodesMap,
histories,
......@@ -96,7 +96,7 @@ export const dispatchHttp468Request = async (props: HttpRequestProps): Promise<H
histories: histories?.slice(-10) || []
};
const concatVariables = {
...variables,
...variableState.toRuntimeRecord(),
...body,
...systemVariables
};
......@@ -177,7 +177,10 @@ export const dispatchHttp468Request = async (props: HttpRequestProps): Promise<H
if (httpContentType === ContentTypes.json) {
httpJsonBody = replaceJsonBodyString(
{ text: httpJsonBody },
{ variables, allVariables, runtimeNodesMap }
{
allVariables,
runtimeNodesMap
}
);
return json5.parse(httpJsonBody);
}
......@@ -303,12 +306,11 @@ export const dispatchHttp468Request = async (props: HttpRequestProps): Promise<H
export const replaceJsonBodyString = (
{ text, depth = 0 }: { text: string; depth?: number },
props: {
variables: Record<string, any>;
allVariables: Record<string, any>;
runtimeNodesMap: Map<string, RuntimeNodeItemType>;
}
) => {
const { variables, allVariables, runtimeNodesMap } = props;
const { allVariables, runtimeNodesMap } = props;
const MAX_REPLACEMENT_DEPTH = 10;
const processedVariables = new Set<string>();
......@@ -401,7 +403,7 @@ export const replaceJsonBodyString = (
const variableVal = (() => {
if (nodeId === VARIABLE_NODE_ID) {
return variables[id];
return allVariables[id];
}
// Find upstream node input/output
const node = runtimeNodesMap.get(nodeId);
......@@ -415,7 +417,7 @@ export const replaceJsonBodyString = (
return getReferenceVariableValue({
value: input.value,
nodesMap: runtimeNodesMap,
variables
variables: allVariables
});
}
})();
......
......@@ -3,7 +3,8 @@ import { NodeOutputKeyEnum } from '@fastgpt/global/core/workflow/constants';
import { DispatchNodeResponseKeyEnum } from '@fastgpt/global/core/workflow/runtime/constants';
import {
type RuntimeNodeItemType,
type DispatchNodeResultType
type DispatchNodeResultType,
type WorkflowVariableStateLike
} from '@fastgpt/global/core/workflow/runtime/type';
import {
IfElseResultEnum,
......@@ -104,16 +105,17 @@ function checkCondition(condition: VariableConditionEnum, inputValue: any, value
function getResult(
condition: IfElseConditionType,
list: ConditionListItemType[],
variables: Record<string, any>,
variableState: WorkflowVariableStateLike,
runtimeNodesMap: Map<string, RuntimeNodeItemType>
) {
const runtimeVariables = variableState.toRuntimeRecord();
const listResult = list.map((item) => {
const { variable, condition: variableCondition, value, valueType } = item;
if (!variableCondition) return;
const conditionLeftValue = getReferenceVariableValue({
value: variable,
variables,
variables: runtimeVariables,
nodesMap: runtimeNodesMap
});
......@@ -121,7 +123,7 @@ function getResult(
valueType === 'reference'
? getReferenceVariableValue({
value: value as ReferenceItemValueType,
variables,
variables: runtimeVariables,
nodesMap: runtimeNodesMap
})
: value;
......@@ -136,7 +138,7 @@ export const dispatchIfElse = async (props: Props): Promise<Response> => {
const {
params,
runtimeNodesMap,
variables,
variableState,
node: { nodeId }
} = props;
const { ifElseList } = params;
......@@ -144,7 +146,7 @@ export const dispatchIfElse = async (props: Props): Promise<Response> => {
let res = IfElseResultEnum.ELSE as string;
for (let i = 0; i < ifElseList.length; i++) {
const item = ifElseList[i];
const result = getResult(item.condition, item.list, variables, runtimeNodesMap);
const result = getResult(item.condition, item.list, variableState, runtimeNodesMap);
if (result) {
res = getElseIFLabel(i);
break;
......
......@@ -29,7 +29,7 @@ export const dispatchLafRequest = async (props: LafRequestProps): Promise<LafRes
runningAppInfo: { id: appId },
chatId,
responseChatItemId,
variables,
variableState,
node: { outputs },
histories,
params: {
......@@ -38,6 +38,7 @@ export const dispatchLafRequest = async (props: LafRequestProps): Promise<LafRes
...body
}
} = props;
const variables = variableState.toRuntimeRecord();
if (!httpReqUrl) {
return Promise.reject('Http url is empty');
......
......@@ -12,7 +12,6 @@ import {
} from '@fastgpt/global/core/workflow/runtime/utils';
import { type TUpdateListItem } from '@fastgpt/global/core/workflow/template/system/variableUpdate/type';
import { type ModuleDispatchProps } from '@fastgpt/global/core/workflow/runtime/type';
import { runtimeSystemVar2StoreType } from '../utils';
import { isValidReferenceValue } from '@fastgpt/global/core/workflow/utils';
import { valueTypeFormat } from '@fastgpt/global/core/workflow/runtime/utils';
import { getLogger, LogCategories } from '../../../../common/logger';
......@@ -66,43 +65,40 @@ type Props = ModuleDispatchProps<{
type Response = DispatchNodeResultType<{}>;
export const dispatchUpdateVariable = async (props: Props): Promise<Response> => {
const {
chatConfig,
params,
variables,
runtimeNodesMap,
workflowStreamResponse,
externalProvider,
runningAppInfo
} = props;
const { params, variableState, runtimeNodesMap, workflowStreamResponse, runningAppInfo } = props;
const { updateList } = params;
const nodeIds = Array.from(runtimeNodesMap.keys());
// 顺序执行:同一节点多条 update 依次写入,后一条读到前一条的新值
const result = updateList.map((item) => {
const result = [];
for (const item of updateList) {
const variable = item.variable;
if (!isValidReferenceValue(variable, nodeIds)) {
return null;
result.push(null);
continue;
}
const varNodeId = variable[0];
const varKey = variable[1];
if (!varKey) {
return null;
result.push(null);
continue;
}
const isInput = item.renderType === FlowNodeInputTypeEnum.input;
const isArrayVar = isArrayValueType(item.valueType);
const isArrayClear = isArrayVar && item.arrayMode === 'clear';
const isArrayAppend = isArrayVar && item.arrayMode === 'append';
const runtimeVariables = variableState.toRuntimeRecord();
// 读 oldValue(Number 公式 / Boolean negate / Array append 需要)
const oldValue =
varNodeId === VARIABLE_NODE_ID
? variables[varKey]
? variableState.get(varKey)
: runtimeNodesMap.get(varNodeId)?.outputs?.find((o) => o.id === varKey)?.value;
// 计算原始输入值(clear 分支无输入)
......@@ -115,7 +111,7 @@ export const dispatchUpdateVariable = async (props: Props): Promise<Response> =>
? replaceEditorVariable({
text: item.value?.[1],
nodesMap: runtimeNodesMap,
variables
variables: runtimeVariables
})
: item.value?.[1];
......@@ -127,7 +123,7 @@ export const dispatchUpdateVariable = async (props: Props): Promise<Response> =>
// reference
return getReferenceVariableValue({
value: item.value!,
variables,
variables: runtimeVariables,
nodesMap: runtimeNodesMap
});
})();
......@@ -163,7 +159,7 @@ export const dispatchUpdateVariable = async (props: Props): Promise<Response> =>
// 写回
if (varNodeId === VARIABLE_NODE_ID) {
variables[varKey] = value;
value = await variableState.set(varKey, value);
} else {
const node = runtimeNodesMap.get(varNodeId);
node?.outputs?.find((output) => {
......@@ -174,22 +170,17 @@ export const dispatchUpdateVariable = async (props: Props): Promise<Response> =>
});
}
return value;
});
result.push(value);
}
if (!runningAppInfo.isChildApp) {
workflowStreamResponse?.({
event: SseResponseEventEnum.updateVariables,
data: runtimeSystemVar2StoreType({
variables,
removeObj: externalProvider.externalWorkflowVariables,
userVariablesConfigs: chatConfig?.variables
})
data: variableState.toStoreRecord()
});
}
return {
[DispatchNodeResponseKeyEnum.newVariables]: variables,
[DispatchNodeResponseKeyEnum.nodeResponse]: {
updateVarResult: result
}
......
......@@ -15,7 +15,7 @@ type Response = DispatchNodeResultType<{
export const dispatchTextEditor = (props: Record<string, any>): Response => {
const {
variables,
variableState,
params: { system_textareaInput: text = '', system_addInputParam: customVariables = {} }
} = props as Props;
......@@ -36,7 +36,7 @@ export const dispatchTextEditor = (props: Record<string, any>): Response => {
const textResult = replaceVariable(text, {
...customVariables,
...variables
...variableState.toRuntimeRecord()
});
return {
......
......@@ -41,7 +41,7 @@ export type DispatchFlowResponse = {
[DispatchNodeResponseKeyEnum.runTimes]: number;
[DispatchNodeResponseKeyEnum.memories]?: Record<string, any>;
[DispatchNodeResponseKeyEnum.customFeedbacks]?: string[];
[DispatchNodeResponseKeyEnum.newVariables]: Record<string, string>;
[DispatchNodeResponseKeyEnum.newVariables]: Record<string, any>;
durationSeconds: number;
};
......
import path from 'path';
import { getErrText } from '@fastgpt/global/common/error/utils';
import { ChatRoleEnum } from '@fastgpt/global/core/chat/constants';
import type { ChatItemMiniType } from '@fastgpt/global/core/chat/type';
import type { ChatNodeUsageType } from '@fastgpt/global/support/wallet/bill/type';
import type { DispatchFlowResponse } from './type';
import {
NodeInputKeyEnum,
NodeOutputKeyEnum,
VariableInputEnum
} from '@fastgpt/global/core/workflow/constants';
import type { VariableItemType } from '@fastgpt/global/core/app/type';
import { encryptSecret } from '../../../common/secret/aes256gcm';
import { imageFileType } from '@fastgpt/global/common/file/constants';
import type { ChatDispatchProps } from '@fastgpt/global/core/workflow/runtime/type';
import type { DispatchFlowResponse } from '../type';
import { NodeInputKeyEnum, NodeOutputKeyEnum } from '@fastgpt/global/core/workflow/constants';
import {
type RuntimeNodeItemType,
type SystemVariablesType
} from '@fastgpt/global/core/workflow/runtime/type';
import type { RuntimeEdgeItemType } from '@fastgpt/global/core/workflow/type/edge';
import { responseWrite } from '../../../common/response';
import { responseWrite } from '../../../../common/response';
import { type NextApiResponse } from 'next';
import {
DispatchNodeResponseKeyEnum,
......@@ -32,85 +23,17 @@ import {
parseHttpToolConfig
} from '@fastgpt/global/core/app/tool/httpTool/utils';
import { FlowNodeTypeEnum } from '@fastgpt/global/core/workflow/node/constant';
import { MongoApp } from '../../../core/app/schema';
import { getMCPChildren } from '../../../core/app/mcp';
import { getSystemToolRunTimeNodeFromSystemToolset } from '../utils';
import { MongoApp } from '../../../app/schema';
import { getMCPChildren } from '../../../app/mcp';
import { getSystemToolRunTimeNodeFromSystemToolset } from '../../utils';
import type { localeType } from '@fastgpt/global/common/i18n/type';
import type { HttpToolConfigType } from '@fastgpt/global/core/app/tool/httpTool/type';
import type { WorkflowResponseType } from './type';
import { getLogger, LogCategories } from '../../../common/logger';
import { anyValueDecrypt } from '../../../common/secret/utils';
import { valueTypeFormat } from '@fastgpt/global/core/workflow/runtime/utils';
import { presignVariablesFileUrls } from '../../chat/utils';
import { getSystemTime } from '@fastgpt/global/common/time/timezone';
import type { WorkflowResponseType } from '../type';
import { getLogger, LogCategories } from '../../../../common/logger';
import { parsetMcpToolConfig } from '@fastgpt/global/core/app/tool/mcpTool/utils';
import { getMcpToolsets } from '../../app/tool/mcpTool/entity';
import { getHttpToolsets } from '../../app/tool/httpTool/entity';
import { getHTTPToolList } from '../../app/http';
/* get system variable */
export const getSystemVariables = async ({
timezone,
runningAppInfo,
chatId,
responseChatItemId,
histories = [],
uid,
chatConfig,
variables
}: {
runningAppInfo: ChatDispatchProps['runningAppInfo'];
chatId: ChatDispatchProps['chatId'];
responseChatItemId: ChatDispatchProps['responseChatItemId'];
histories: ChatDispatchProps['histories'];
uid: ChatDispatchProps['uid'];
chatConfig: ChatDispatchProps['chatConfig'];
variables: ChatDispatchProps['variables'];
timezone: string;
}): Promise<SystemVariablesType> => {
// Get global variables(Label -> key; Key -> key)
const variablesConfig = chatConfig?.variables || [];
const variablesMap: Record<string, any> = {};
for await (const item of variablesConfig) {
// For internal variables, ignore external input and use default value
if (item.type === VariableInputEnum.password) {
const val = variables[item.label] || variables[item.key] || item.defaultValue;
const actualValue = anyValueDecrypt(val);
variablesMap[item.key] = valueTypeFormat(actualValue, item.valueType);
}
// 文件类型全局变量,签发成 string[] 格式
else if (item.type === VariableInputEnum.file) {
const vars = await presignVariablesFileUrls({
variables,
variableConfig: [item]
});
variablesMap[item.key] = vars?.[item.key]?.map((item: any) => item.url);
}
// API
else if (variables[item.label] !== undefined) {
variablesMap[item.key] = valueTypeFormat(variables[item.label], item.valueType);
}
// Web
else if (variables[item.key] !== undefined) {
variablesMap[item.key] = valueTypeFormat(variables[item.key], item.valueType);
} else {
variablesMap[item.key] = valueTypeFormat(item.defaultValue, item.valueType);
}
}
return {
...variablesMap,
// System var:
userId: uid,
appId: String(runningAppInfo.id),
chatId,
responseChatItemId,
histories,
cTime: getSystemTime(timezone)
};
};
import { getMcpToolsets } from '../../../app/tool/mcpTool/entity';
import { getHttpToolsets } from '../../../app/tool/httpTool/entity';
import { getHTTPToolList } from '../../../app/http';
export const getWorkflowResponseWrite = ({
res,
......@@ -293,74 +216,6 @@ export const checkQuoteQAValue = (quoteQA?: SearchDataResponseItemType[]) => {
return quoteQA;
};
/* remove system variable */
export const runtimeSystemVar2StoreType = ({
variables,
removeObj = {},
userVariablesConfigs = []
}: {
variables: Record<string, any>;
removeObj?: Record<string, string>;
userVariablesConfigs?: VariableItemType[];
}) => {
const copyVariables = { ...variables };
// Delete system variables
delete copyVariables.userId;
delete copyVariables.appId;
delete copyVariables.chatId;
delete copyVariables.responseChatItemId;
delete copyVariables.histories;
delete copyVariables.cTime;
// Delete special variables
Object.keys(removeObj).forEach((key) => {
delete copyVariables[key];
});
// Encrypt password variables
userVariablesConfigs.forEach((item) => {
const val = copyVariables[item.key];
if (item.type === VariableInputEnum.password) {
if (typeof val === 'string') {
copyVariables[item.key] = {
value: '',
secret: encryptSecret(val)
};
}
}
// Handle file variables
else if (item.type === VariableInputEnum.file) {
const currentValue = copyVariables[item.key];
copyVariables[item.key] = currentValue
.map((url: string) => {
try {
const urlObj = new URL(url);
// Extract key: remove bucket prefix (e.g., "/fastgpt-private/")
const key = decodeURIComponent(urlObj.pathname.replace(/^\/[^/]+\//, ''));
const filename = path.basename(key) || 'file';
const extname = path.extname(key).toLowerCase(); // includes the dot, e.g., ".jpg"
// Check if it's an image type
const isImage = extname && imageFileType.includes(extname);
return {
id: path.basename(key, path.extname(key)), // filename without extension
key,
name: filename
};
} catch {
return null;
}
})
.filter((file: any) => file !== null);
}
});
return copyVariables;
};
export const filterSystemVariables = (variables: Record<string, any>): SystemVariablesType => {
return {
userId: variables.userId,
......@@ -569,21 +424,18 @@ export const getNodeErrResponse = ({
customErr,
responseData,
runTimes,
newVariables,
system_memories
}: {
error: any;
customErr?: Record<string, any>;
[DispatchNodeResponseKeyEnum.nodeResponse]?: Record<string, any>;
[DispatchNodeResponseKeyEnum.runTimes]?: number;
[DispatchNodeResponseKeyEnum.newVariables]?: Record<string, any>;
[DispatchNodeResponseKeyEnum.memories]?: Record<string, any>;
}) => {
const errorText = getErrText(error);
return {
[DispatchNodeResponseKeyEnum.runTimes]: runTimes,
[DispatchNodeResponseKeyEnum.newVariables]: newVariables,
[DispatchNodeResponseKeyEnum.memories]: system_memories,
error: {
[NodeOutputKeyEnum.errorText]: errorText,
......
import type { VariableItemType } from '@fastgpt/global/core/app/type';
import type { ChatFileStoreValue } from '@fastgpt/global/core/chat/type';
import { VariableInputEnum } from '@fastgpt/global/core/workflow/constants';
import type {
ChatDispatchProps,
WorkflowVariableStateLike
} from '@fastgpt/global/core/workflow/runtime/type';
import { valueTypeFormat } from '@fastgpt/global/core/workflow/runtime/utils';
import { getSystemTime } from '@fastgpt/global/common/time/timezone';
import { encryptSecret } from '../../../../common/secret/aes256gcm';
import { anyValueDecrypt } from '../../../../common/secret/utils';
import { createChatFilePreviewUrlGetter } from '../../../../common/s3/sources/chat';
import {
type ChatFileRuntimeValue,
type ChatFileRuntimeValueItem,
assertChatFileRuntimeValue,
normalizeChatFileStoreValue
} from '../../../chat/fileStoreValue';
/**
* 工作流全局变量状态管理器。
*
* 这里统一维护同一份变量的两种形态:
* - storeValue:可持久化到数据库、可返回给前端继续编辑的值。
* - runtimeValue:节点运行时直接消费的值,例如 file 变量会被转换成 string[] URL。
*
* 变量读取统一走 `get()`,变量更新统一走 `set()`,最终保存统一走 `toStoreRecord()`。
*
* 特殊变量处理也集中在这里:
* - file:store 里保存 `{ key, name, type } | { url, name, type }`,runtime 里使用 URL 数组。
* - password:store 里保存加密结构,runtime 里使用明文。
* - runtimeOnly:系统变量、外部注入变量等只参与运行,不进入最终存储。
*
* child workflow 如果收到 parent 传下来的 file runtime URL,可以通过 `sourceVariableState`
* 找回 parent 中的原始 file store metadata,避免把临时预览 URL 错写成外链。
*/
export type WorkflowVariableStateItem = {
key: string;
config?: VariableItemType;
storeValue: unknown;
runtimeValue: unknown;
runtimeOnly?: boolean;
};
export type WorkflowVariableStateCreateProps = {
// 系统级别变量,不需要额外加工
timezone: string;
runningAppInfo: ChatDispatchProps['runningAppInfo'];
uid: ChatDispatchProps['uid'];
chatId: ChatDispatchProps['chatId'];
responseChatItemId?: ChatDispatchProps['responseChatItemId'];
histories?: ChatDispatchProps['histories'];
externalVariables?: Record<string, unknown>;
// 运行时级别变量,不需要额外加工
runtimeOnlyVariables?: Record<string, unknown>;
// 全局变量配置
variablesConfig?: ChatDispatchProps['chatConfig']['variables'];
// 外部传入的变量,需要基于 variablesConfig 加工
inputVariables?: Record<string, unknown>;
// 源变量状态,用于复制变量状态
sourceVariableState?: WorkflowVariableStateLike;
};
/** 根据变量配置从入参中取值,兼容 API label 入参与前端 key 入参。 */
const getVariableInputValue = ({
variables,
item
}: {
variables: Record<string, unknown>;
item: VariableItemType;
}) => {
if (item.label && variables[item.label] !== undefined) return variables[item.label];
if (variables[item.key] !== undefined) return variables[item.key];
return item.defaultValue;
};
/** 将文件存储值转换为运行时 URL,并记录 URL 到 store metadata 的映射。 */
const fileStoreValuesToRuntimeUrls = async ({
files,
fileMetaMap,
getPreviewUrl = createChatFilePreviewUrlGetter()
}: {
files: ChatFileStoreValue[];
fileMetaMap: Map<string, ChatFileStoreValue>;
getPreviewUrl?: (key: string) => Promise<string>;
}) => {
const urls = await Promise.all(
files.map(async (file) => {
if ('key' in file) {
const url = await getPreviewUrl(file.key);
fileMetaMap.set(url, file);
return url;
}
fileMetaMap.set(file.url, file);
return file.url;
})
);
return urls.filter((url): url is string => typeof url === 'string' && !!url);
};
export class WorkflowVariableState implements WorkflowVariableStateLike {
/**
* 构造函数保持私有,外部必须通过 create 初始化。
* 这样可以保证 file 预签名、password 解密、系统变量注入都在创建阶段完成。
*/
private constructor(
private readonly state: Map<string, WorkflowVariableStateItem>,
private readonly fileMetaMap: Map<string, ChatFileStoreValue>,
private readonly sourceVariableState?: WorkflowVariableStateLike
) {}
/** 创建完整变量状态,包含用户全局变量、系统变量和运行时临时变量。 */
static async create({
timezone,
runningAppInfo,
uid,
chatId,
responseChatItemId,
histories = [],
variablesConfig = [],
inputVariables = {},
externalVariables = {},
runtimeOnlyVariables = {},
sourceVariableState
}: WorkflowVariableStateCreateProps) {
const state = new WorkflowVariableState(new Map(), new Map(), sourceVariableState);
for (const item of variablesConfig) {
const value = getVariableInputValue({ variables: inputVariables, item });
await state.initConfiguredVariable(item, value);
}
state.setRuntimeOnlyVariables(externalVariables);
state.setRuntimeOnlyVariables({
userId: uid,
appId: String(runningAppInfo.id),
chatId,
responseChatItemId,
histories,
cTime: getSystemTime(timezone)
});
state.setRuntimeOnlyVariables(runtimeOnlyVariables);
return state;
}
/** 读取运行时值,节点执行、引用变量替换都应该读这个值。 */
get(key: string) {
return this.state.get(key)?.runtimeValue;
}
/** 读取可存储值,主要用于少量需要查看原始 store value 的内部逻辑。 */
getStoreValue(key: string) {
return this.state.get(key)?.storeValue;
}
/** 根据运行时 URL 找回文件 store metadata,child workflow 会向 parent state 递归查询。 */
getFileStoreValueByRuntimeUrl(url: string) {
return (
this.fileMetaMap.get(url) || this.sourceVariableState?.getFileStoreValueByRuntimeUrl(url)
);
}
/** 更新变量值,并按变量类型同步刷新 storeValue 与 runtimeValue。 */
async set(key: string, value: unknown) {
const item = this.state.get(key);
const config = item?.config;
if (item?.runtimeOnly) {
this.state.set(key, {
...item,
runtimeValue: value
});
return value;
}
if (config?.type === VariableInputEnum.file) {
const val = value as ChatFileRuntimeValue;
const storeValue = this.runtimeFileValueToStoreValue(assertChatFileRuntimeValue(val));
const runtimeValue = await fileStoreValuesToRuntimeUrls({
files: storeValue,
fileMetaMap: this.fileMetaMap
});
this.state.set(key, {
key,
config,
storeValue,
runtimeValue
});
return runtimeValue;
}
if (config?.type === VariableInputEnum.password && typeof value === 'string') {
const storeValue = {
value: '',
secret: encryptSecret(value)
};
this.state.set(key, {
key,
config,
storeValue,
runtimeValue: value
});
return value;
}
const runtimeValue = valueTypeFormat(value, config?.valueType);
this.state.set(key, {
key,
config,
storeValue: runtimeValue,
runtimeValue
});
return runtimeValue;
}
/** 输出节点运行可直接消费的变量记录,包含 runtimeOnly 变量。 */
toRuntimeRecord() {
return Array.from(this.state.values()).reduce<Record<string, unknown>>((acc, item) => {
acc[item.key] = item.runtimeValue;
return acc;
}, {});
}
/** 输出最终可持久化变量记录,不包含 runtimeOnly 变量。 */
toStoreRecord() {
return Array.from(this.state.values()).reduce<Record<string, unknown>>((acc, item) => {
if (!item.runtimeOnly) {
acc[item.key] = item.storeValue;
}
return acc;
}, {});
}
/** 克隆当前状态,主要用于子运行/分支运行时隔离运行态修改。 */
clone() {
return new WorkflowVariableState(
new Map(
Array.from(this.state.entries()).map(([key, item]) => [
key,
{
...item
}
])
),
new Map(this.fileMetaMap),
this.sourceVariableState
);
}
/** 根据变量配置初始化单个用户变量,并完成特殊类型的 store/runtime 转换。 */
private async initConfiguredVariable(config: VariableItemType, value: unknown) {
if (config.type === VariableInputEnum.file) {
const storeValue = Array.isArray(value)
? this.runtimeFileValueToStoreValue(
assertChatFileRuntimeValue(value as ChatFileRuntimeValueItem[])
)
: [];
const runtimeValue = await fileStoreValuesToRuntimeUrls({
files: storeValue,
fileMetaMap: this.fileMetaMap
});
this.state.set(config.key, {
key: config.key,
config,
storeValue,
runtimeValue
});
return;
}
if (config.type === VariableInputEnum.password) {
const runtimeValue = anyValueDecrypt(value);
const storeValue =
typeof runtimeValue === 'string'
? {
value: '',
secret: encryptSecret(runtimeValue)
}
: value;
this.state.set(config.key, {
key: config.key,
config,
storeValue,
runtimeValue
});
return;
}
const runtimeValue = valueTypeFormat(value, config.valueType);
this.state.set(config.key, {
key: config.key,
config,
storeValue: runtimeValue,
runtimeValue
});
}
/** 注入只参与运行、不进入存储的变量。 */
private setRuntimeOnlyVariables(variables: Record<string, unknown>) {
Object.entries(variables).forEach(([key, value]) => {
if (value === undefined) return;
this.state.set(key, {
key,
storeValue: undefined,
runtimeValue: value,
runtimeOnly: true
});
});
}
/** 将 file runtime 值转回 store 值,优先复用已知 URL 对应的原始 metadata。 */
private runtimeFileValueToStoreValue(value: ChatFileRuntimeValue): ChatFileStoreValue[] {
return value
.map((item) => {
if (typeof item === 'string') {
if (!item || item.startsWith('data:')) return;
const knownFile = this.getFileStoreValueByRuntimeUrl(item);
if (knownFile) return knownFile;
return normalizeChatFileStoreValue({ url: item });
}
return normalizeChatFileStoreValue(item);
})
.filter((file): file is ChatFileStoreValue => Boolean(file));
}
}
......@@ -891,7 +891,6 @@ describe('pushChatRecords', () => {
chatId: props.chatId,
obj: ChatRoleEnum.AI
});
console.log(chatItem?.value, 1212);
if (chatItem) {
if (chatItem.obj === ChatRoleEnum.AI) {
const lastValue = chatItem.value[chatItem.value.length - 1];
......@@ -997,6 +996,133 @@ describe('pushChatRecords', () => {
}
});
it('should sanitize fileSelect form value before storing interactive history', async () => {
await MongoChatItem.create({
chatId: 'test-chat-id',
teamId: testTeamId,
tmbId: testTmbId,
appId: testAppId,
obj: ChatRoleEnum.AI,
dataId: 'data-id-1',
value: [
{
interactive: {
type: 'userInput',
params: {
submitted: false,
inputForm: [
{
key: 'upload',
type: FlowNodeInputTypeEnum.fileSelect,
label: 'Upload',
value: []
}
]
}
}
}
]
});
const props = createMockProps(
{
userContent: {
obj: ChatRoleEnum.Human,
value: [
{
text: {
content: JSON.stringify({
upload: [
{
id: 'runtime-id',
key: 'chat/files/invoice.png',
url: 'https://preview.example.com/invoice.png',
name: 'invoice.png',
type: ChatFileTypeEnum.image,
icon: 'https://preview.example.com/invoice.png',
status: 'done',
process: 100,
error: 'should not persist'
},
{
id: 'external-id',
url: 'https://external.example.com/report.pdf',
name: 'report.pdf',
type: ChatFileTypeEnum.file,
status: 'done'
},
{
url: 'data:image/png;base64,AAAA',
name: 'inline.png',
type: ChatFileTypeEnum.image
}
]
})
}
}
]
},
aiContent: {
obj: ChatRoleEnum.AI,
value: [],
responseData: []
}
},
{ appId: testAppId, teamId: testTeamId, tmbId: testTmbId }
);
const interactive = {
type: 'userInput' as const,
params: {
description: '',
submitted: false,
inputForm: [
{
key: 'upload',
type: FlowNodeInputTypeEnum.fileSelect,
label: 'Upload',
value: [],
valueType: WorkflowIOValueTypeEnum.arrayString,
required: false
}
]
},
entryNodeIds: [],
memoryEdges: [],
nodeOutputs: []
};
await updateInteractiveChat({ interactive, ...props });
const chatItem = await MongoChatItem.findOne({
appId: testAppId,
chatId: props.chatId,
obj: ChatRoleEnum.AI
});
if (chatItem?.obj !== ChatRoleEnum.AI) {
throw new Error('chatItem does not have AI interactive value');
}
const lastValue = chatItem.value[chatItem.value.length - 1];
if (lastValue.interactive?.type !== 'userInput') {
throw new Error('chatItem does not have userInput interactive');
}
expect(lastValue.interactive.params.inputForm[0].value).toEqual([
{
key: 'chat/files/invoice.png',
name: 'invoice.png',
type: ChatFileTypeEnum.image
},
{
url: 'https://external.example.com/report.pdf',
name: 'report.pdf',
type: ChatFileTypeEnum.file
}
]);
});
it('should persist agentPlanAskQuery answer before pushing new records', async () => {
await MongoChatItem.create({
chatId: 'test-chat-id',
......
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ChatFileTypeEnum } from '@fastgpt/global/core/chat/constants';
import {
VariableInputEnum,
WorkflowIOValueTypeEnum
} from '@fastgpt/global/core/workflow/constants';
import { FlowNodeInputTypeEnum } from '@fastgpt/global/core/workflow/node/constant';
import {
addPreviewUrlToChatItems,
presignVariablesFileUrls
} from '@fastgpt/service/core/chat/utils';
const { mockCreateGetChatFileURL } = vi.hoisted(() => ({
mockCreateGetChatFileURL: vi.fn()
}));
vi.mock('@fastgpt/service/common/s3/sources/chat', () => ({
getS3ChatSource: () => ({
createGetChatFileURL: mockCreateGetChatFileURL
}),
createChatFilePreviewUrlGetter:
(options?: { expiredHours?: number; mode?: 'proxy' | 'presigned' }) => async (key: string) => {
const { url } = await mockCreateGetChatFileURL({
key,
external: true,
...options
});
return url;
}
}));
describe('presignVariablesFileUrls', () => {
beforeEach(() => {
mockCreateGetChatFileURL.mockReset();
});
it('为全局变量文件补预览 url,并保留已有 type', async () => {
mockCreateGetChatFileURL.mockResolvedValueOnce({
url: 'https://preview.example.com/image.png'
});
const variables = {
imageFiles: [
{
key: 'chat/files/image.png',
name: 'image.png',
type: ChatFileTypeEnum.image
}
]
};
const result = await presignVariablesFileUrls({
variables,
variableConfig: [
{
key: 'imageFiles',
label: '图片',
type: VariableInputEnum.file,
valueType: WorkflowIOValueTypeEnum.arrayString
}
]
});
expect(result?.imageFiles).toEqual([
{
key: 'chat/files/image.png',
name: 'image.png',
type: ChatFileTypeEnum.image,
url: 'https://preview.example.com/image.png'
}
]);
expect(variables.imageFiles[0]).not.toHaveProperty('url');
expect(mockCreateGetChatFileURL).toHaveBeenCalledWith({
key: 'chat/files/image.png',
external: true
});
});
it('没有 S3 key 的文件值不请求预览 url,并保留已有 type', async () => {
const result = await presignVariablesFileUrls({
variables: {
files: [
{
url: 'https://example.com/doc.pdf',
name: 'doc.pdf',
type: ChatFileTypeEnum.file
}
]
},
variableConfig: [
{
key: 'files',
label: '文件',
type: VariableInputEnum.file,
valueType: WorkflowIOValueTypeEnum.arrayString
}
]
});
expect(result?.files).toEqual([
{
url: 'https://example.com/doc.pdf',
name: 'doc.pdf',
type: ChatFileTypeEnum.file
}
]);
expect(mockCreateGetChatFileURL).not.toHaveBeenCalled();
});
it('保留全局变量文件已有 type,不用文件名推断覆盖', async () => {
mockCreateGetChatFileURL.mockResolvedValueOnce({
url: 'https://preview.example.com/photo.png'
});
const result = await presignVariablesFileUrls({
variables: {
files: [
{
key: 'chat/files/photo.png',
name: 'photo.png',
type: ChatFileTypeEnum.file
}
]
},
variableConfig: [
{
key: 'files',
label: '文件',
type: VariableInputEnum.file,
valueType: WorkflowIOValueTypeEnum.arrayString
}
]
});
expect(result?.files).toEqual([
{
key: 'chat/files/photo.png',
name: 'photo.png',
type: ChatFileTypeEnum.file,
url: 'https://preview.example.com/photo.png'
}
]);
});
it('只重建文件变量,保留非文件变量引用,避免深拷贝大对象', async () => {
const payload = {
nested: {
items: Array.from({ length: 10 }, (_, index) => ({ index }))
}
};
const variables = {
payload,
files: [
{
url: 'https://example.com/doc.pdf',
name: 'doc.pdf'
}
]
};
const result = await presignVariablesFileUrls({
variables,
variableConfig: [
{
key: 'files',
label: '文件',
type: VariableInputEnum.file,
valueType: WorkflowIOValueTypeEnum.arrayString
}
]
});
expect(result).not.toBe(variables);
expect(result?.payload).toBe(payload);
expect(result?.files).not.toBe(variables.files);
expect(variables.files[0]).not.toHaveProperty('type');
});
});
describe('addPreviewUrlToChatItems', () => {
beforeEach(() => {
mockCreateGetChatFileURL.mockReset();
});
it('兼容缺少 params 的历史 interactive 数据,不阻断历史加载', async () => {
const histories = [
{
obj: 'AI',
value: [
{
interactive: {
type: 'userInput'
}
}
]
}
];
await expect(addPreviewUrlToChatItems(histories as any, 'chatFlow')).resolves.toBeUndefined();
expect(mockCreateGetChatFileURL).not.toHaveBeenCalled();
});
it('为历史 interactive fileSelect 值补预览 url 和 type', async () => {
mockCreateGetChatFileURL.mockResolvedValueOnce({
url: 'https://preview.example.com/image.png'
});
const histories = [
{
obj: 'AI',
value: [
{
interactive: {
type: 'userInput',
params: {
inputForm: [
{
key: 'upload',
type: FlowNodeInputTypeEnum.fileSelect,
value: [
{
key: 'chat/files/image.png',
name: 'image.png',
type: ChatFileTypeEnum.image
}
]
}
]
}
}
}
]
}
];
await addPreviewUrlToChatItems(histories as any, 'chatFlow');
expect(histories[0].value[0].interactive.params.inputForm[0].value).toEqual([
{
key: 'chat/files/image.png',
name: 'image.png',
type: ChatFileTypeEnum.image,
url: 'https://preview.example.com/image.png'
}
]);
expect(mockCreateGetChatFileURL).toHaveBeenCalledWith({
key: 'chat/files/image.png',
external: true
});
});
it('为 workflowTool 历史输入中的 fileSelect 值补预览 url', async () => {
mockCreateGetChatFileURL.mockResolvedValueOnce({
url: 'https://preview.example.com/doc.pdf'
});
const histories = [
{
obj: 'Human',
value: [
{
text: {
content: JSON.stringify([
{
renderTypeList: [FlowNodeInputTypeEnum.fileSelect],
value: [
{
key: 'chat/files/doc.pdf',
name: 'doc.pdf',
type: ChatFileTypeEnum.file
}
]
}
])
}
}
]
}
];
await addPreviewUrlToChatItems(histories as any, 'workflowTool');
expect(JSON.parse(histories[0].value[0].text.content)).toEqual([
{
renderTypeList: [FlowNodeInputTypeEnum.fileSelect],
value: [
{
key: 'chat/files/doc.pdf',
name: 'doc.pdf',
type: ChatFileTypeEnum.file,
url: 'https://preview.example.com/doc.pdf'
}
]
}
]);
expect(mockCreateGetChatFileURL).toHaveBeenCalledWith({
key: 'chat/files/doc.pdf',
external: true
});
});
});
import { describe, expect, it, vi } from 'vitest';
import { NodeInputKeyEnum, WorkflowIOValueTypeEnum } from '@fastgpt/global/core/workflow/constants';
import { VariableInputEnum } from '@fastgpt/global/core/workflow/constants';
import { WorkflowVariableState } from '../../../../../core/workflow/dispatch/utils/variables';
const runWorkflowMock = vi.fn();
const authAppByTmbIdMock = vi.fn();
const getUserChatInfoMock = vi.fn();
vi.mock('../../../../../core/workflow/dispatch/index', () => ({
runWorkflow: (args: any) => runWorkflowMock(args)
}));
vi.mock('../../../../../support/permission/app/auth', () => ({
authAppByTmbId: (...args: any[]) => authAppByTmbIdMock(...args)
}));
vi.mock('../../../../../support/user/team/utils', () => ({
getUserChatInfo: (...args: any[]) => getUserChatInfoMock(...args)
}));
import { dispatchAppRequest } from '../../../../../core/workflow/dispatch/abandoned/runApp';
const createParentVariableState = () =>
WorkflowVariableState.create({
timezone: 'Asia/Shanghai',
runningAppInfo: {
id: 'parent-app',
teamId: 'team',
tmbId: 'parent-tmb',
name: 'parent'
},
uid: 'uid',
chatId: 'chat',
variablesConfig: [
{
key: 'shared',
type: VariableInputEnum.input,
valueType: WorkflowIOValueTypeEnum.string
} as any
],
inputVariables: {
shared: 'parent-value'
}
});
describe('abandoned dispatchAppRequest', () => {
it('should run child app with an isolated variable state', async () => {
const parentVariableState = await createParentVariableState();
let childInitialValue: unknown;
authAppByTmbIdMock.mockResolvedValue({
app: {
_id: 'child-app',
name: 'child',
avatar: '',
teamId: 'team',
tmbId: 'child-tmb',
modules: [],
edges: [],
chatConfig: {
variables: [
{
key: 'shared',
type: VariableInputEnum.input,
valueType: WorkflowIOValueTypeEnum.string
}
]
}
}
});
getUserChatInfoMock.mockResolvedValue({
externalProvider: {
externalWorkflowVariables: {}
}
});
runWorkflowMock.mockImplementation(async (args: any) => {
childInitialValue = args.variableState.get('shared');
await args.variableState.set('shared', 'child-value');
return {
flowResponses: [],
flowUsages: [],
assistantResponses: [],
system_memories: []
};
});
await dispatchAppRequest({
runningAppInfo: {
id: 'parent-app',
teamId: 'team',
tmbId: 'parent-tmb',
name: 'parent'
},
workflowStreamResponse: vi.fn(),
histories: [],
query: [],
variableState: parentVariableState,
params: {
[NodeInputKeyEnum.userChatInput]: 'hello',
app: {
id: 'child-app'
}
},
timezone: 'Asia/Shanghai',
uid: 'uid',
chatId: 'chat',
responseChatItemId: 'response',
chatConfig: {
variables: []
}
} as any);
const childVariableState = runWorkflowMock.mock.calls[0][0].variableState;
expect(childVariableState).not.toBe(parentVariableState);
expect(childInitialValue).toBe('parent-value');
expect(childVariableState.get('shared')).toBe('child-value');
expect(parentVariableState.get('shared')).toBe('parent-value');
});
});
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
NodeInputKeyEnum,
NodeOutputKeyEnum,
WorkflowIOValueTypeEnum
} from '@fastgpt/global/core/workflow/constants';
import { FlowNodeInputTypeEnum } from '@fastgpt/global/core/workflow/node/constant';
import { DispatchNodeResponseKeyEnum } from '@fastgpt/global/core/workflow/runtime/constants';
import { dispatchFormInput } from '@fastgpt/service/core/workflow/dispatch/interactive/formInput';
const { mockCreateGetChatFileURL } = vi.hoisted(() => ({
mockCreateGetChatFileURL: vi.fn()
}));
vi.mock('@fastgpt/service/common/s3/sources/chat', () => ({
getS3ChatSource: () => ({
createGetChatFileURL: mockCreateGetChatFileURL
}),
createChatFilePreviewUrlGetter:
(options?: { expiredHours?: number; mode?: 'proxy' | 'presigned' }) => async (key: string) => {
const { url } = await mockCreateGetChatFileURL({
key,
external: true,
...options
});
return url;
}
}));
describe('dispatchFormInput', () => {
beforeEach(() => {
mockCreateGetChatFileURL.mockReset();
});
it('presigns key-only fileSelect values before exposing form outputs', async () => {
mockCreateGetChatFileURL.mockResolvedValueOnce({
url: 'https://preview.example.com/upload.png'
});
const result = await dispatchFormInput({
histories: [{ obj: 'Human', value: [] }],
node: { isEntry: true },
params: {
[NodeInputKeyEnum.description]: 'upload',
[NodeInputKeyEnum.userInputForms]: [
{
key: 'upload',
label: 'upload',
type: FlowNodeInputTypeEnum.fileSelect,
value: [],
valueType: WorkflowIOValueTypeEnum.arrayString,
required: false
}
]
},
query: [
{
text: {
content: JSON.stringify({
upload: [
{ key: 'chat/files/upload.png', name: 'upload.png' },
{ url: 'https://external.example.com/file.pdf' },
'https://legacy.example.com/file.txt'
]
})
}
}
],
lastInteractive: { type: 'userInput' }
} as any);
expect(result.data?.upload).toEqual([
'https://preview.example.com/upload.png',
'https://external.example.com/file.pdf',
'https://legacy.example.com/file.txt'
]);
expect(result.data?.[NodeOutputKeyEnum.formInputResult]).toEqual({
upload: [
'https://preview.example.com/upload.png',
'https://external.example.com/file.pdf',
'https://legacy.example.com/file.txt'
]
});
expect(result[DispatchNodeResponseKeyEnum.toolResponses]).toEqual({
upload: [
'https://preview.example.com/upload.png',
'https://external.example.com/file.pdf',
'https://legacy.example.com/file.txt'
]
});
expect(mockCreateGetChatFileURL).toHaveBeenCalledWith({
key: 'chat/files/upload.png',
external: true,
expiredHours: 1
});
});
});
......@@ -7,6 +7,7 @@ import { NodeInputKeyEnum, NodeOutputKeyEnum } from '@fastgpt/global/core/workfl
import { DispatchNodeResponseKeyEnum } from '@fastgpt/global/core/workflow/runtime/constants';
import { LoopRunModeEnum } from '@fastgpt/global/core/workflow/template/system/loopRun/loopRun';
import type { RuntimeNodeItemType } from '@fastgpt/global/core/workflow/runtime/type';
import type { WorkflowVariableStateLike } from '@fastgpt/global/core/workflow/runtime/type';
import type { FlowNodeInputItemType } from '@fastgpt/global/core/workflow/type/io';
import type { ChatHistoryItemResType } from '@fastgpt/global/core/chat/type';
import type { DispatchFlowResponse } from '@fastgpt/service/core/workflow/dispatch/type';
......@@ -148,6 +149,20 @@ const makeResponseItem = (nodeId: string, override: Partial<ChatHistoryItemResTy
...override
}) as ChatHistoryItemResType;
const makeVariableState = (variables: Record<string, unknown> = {}): WorkflowVariableStateLike =>
({
get: (key: string) => variables[key],
set: async (key: string, value: unknown) => {
variables[key] = value;
return value;
},
getStoreValue: (key: string) => variables[key],
getFileStoreValueByRuntimeUrl: () => undefined,
toRuntimeRecord: () => variables,
toStoreRecord: () => variables,
clone: () => makeVariableState({ ...variables })
}) satisfies WorkflowVariableStateLike;
const makeProps = (
params: any,
opts: { withBreak?: boolean; childrenNodeIdList?: string[] } = {}
......@@ -169,7 +184,7 @@ const makeProps = (
runtimeNodes,
runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])),
runtimeEdges: [],
variables: {},
variableState: makeVariableState(),
usagePush: vi.fn(),
lastInteractive: undefined,
checkIsStopping: () => false
......@@ -215,7 +230,7 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => {
runtimeNodes,
runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])),
runtimeEdges: [],
variables: {},
variableState: makeVariableState(),
usagePush: vi.fn(),
lastInteractive: undefined,
checkIsStopping: () => false
......@@ -233,6 +248,28 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => {
expect(result.error).toBeUndefined();
});
it('子运行返回的 newVariables 不再透出到 loopRun 节点结果', async () => {
runWorkflowMock.mockImplementation((args: any) => {
void args.variableState.set('runtimeOnly', 'runtime-value');
return Promise.resolve(
makeDispatchFlowResponse({
[DispatchNodeResponseKeyEnum.newVariables]: {
runtimeOnly: { value: '', secret: 'encrypted-store-value' }
}
})
);
});
const props = makeProps({
[NodeInputKeyEnum.loopRunMode]: LoopRunModeEnum.array,
[NodeInputKeyEnum.loopRunInputArray]: ['a']
});
const result: any = await dispatchLoopRun(props);
expect(result[DispatchNodeResponseKeyEnum.newVariables]).toBeUndefined();
});
it('array mode 第 2 轮节点出错 → 本轮 success:false, 失败轮快照对未跑节点返回 undefined', async () => {
let iter = 0;
runWorkflowMock.mockImplementation((args: any) => {
......@@ -268,7 +305,7 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => {
runtimeNodes,
runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])),
runtimeEdges: [],
variables: {},
variableState: makeVariableState(),
usagePush: vi.fn(),
lastInteractive: undefined,
checkIsStopping: () => false
......@@ -476,7 +513,7 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => {
runtimeNodes,
runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])),
runtimeEdges: [],
variables: {},
variableState: makeVariableState(),
usagePush: vi.fn(),
lastInteractive: {
type: 'loopRunInteractive',
......@@ -528,7 +565,7 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => {
runtimeNodes,
runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])),
runtimeEdges: [],
variables: {},
variableState: makeVariableState(),
usagePush: vi.fn(),
lastInteractive: {
type: 'loopRunInteractive',
......@@ -614,7 +651,7 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => {
runtimeNodes,
runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])),
runtimeEdges: [],
variables: {},
variableState: makeVariableState(),
usagePush: vi.fn(),
lastInteractive: undefined,
checkIsStopping: () => false
......@@ -785,7 +822,7 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => {
runtimeNodes,
runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])),
runtimeEdges: [],
variables: {},
variableState: makeVariableState(),
usagePush: vi.fn(),
checkIsStopping: () => false,
lastInteractive: {
......
......@@ -5,7 +5,10 @@ import {
} from '@fastgpt/global/core/workflow/node/constant';
import { NodeInputKeyEnum } from '@fastgpt/global/core/workflow/constants';
import { LoopRunModeEnum } from '@fastgpt/global/core/workflow/template/system/loopRun/loopRun';
import type { RuntimeNodeItemType } from '@fastgpt/global/core/workflow/runtime/type';
import type {
RuntimeNodeItemType,
WorkflowVariableStateLike
} from '@fastgpt/global/core/workflow/runtime/type';
import type {
FlowNodeInputItemType,
FlowNodeOutputItemType
......@@ -65,6 +68,18 @@ const makeResponse = (override: Partial<ChatHistoryItemResType>): ChatHistoryIte
...override
}) as ChatHistoryItemResType;
const makeVariableState = (variables: Record<string, unknown> = {}): WorkflowVariableStateLike => ({
get: (key: string) => variables[key],
set: async (key: string, value: unknown) => {
variables[key] = value;
return value;
},
getStoreValue: (key: string) => variables[key],
getFileStoreValueByRuntimeUrl: () => undefined,
toRuntimeRecord: () => ({ ...variables }),
toStoreRecord: () => ({ ...variables })
});
// ─── Tests ────────────────────────────────────────────────────────────────────
describe('loopRun/service', () => {
......@@ -155,7 +170,7 @@ describe('loopRun/service', () => {
const snapshot = readCustomOutputSnapshot({
customOutputInputs,
runtimeNodes: [nodeA, nodeB],
variables: {}
variableState: makeVariableState()
});
expect(snapshot).toEqual({ a: 'valueFromA', b: 'valueFromB' });
});
......@@ -168,7 +183,7 @@ describe('loopRun/service', () => {
const snapshot = readCustomOutputSnapshot({
customOutputInputs,
runtimeNodes: [nodeA, nodeB],
variables: {},
variableState: makeVariableState(),
finishedNodeIds: new Set(['A']) // 只有 A 跑过
});
expect(snapshot).toEqual({ a: 'valueFromA', b: undefined });
......@@ -181,7 +196,7 @@ describe('loopRun/service', () => {
const snapshot = readCustomOutputSnapshot({
customOutputInputs,
runtimeNodes: [nodeA],
variables: {},
variableState: makeVariableState(),
finishedNodeIds: new Set()
});
expect(snapshot).toEqual({ a: undefined });
......@@ -194,7 +209,7 @@ describe('loopRun/service', () => {
const snapshot = readCustomOutputSnapshot({
customOutputInputs,
runtimeNodes: [],
variables: { globalKey: 'globalValue' },
variableState: makeVariableState({ globalKey: 'globalValue' }),
finishedNodeIds: new Set()
});
expect(snapshot).toEqual({ g: 'globalValue' });
......@@ -204,7 +219,7 @@ describe('loopRun/service', () => {
const snapshot = readCustomOutputSnapshot({
customOutputInputs: [],
runtimeNodes: [],
variables: {}
variableState: makeVariableState()
});
expect(snapshot).toEqual({});
});
......@@ -219,7 +234,7 @@ describe('loopRun/service', () => {
const snapshot = readCustomOutputSnapshot({
customOutputInputs,
runtimeNodes: [nodeA, nodeB],
variables: {},
variableState: makeVariableState(),
finishedNodeIds: new Set(['B']), // 只有 B(循环体内)跑过
childrenNodeIdList: ['B'] // A 在循环体外
});
......@@ -234,7 +249,7 @@ describe('loopRun/service', () => {
const snapshot = readCustomOutputSnapshot({
customOutputInputs,
runtimeNodes: [nodeA, nodeB],
variables: {},
variableState: makeVariableState(),
finishedNodeIds: new Set(['B']),
childrenNodeIdList: ['A', 'B'] // 都在循环体内,A 本轮未跑
});
......
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ChatFileTypeEnum } from '@fastgpt/global/core/chat/constants';
import { NodeOutputKeyEnum } from '@fastgpt/global/core/workflow/constants';
import { DispatchNodeResponseKeyEnum } from '@fastgpt/global/core/workflow/runtime/constants';
import { dispatchPluginInput } from '@fastgpt/service/core/workflow/dispatch/plugin/runInput';
const { mockCreateGetChatFileURL } = vi.hoisted(() => ({
mockCreateGetChatFileURL: vi.fn()
}));
vi.mock('@fastgpt/service/common/s3/sources/chat', () => ({
getS3ChatSource: () => ({
createGetChatFileURL: mockCreateGetChatFileURL
}),
createChatFilePreviewUrlGetter:
(options?: { expiredHours?: number; mode?: 'proxy' | 'presigned' }) => async (key: string) => {
const { url } = await mockCreateGetChatFileURL({
key,
external: true,
...options
});
return url;
}
}));
describe('dispatchPluginInput', () => {
beforeEach(() => {
mockCreateGetChatFileURL.mockReset();
});
it('presigns key-only file params before exposing plugin inputs', async () => {
mockCreateGetChatFileURL.mockResolvedValueOnce({
url: 'https://preview.example.com/doc.pdf'
});
const result = await dispatchPluginInput({
params: {
upload: [
{
type: ChatFileTypeEnum.file,
key: 'chat/files/doc.pdf',
name: 'doc.pdf'
},
{
type: ChatFileTypeEnum.image,
key: 'chat/files/image.png',
name: 'image.png',
url: 'https://existing.example.com/image.png'
}
]
},
query: []
} as any);
expect(result.data?.upload).toEqual([
'https://preview.example.com/doc.pdf',
'https://existing.example.com/image.png'
]);
expect(result.data?.[NodeOutputKeyEnum.userFiles]).toEqual([]);
expect(result[DispatchNodeResponseKeyEnum.nodeResponse]).toEqual({});
expect(mockCreateGetChatFileURL).toHaveBeenCalledWith({
key: 'chat/files/doc.pdf',
external: true,
expiredHours: 1
});
});
it('keeps plugin-called string url arrays unchanged', async () => {
const result = await dispatchPluginInput({
params: {
upload: ['https://external.example.com/doc.pdf']
},
query: []
} as any);
expect(result.data?.upload).toEqual(['https://external.example.com/doc.pdf']);
expect(mockCreateGetChatFileURL).not.toHaveBeenCalled();
});
it('keeps legacy userFiles from top-level query files', async () => {
const result = await dispatchPluginInput({
params: {},
query: [
{
file: {
type: ChatFileTypeEnum.file,
name: 'top.pdf',
url: 'https://query.example.com/top.pdf'
}
},
{
text: {
content: 'ignored'
}
}
]
} as any);
expect(result.data?.[NodeOutputKeyEnum.userFiles]).toEqual([
'https://query.example.com/top.pdf'
]);
});
});
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { describe, it, expect, vi } from 'vitest';
import { dispatchUpdateVariable } from '@fastgpt/service/core/workflow/dispatch/tools/runUpdateVar';
import { VARIABLE_NODE_ID, WorkflowIOValueTypeEnum } from '@fastgpt/global/core/workflow/constants';
import {
VARIABLE_NODE_ID,
VariableInputEnum,
WorkflowIOValueTypeEnum
} from '@fastgpt/global/core/workflow/constants';
import { FlowNodeInputTypeEnum } from '@fastgpt/global/core/workflow/node/constant';
import type { TUpdateListItem } from '@fastgpt/global/core/workflow/template/system/variableUpdate/type';
import { ChatFileTypeEnum } from '@fastgpt/global/core/chat/constants';
import { WorkflowVariableState } from '../../../../../core/workflow/dispatch/utils/variables';
// Logger 不走真实实现,避免 log 基础设施依赖
vi.mock('../../../../../../../../packages/service/common/logger', () => ({
......@@ -21,6 +27,11 @@ vi.mock('../../../../../../../../packages/service/common/logger', () => ({
}
}));
const mockGetChatFilePreviewUrl = vi.fn(async (key: string) => `http://example.com/${key}`);
vi.mock('@fastgpt/service/common/s3/sources/chat', () => ({
createChatFilePreviewUrlGetter: () => mockGetChatFilePreviewUrl
}));
type AnyProps = Parameters<typeof dispatchUpdateVariable>[0];
type BuildOpts = {
......@@ -29,8 +40,41 @@ type BuildOpts = {
isChildApp?: boolean;
chatConfig?: any;
externalWorkflowVariables?: Record<string, any>;
storeVariables?: Record<string, any>;
};
const createTestVariableState = ({
variables,
storeVariables = {},
chatConfig = {}
}: {
variables: Record<string, any>;
storeVariables?: Record<string, any>;
chatConfig?: any;
}) => ({
get: (key: string) => variables[key],
getStoreValue: (key: string) => storeVariables[key] ?? variables[key],
getFileStoreValueByRuntimeUrl: () => undefined,
toRuntimeRecord: () => ({ ...variables }),
toStoreRecord: () => (Object.keys(storeVariables).length > 0 ? storeVariables : variables),
clone: () => createTestVariableState({ variables: { ...variables }, storeVariables, chatConfig }),
set: async (key: string, value: any) => {
variables[key] = value;
const variableConfig = chatConfig.variables?.find((item: any) => item.key === key);
if (variableConfig?.type === VariableInputEnum.password) {
storeVariables[key] = {
value: '',
secret: `mock-secret:${value}`
};
} else if (Object.keys(storeVariables).length > 0) {
storeVariables[key] = value;
}
return value;
}
});
const buildProps = (
variables: Record<string, any>,
updateList: TUpdateListItem[],
......@@ -40,7 +84,11 @@ const buildProps = (
return {
chatConfig: opts.chatConfig ?? {},
params: { updateList },
variableState: createTestVariableState({
variables,
storeVariables: opts.storeVariables,
chatConfig: opts.chatConfig
}),
runtimeNodesMap,
workflowStreamResponse: opts.workflowStreamResponse,
externalProvider: { externalWorkflowVariables: opts.externalWorkflowVariables ?? {} },
......@@ -50,6 +98,113 @@ const buildProps = (
const ref = (key: string) => [VARIABLE_NODE_ID, key] as [string, string];
describe('WorkflowVariableState file variable updates', () => {
const createFileState = (inputVariables: Record<string, unknown> = {}) =>
WorkflowVariableState.create({
timezone: 'Asia/Shanghai',
runningAppInfo: {
id: 'appId',
teamId: 'teamId',
tmbId: 'tmbId',
name: 'app'
},
uid: 'uid',
chatId: 'chatId',
variablesConfig: [
{
key: 'files',
type: VariableInputEnum.file
} as any
],
inputVariables
});
it('should restore key file metadata from runtime url map', async () => {
const state = await createFileState({
files: [
{
key: 'chat/app/a.png',
name: 'a.png',
type: ChatFileTypeEnum.image
}
]
});
const runtimeUrls = state.get('files') as string[];
const result = await state.set('files', [runtimeUrls[0]]);
expect(result).toEqual(['http://example.com/chat/app/a.png']);
expect(state.toStoreRecord().files).toEqual([
{
key: 'chat/app/a.png',
name: 'a.png',
type: ChatFileTypeEnum.image
}
]);
});
it('should infer store metadata for unknown external urls', async () => {
const state = await createFileState();
await state.set('files', ['https://external.example.com/report.unknown']);
expect(state.toStoreRecord().files).toEqual([
{
url: 'https://external.example.com/report.unknown',
name: 'report.unknown',
type: ChatFileTypeEnum.file
}
]);
});
it('should keep existing runtime urls when appending object values', async () => {
const state = await createFileState({
files: [
{
key: 'chat/app/old.pdf',
name: 'old.pdf',
type: ChatFileTypeEnum.file
}
]
});
const runtimeUrls = state.get('files') as string[];
const result = await state.set('files', [
runtimeUrls[0],
{
key: 'chat/app/new.png',
name: 'new.png',
type: ChatFileTypeEnum.image
}
]);
expect(result).toEqual([
'http://example.com/chat/app/old.pdf',
'http://example.com/chat/app/new.png'
]);
expect(state.toStoreRecord().files).toEqual([
{
key: 'chat/app/old.pdf',
name: 'old.pdf',
type: ChatFileTypeEnum.file
},
{
key: 'chat/app/new.png',
name: 'new.png',
type: ChatFileTypeEnum.image
}
]);
});
it('should throw when file variable update value is not an array', async () => {
const state = await createFileState();
await expect(state.set('files', 'https://external.example.com/report.pdf')).rejects.toThrow(
'File variable value must be an array'
);
});
});
describe('dispatchUpdateVariable — Number 公式', () => {
it.each([
['+', 10, 3, 13],
......@@ -171,6 +326,39 @@ describe('dispatchUpdateVariable — Boolean', () => {
});
});
describe('dispatchUpdateVariable — Store variables', () => {
it('should encrypt password values when writing storeVariables', async () => {
const variables = { pwd: 'old' };
const storeVariables: Record<string, any> = {};
await dispatchUpdateVariable(
buildProps(
variables,
[
{
variable: ref('pwd'),
value: ['', 'new-secret'],
valueType: WorkflowIOValueTypeEnum.string,
renderType: FlowNodeInputTypeEnum.input
}
],
{
storeVariables,
chatConfig: {
variables: [{ key: 'pwd', type: VariableInputEnum.password }]
}
}
)
);
expect(variables.pwd).toBe('new-secret');
expect(storeVariables.pwd).toHaveProperty('value', '');
expect(storeVariables.pwd).toHaveProperty('secret');
expect(typeof storeVariables.pwd.secret).toBe('string');
expect(storeVariables.pwd.secret).not.toBe('new-secret');
});
});
describe('dispatchUpdateVariable — Array', () => {
it('append:旧值数组', async () => {
const variables = { list: [1, 2] };
......@@ -441,7 +629,7 @@ describe('dispatchUpdateVariable — 老数据向前兼容(无新字段)', (
expect(variables.mixed).toEqual({ x: 1 });
});
it('返回值结构:newVariables + updateVarResult 与老接口一致', async () => {
it('返回值结构:仅返回 updateVarResult,变量由 variableState 统一保存', async () => {
const variables = { a: 0, b: 0 };
const res = await dispatchUpdateVariable(
buildProps(variables, [
......@@ -459,8 +647,9 @@ describe('dispatchUpdateVariable — 老数据向前兼容(无新字段)', (
}
])
);
expect((res as any).newVariables).toBe(variables);
expect((res as any).newVariables).toBeUndefined();
expect((res as any).responseData?.updateVarResult).toEqual([1, null]);
expect(variables.a).toBe(1);
});
});
......@@ -624,4 +813,48 @@ describe('dispatchUpdateVariable — 多条 update 的顺序语义', () => {
// 第一条:counter = 5;第二条:5 + 3 = 8
expect(variables.counter).toBe(8);
});
it('后一条模板输入读取到前一条更新后的全局变量', async () => {
const variables = { source: 'old', target: '' };
await dispatchUpdateVariable(
buildProps(variables, [
{
variable: ref('source'),
value: ['', 'new'],
valueType: WorkflowIOValueTypeEnum.string,
renderType: FlowNodeInputTypeEnum.input
},
{
variable: ref('target'),
value: ['', '{{source}}'],
valueType: WorkflowIOValueTypeEnum.string,
renderType: FlowNodeInputTypeEnum.input
}
])
);
expect(variables.target).toBe('new');
});
it('后一条 reference 读取到前一条更新后的全局变量', async () => {
const variables = { source: 'old', target: '' };
await dispatchUpdateVariable(
buildProps(variables, [
{
variable: ref('source'),
value: ['', 'new'],
valueType: WorkflowIOValueTypeEnum.string,
renderType: FlowNodeInputTypeEnum.input
},
{
variable: ref('target'),
value: ref('source'),
valueType: WorkflowIOValueTypeEnum.string,
renderType: FlowNodeInputTypeEnum.reference
}
])
);
expect(variables.target).toBe('new');
});
});
......@@ -7,18 +7,15 @@ import {
filterToolNodeIdByEdges,
getHistories,
checkQuoteQAValue,
runtimeSystemVar2StoreType,
filterSystemVariables,
formatHttpError,
rewriteRuntimeWorkFlow,
getNodeErrResponse,
safePoints,
getSystemVariables
safePoints
} from '@fastgpt/service/core/workflow/dispatch/utils';
import { encryptSecret } from '@fastgpt/service/common/secret/aes256gcm';
import { WorkflowIOValueTypeEnum } from '@fastgpt/global/core/workflow/constants';
import { WorkflowVariableState } from '../../../../core/workflow/dispatch/utils/variables';
import { responseWrite } from '@fastgpt/service/common/response';
import { ChatRoleEnum } from '@fastgpt/global/core/chat/constants';
import { ChatFileTypeEnum, ChatRoleEnum } from '@fastgpt/global/core/chat/constants';
import type { ChatItemMiniType } from '@fastgpt/global/core/chat/type';
import { NodeOutputKeyEnum, VariableInputEnum } from '@fastgpt/global/core/workflow/constants';
import {
......@@ -59,6 +56,11 @@ vi.mock('@fastgpt/service/core/chat/utils', () => ({
presignVariablesFileUrls: (...args: any[]) => mockPresignVariablesFileUrls(...args)
}));
const mockGetChatFilePreviewUrl = vi.fn(async (key: string) => `http://example.com/${key}`);
vi.mock('@fastgpt/service/common/s3/sources/chat', () => ({
createChatFilePreviewUrlGetter: () => mockGetChatFilePreviewUrl
}));
describe('getWorkflowResponseWrite', () => {
const mockRes = () => {
const res: any = { closed: false };
......@@ -533,81 +535,67 @@ describe('checkQuoteQAValue', () => {
});
});
describe('runtimeSystemVar2StoreType', () => {
it('should remove system variables', () => {
const variables = {
userId: 'u1',
appId: 'a1',
chatId: 'c1',
responseChatItemId: 'r1',
histories: [],
cTime: '2024-01-01',
customVar: 'keep'
};
const result = runtimeSystemVar2StoreType({ variables });
expect(result.userId).toBeUndefined();
expect(result.appId).toBeUndefined();
expect(result.chatId).toBeUndefined();
expect(result.responseChatItemId).toBeUndefined();
expect(result.histories).toBeUndefined();
expect(result.cTime).toBeUndefined();
expect(result.customVar).toBe('keep');
describe('WorkflowVariableState file store conversion', () => {
const createFileVariableState = (inputVariables: Record<string, unknown> = {}) =>
WorkflowVariableState.create({
timezone: 'Asia/Shanghai',
runningAppInfo: {
id: 'appId',
teamId: 'teamId',
tmbId: 'tmbId',
name: 'app'
},
uid: 'uid',
chatId: 'chatId',
variablesConfig: [
{
key: 'files',
type: VariableInputEnum.file
} as any
],
inputVariables
});
it('should remove custom removeObj keys', () => {
const variables = { key1: 'v1', key2: 'v2' };
const result = runtimeSystemVar2StoreType({
variables,
removeObj: { key1: 'any' }
});
expect(result.key1).toBeUndefined();
expect(result.key2).toBe('v2');
});
it('should convert unknown runtime urls to external file store values', async () => {
const state = await createFileVariableState();
it('should encrypt password variables', () => {
const variables = { pwd: 'secret123' };
const result = runtimeSystemVar2StoreType({
variables,
userVariablesConfigs: [{ key: 'pwd', type: VariableInputEnum.password } as any]
});
expect(result.pwd).toHaveProperty('value', '');
expect(result.pwd).toHaveProperty('secret');
expect(typeof result.pwd.secret).toBe('string');
expect(result.pwd.secret.split(':').length).toBe(3);
});
await state.set('files', ['https://preview.example.com/doc.pdf']);
it('should skip non-string password values', () => {
const variables = { pwd: 123 };
const result = runtimeSystemVar2StoreType({
variables,
userVariablesConfigs: [{ key: 'pwd', type: VariableInputEnum.password } as any]
});
expect(result.pwd).toBe(123);
expect(state.toStoreRecord().files).toEqual([
{
url: 'https://preview.example.com/doc.pdf',
name: 'doc.pdf',
type: ChatFileTypeEnum.file
}
]);
});
it('should handle file variables with valid URLs', () => {
const variables = {
myFile: ['https://example.com/fastgpt-private/path/to/file.jpg']
};
const result = runtimeSystemVar2StoreType({
variables,
userVariablesConfigs: [{ key: 'myFile', type: VariableInputEnum.file } as any]
});
expect(result.myFile).toHaveLength(1);
expect(result.myFile[0]).toHaveProperty('key', 'path/to/file.jpg');
expect(result.myFile[0]).toHaveProperty('name', 'file.jpg');
expect(result.myFile[0]).toHaveProperty('id', 'file');
it('should convert runtime urls to file store values when file metadata is provided', async () => {
const state = await createFileVariableState({
files: [
{
key: 'chat/app/a.png',
name: 'a.png',
type: ChatFileTypeEnum.image
}
]
});
const runtimeUrls = state.get('files') as string[];
it('should filter out invalid URLs in file variables', () => {
const variables = {
myFile: ['not-a-url']
};
const result = runtimeSystemVar2StoreType({
variables,
userVariablesConfigs: [{ key: 'myFile', type: VariableInputEnum.file } as any]
});
expect(result.myFile).toHaveLength(0);
await state.set('files', [runtimeUrls[0], 'https://external.example.com/report.unknown']);
expect(state.toStoreRecord().files).toEqual([
{
key: 'chat/app/a.png',
name: 'a.png',
type: ChatFileTypeEnum.image
},
{
url: 'https://external.example.com/report.unknown',
name: 'report.unknown',
type: ChatFileTypeEnum.file
}
]);
});
});
......@@ -1021,11 +1009,10 @@ describe('getNodeErrResponse', () => {
const result = getNodeErrResponse({
error: 'fail',
runTimes: 3,
newVariables: { a: 1 },
system_memories: { mem: 'val' }
});
expect(result[DispatchNodeResponseKeyEnum.runTimes]).toBe(3);
expect(result[DispatchNodeResponseKeyEnum.newVariables]).toEqual({ a: 1 });
expect(result[DispatchNodeResponseKeyEnum.newVariables]).toBeUndefined();
expect(result[DispatchNodeResponseKeyEnum.memories]).toEqual({ mem: 'val' });
});
......@@ -1065,306 +1052,3 @@ describe('safePoints', () => {
expect(safePoints(undefined)).toBe(0);
});
});
describe('getSystemVariables', () => {
const baseArgs = {
timezone: 'Asia/Shanghai',
runningAppInfo: { id: 'app-123' } as any,
chatId: 'chat-1',
responseChatItemId: 'rci-1',
histories: [],
uid: 'user-1',
chatConfig: {} as any,
variables: {}
};
it('should return only system variables when chatConfig has no variables', async () => {
const result = await getSystemVariables(baseArgs);
expect(result.userId).toBe('user-1');
expect(result.appId).toBe('app-123');
expect(result.chatId).toBe('chat-1');
expect(result.responseChatItemId).toBe('rci-1');
expect(result.histories).toEqual([]);
expect(typeof result.cTime).toBe('string');
});
it('should return only system variables when chatConfig is undefined', async () => {
const result = await getSystemVariables({
...baseArgs,
chatConfig: undefined as any
});
expect(result.userId).toBe('user-1');
expect(result.appId).toBe('app-123');
expect((result as any).custom).toBeUndefined();
});
it('should coerce runningAppInfo.id to string', async () => {
const result = await getSystemVariables({
...baseArgs,
runningAppInfo: { id: 42 } as any
});
expect(result.appId).toBe('42');
});
it('should default histories to [] when not provided', async () => {
const { histories, ...rest } = baseArgs;
const result = await getSystemVariables(rest as any);
expect(result.histories).toEqual([]);
});
it('should preserve provided histories', async () => {
const histories = [{ obj: 'Human', value: [] }] as any;
const result = await getSystemVariables({
...baseArgs,
histories
});
expect(result.histories).toBe(histories);
});
it('should decrypt password variable from item.label', async () => {
const encrypted = encryptSecret('plain-value');
const result = await getSystemVariables({
...baseArgs,
chatConfig: {
variables: [
{
key: 'pwdKey',
label: 'pwdLabel',
type: VariableInputEnum.password,
valueType: WorkflowIOValueTypeEnum.string
}
]
} as any,
variables: {
pwdLabel: JSON.stringify({ value: '', secret: encrypted })
}
});
expect((result as any).pwdKey).toBe('plain-value');
});
it('should decrypt password variable from item.key when label missing', async () => {
const encrypted = encryptSecret('key-value');
const result = await getSystemVariables({
...baseArgs,
chatConfig: {
variables: [
{
key: 'pwdKey',
label: 'pwdLabel',
type: VariableInputEnum.password,
valueType: WorkflowIOValueTypeEnum.string
}
]
} as any,
variables: {
pwdKey: { value: '', secret: encrypted }
}
});
expect((result as any).pwdKey).toBe('key-value');
});
it('should fall back to defaultValue for password variable', async () => {
const encrypted = encryptSecret('default-value');
const result = await getSystemVariables({
...baseArgs,
chatConfig: {
variables: [
{
key: 'pwdKey',
label: 'pwdLabel',
type: VariableInputEnum.password,
valueType: WorkflowIOValueTypeEnum.string,
defaultValue: { value: '', secret: encrypted }
}
]
} as any,
variables: {}
});
expect((result as any).pwdKey).toBe('default-value');
});
it('should map file variables to their url list', async () => {
mockPresignVariablesFileUrls.mockResolvedValueOnce({
fileKey: [
{ key: 'a', url: 'http://example.com/a' },
{ key: 'b', url: 'http://example.com/b' }
]
});
const result = await getSystemVariables({
...baseArgs,
chatConfig: {
variables: [
{
key: 'fileKey',
label: 'fileLabel',
type: VariableInputEnum.file,
valueType: WorkflowIOValueTypeEnum.arrayString
}
]
} as any,
variables: {
fileKey: [{ key: 'a' }, { key: 'b' }]
}
});
expect((result as any).fileKey).toEqual(['http://example.com/a', 'http://example.com/b']);
});
it('should return undefined for file variable when presign returns no entry', async () => {
mockPresignVariablesFileUrls.mockResolvedValueOnce({});
const result = await getSystemVariables({
...baseArgs,
chatConfig: {
variables: [
{
key: 'fileKey',
label: 'fileLabel',
type: VariableInputEnum.file,
valueType: WorkflowIOValueTypeEnum.arrayString
}
]
} as any,
variables: {}
});
expect((result as any).fileKey).toBeUndefined();
});
it('should use variables[label] when provided (API input)', async () => {
const result = await getSystemVariables({
...baseArgs,
chatConfig: {
variables: [
{
key: 'myKey',
label: 'myLabel',
type: VariableInputEnum.input,
valueType: WorkflowIOValueTypeEnum.string
}
]
} as any,
variables: {
myLabel: 'from-label'
}
});
expect((result as any).myKey).toBe('from-label');
});
it('should use variables[key] when label missing (Web input)', async () => {
const result = await getSystemVariables({
...baseArgs,
chatConfig: {
variables: [
{
key: 'myKey',
label: 'myLabel',
type: VariableInputEnum.input,
valueType: WorkflowIOValueTypeEnum.string
}
]
} as any,
variables: {
myKey: 'from-key'
}
});
expect((result as any).myKey).toBe('from-key');
});
it('should fall back to defaultValue when neither label nor key provided', async () => {
const result = await getSystemVariables({
...baseArgs,
chatConfig: {
variables: [
{
key: 'myKey',
label: 'myLabel',
type: VariableInputEnum.input,
valueType: WorkflowIOValueTypeEnum.string,
defaultValue: 'fallback'
}
]
} as any,
variables: {}
});
expect((result as any).myKey).toBe('fallback');
});
it('should format value by valueType (number)', async () => {
const result = await getSystemVariables({
...baseArgs,
chatConfig: {
variables: [
{
key: 'n',
label: 'nLabel',
type: VariableInputEnum.numberInput,
valueType: WorkflowIOValueTypeEnum.number
}
]
} as any,
variables: {
nLabel: '42'
}
});
expect((result as any).n).toBe(42);
});
it('should prefer label over key when both present', async () => {
const result = await getSystemVariables({
...baseArgs,
chatConfig: {
variables: [
{
key: 'dup',
label: 'dupLabel',
type: VariableInputEnum.input,
valueType: WorkflowIOValueTypeEnum.string
}
]
} as any,
variables: {
dupLabel: 'label-wins',
dup: 'key-loses'
}
});
expect((result as any).dup).toBe('label-wins');
});
it('should process multiple variables in the same call', async () => {
mockPresignVariablesFileUrls.mockResolvedValueOnce({
f: [{ key: 'k', url: 'http://example.com/k' }]
});
const encrypted = encryptSecret('pwd-plain');
const result = await getSystemVariables({
...baseArgs,
chatConfig: {
variables: [
{
key: 'a',
label: 'aLabel',
type: VariableInputEnum.input,
valueType: WorkflowIOValueTypeEnum.string
},
{
key: 'f',
label: 'fLabel',
type: VariableInputEnum.file,
valueType: WorkflowIOValueTypeEnum.arrayString
},
{
key: 'p',
label: 'pLabel',
type: VariableInputEnum.password,
valueType: WorkflowIOValueTypeEnum.string
}
]
} as any,
variables: {
aLabel: 'alpha',
f: [{ key: 'k' }],
pLabel: JSON.stringify({ value: '', secret: encrypted })
}
});
expect((result as any).a).toBe('alpha');
expect((result as any).f).toEqual(['http://example.com/k']);
expect((result as any).p).toBe('pwd-plain');
});
});
import { describe, expect, it, vi } from 'vitest';
import {
VariableInputEnum,
WorkflowIOValueTypeEnum
} from '@fastgpt/global/core/workflow/constants';
import { ChatFileTypeEnum } from '@fastgpt/global/core/chat/constants';
import { WorkflowVariableState } from '../../../../core/workflow/dispatch/utils/variables';
import { encryptSecret } from '../../../../common/secret/aes256gcm';
import { anyValueDecrypt } from '../../../../common/secret/utils';
const mockGetChatFilePreviewUrl = vi.fn(async (key: string) => `http://preview.local/${key}`);
vi.mock('@fastgpt/service/common/s3/sources/chat', () => ({
createChatFilePreviewUrlGetter: () => mockGetChatFilePreviewUrl
}));
const createState = (props: Partial<Parameters<typeof WorkflowVariableState.create>[0]> = {}) =>
WorkflowVariableState.create({
timezone: 'Asia/Shanghai',
runningAppInfo: {
id: 'appId',
teamId: 'teamId',
tmbId: 'tmbId',
name: 'app'
},
uid: 'uid',
chatId: 'chatId',
variablesConfig: [],
inputVariables: {},
...props
});
describe('WorkflowVariableState', () => {
it('should initialize normal variables and runtime-only system variables', async () => {
const state = await createState({
variablesConfig: [
{
key: 'name',
type: VariableInputEnum.input,
valueType: WorkflowIOValueTypeEnum.string,
defaultValue: 'default'
} as any
],
inputVariables: { name: 123 },
externalVariables: { externalOnly: 'external' }
});
expect(state.get('name')).toBe('123');
expect(state.get('userId')).toBe('uid');
expect(state.get('externalOnly')).toBe('external');
expect(state.toStoreRecord()).toEqual({ name: '123' });
});
it('should encrypt password store value while keeping runtime plain text', async () => {
const state = await createState({
variablesConfig: [
{
key: 'pwd',
type: VariableInputEnum.password,
valueType: WorkflowIOValueTypeEnum.string
} as any
]
});
await state.set('pwd', 'new-secret');
expect(state.get('pwd')).toBe('new-secret');
expect(state.toStoreRecord().pwd).toMatchObject({ value: '' });
expect((state.toStoreRecord().pwd as any).secret).toEqual(expect.any(String));
expect((state.toStoreRecord().pwd as any).secret).not.toBe('new-secret');
});
it('should keep encrypted password object readable and storable after initialization', async () => {
const state = await createState({
variablesConfig: [
{
key: 'pwd',
type: VariableInputEnum.password,
valueType: WorkflowIOValueTypeEnum.string
} as any
],
inputVariables: {
pwd: {
value: '',
secret: encryptSecret('old-secret')
}
}
});
expect(state.get('pwd')).toBe('old-secret');
expect(anyValueDecrypt(state.toStoreRecord().pwd)).toBe('old-secret');
});
it('should not double encrypt password when initialized from stored JSON string', async () => {
const state = await createState({
variablesConfig: [
{
key: 'pwd',
type: VariableInputEnum.password,
valueType: WorkflowIOValueTypeEnum.string
} as any
],
inputVariables: {
pwd: JSON.stringify({
value: '',
secret: encryptSecret('old-secret')
})
}
});
expect(state.get('pwd')).toBe('old-secret');
expect(anyValueDecrypt(state.toStoreRecord().pwd)).toBe('old-secret');
});
it('should convert key files to runtime urls and keep store value clean', async () => {
const state = await createState({
variablesConfig: [
{
key: 'files',
type: VariableInputEnum.file
} as any
],
inputVariables: {
files: [
{
key: 'chat/app/a.png',
name: 'a.png',
type: ChatFileTypeEnum.image,
url: 'http://preview.local/should-not-store'
},
{
url: 'data:image/png;base64,abc',
name: 'base64.png',
type: ChatFileTypeEnum.image
}
]
}
});
expect(state.get('files')).toEqual(['http://preview.local/chat/app/a.png']);
expect(state.toStoreRecord().files).toEqual([
{
key: 'chat/app/a.png',
name: 'a.png',
type: ChatFileTypeEnum.image
}
]);
});
it('should keep external url files clean and infer string urls on initialization', async () => {
const state = await createState({
variablesConfig: [
{
key: 'files',
type: VariableInputEnum.file
} as any,
{
key: 'missingFiles',
type: VariableInputEnum.file
} as any
],
inputVariables: {
files: [
{
id: 'file',
type: ChatFileTypeEnum.file,
name: 'file.jpg',
url: 'https://example.com/files/file.jpg'
},
'https://preview.example.com/doc.pdf'
]
}
});
expect(state.toStoreRecord().files).toEqual([
{
type: ChatFileTypeEnum.file,
name: 'file.jpg',
url: 'https://example.com/files/file.jpg'
},
{
type: ChatFileTypeEnum.file,
name: 'doc.pdf',
url: 'https://preview.example.com/doc.pdf'
}
]);
expect(state.toStoreRecord().missingFiles).toEqual([]);
});
it('should keep legacy file store values without type and infer metadata', async () => {
const state = await createState({
variablesConfig: [
{
key: 'files',
type: VariableInputEnum.file
} as any
],
inputVariables: {
files: [
{
key: 'chat/app/legacy.png',
name: 'legacy.png'
},
{
url: 'https://example.com/files/report.pdf',
name: 'report.pdf'
}
]
}
});
expect(state.get('files')).toEqual([
'http://preview.local/chat/app/legacy.png',
'https://example.com/files/report.pdf'
]);
expect(state.toStoreRecord().files).toEqual([
{
key: 'chat/app/legacy.png',
name: 'legacy.png',
type: ChatFileTypeEnum.image
},
{
url: 'https://example.com/files/report.pdf',
name: 'report.pdf',
type: ChatFileTypeEnum.file
}
]);
});
it('should restore parent file metadata from runtime url in child state', async () => {
const parent = await createState({
variablesConfig: [
{
key: 'files',
type: VariableInputEnum.file
} as any
],
inputVariables: {
files: [
{
key: 'chat/app/parent.pdf',
name: 'parent.pdf',
type: ChatFileTypeEnum.file
}
]
}
});
const [runtimeUrl] = parent.get('files') as string[];
const child = await createState({
variablesConfig: [
{
key: 'childFiles',
type: VariableInputEnum.file
} as any
],
sourceVariableState: parent
});
await child.set('childFiles', [runtimeUrl]);
expect(child.toStoreRecord().childFiles).toEqual([
{
key: 'chat/app/parent.pdf',
name: 'parent.pdf',
type: ChatFileTypeEnum.file
}
]);
});
it('should restore parent file metadata from runtime url when initializing child state', async () => {
const parent = await createState({
variablesConfig: [
{
key: 'files',
type: VariableInputEnum.file
} as any
],
inputVariables: {
files: [
{
key: 'chat/app/parent-init.png',
name: 'parent-init.png',
type: ChatFileTypeEnum.image
}
]
}
});
const [runtimeUrl] = parent.get('files') as string[];
const child = await createState({
variablesConfig: [
{
key: 'childFiles',
type: VariableInputEnum.file
} as any
],
inputVariables: {
childFiles: [runtimeUrl]
},
sourceVariableState: parent
});
expect(child.get('childFiles')).toEqual(['http://preview.local/chat/app/parent-init.png']);
expect(child.toStoreRecord().childFiles).toEqual([
{
key: 'chat/app/parent-init.png',
name: 'parent-init.png',
type: ChatFileTypeEnum.image
}
]);
});
it('should infer unknown external runtime urls and reject non-array file updates', async () => {
const state = await createState({
variablesConfig: [
{
key: 'files',
type: VariableInputEnum.file
} as any
]
});
await state.set('files', ['https://example.com/report.unknown']);
expect(state.toStoreRecord().files).toEqual([
{
url: 'https://example.com/report.unknown',
name: 'report.unknown',
type: ChatFileTypeEnum.file
}
]);
await expect(state.set('files', 'https://example.com/report.pdf')).rejects.toThrow(
'File variable value must be an array'
);
});
});
......@@ -141,7 +141,6 @@ export const putFileToS3 = async ({
maxSize?: number;
t: any;
}) => {
console.log(headers);
try {
const res = await axios.put(url, file, {
headers: {
......
import type { DragEvent } from 'react';
import React, { useCallback, useEffect, useMemo, useState, useRef } from 'react';
import type { UserInputFileItemType } from '../../chat/ChatContainer/ChatBox/type';
import type {
FileSelectorInputObjectItemType,
FileSelectorInputValueType,
FileSelectorRenderItemType,
FileSelectorValueItemType
} from './type';
import {
Box,
CircularProgress,
......@@ -31,6 +36,121 @@ import { formatFileSize } from '@fastgpt/global/common/file/tools';
import { WorkflowRuntimeContext } from '@/components/core/chat/ChatContainer/context/workflowRuntimeContext';
import { useSafeTranslation } from '@fastgpt/web/hooks/useSafeTranslation';
import { putFileToS3 } from '@fastgpt/web/common/file/utils';
import {
getFileSelectorDisplayIcon,
inferFileSelectorType,
isFileSelectorCleanValueEcho,
isFileSelectorPreviewUrlMissing,
isFileSelectorUploading,
markFileSelectorUploadError,
markFileSelectorUploading,
markFileSelectorUploadSuccess,
sanitizeFileSelectValue
} from './utils';
import { isEqual } from 'lodash';
type WebkitFileSystemFileEntry = {
isFile: true;
isDirectory: false;
file: (successCallback: (file: File) => void) => void;
};
type WebkitFileSystemDirectoryEntry = {
isFile: false;
isDirectory: true;
createReader: () => WebkitFileSystemDirectoryReader;
};
type WebkitFileSystemEntry = WebkitFileSystemFileEntry | WebkitFileSystemDirectoryEntry;
type WebkitFileSystemDirectoryReader = {
readEntries: (successCallback: (entries: WebkitFileSystemEntry[]) => void) => void;
};
type WebkitDataTransferItem = DataTransferItem & {
webkitGetAsEntry?: () => WebkitFileSystemEntry | null;
};
const getFileSystemEntry = (item?: DataTransferItem): WebkitFileSystemEntry | null =>
((item as WebkitDataTransferItem | undefined)?.webkitGetAsEntry?.() as
| WebkitFileSystemEntry
| null
| undefined) ?? null;
const isFileSelectorInputObject = (
file: FileSelectorInputValueType[number]
): file is FileSelectorInputObjectItemType => !!file && typeof file === 'object';
const findExistingRenderFile = (
file: FileSelectorValueItemType | undefined,
existingFiles: FileSelectorRenderItemType[]
) => {
if (!file) return;
if (file.key) {
return existingFiles.find((item) => item.key === file.key);
}
return existingFiles.find((item) => item.url === file.url);
};
/**
* 将外部 value 转成组件内部渲染态。
*
* FileSelector 对外只暴露可存储值(key/url + name/type),但渲染还需要 id、
* 上传进度、错误、临时预览 URL 等字段。外部重新传入 key-only 存储值时,
* 这里会复用已有的 url/icon/id,避免图片预览在父组件回写时反复闪烁。
*/
const formatFileSelectorInternalValue = (
files: FileSelectorInputValueType,
existingFiles: FileSelectorRenderItemType[] = []
): FileSelectorRenderItemType[] => {
if (!Array.isArray(files)) return [];
return files
.map((file): FileSelectorRenderItemType | undefined => {
const valueFile = sanitizeFileSelectValue([file])[0];
const inputFile = isFileSelectorInputObject(file) ? file : undefined;
const rawFile = inputFile?.rawFile;
if (!valueFile && !rawFile) return;
const existingFile = findExistingRenderFile(valueFile, existingFiles);
const inputUrl = inputFile?.url;
const previewUrl =
(inputUrl && !inputUrl.startsWith('data:') ? inputUrl : valueFile?.url) ||
existingFile?.url;
const renderType = valueFile?.type || inputFile?.type || ChatFileTypeEnum.file;
const fileName =
valueFile?.name ||
inputFile?.name ||
valueFile?.url ||
valueFile?.key ||
rawFile?.name ||
previewUrl ||
'';
const fileIcon = inputFile?.icon || existingFile?.icon;
return {
...valueFile,
...(previewUrl ? { url: previewUrl } : {}),
id: inputFile?.id || existingFile?.id || getNanoid(6),
rawFile,
type: renderType,
name: fileName,
icon: getFileSelectorDisplayIcon({
type: renderType,
url: previewUrl,
icon: fileIcon,
name: fileName,
key: valueFile?.key
}),
status: inputFile?.status ?? 1,
process: inputFile?.process,
error: inputFile?.error
};
})
.filter((file): file is FileSelectorRenderItemType => Boolean(file));
};
const FileSelector = ({
value,
......@@ -47,8 +167,8 @@ const FileSelector = ({
isDisabled = false,
isInvalid = false
}: AppFileSelectConfigType & {
value: UserInputFileItemType[];
onChange: (e: any[]) => void;
value: FileSelectorInputValueType;
onChange: (e: FileSelectorValueItemType[]) => void;
canLocalUpload?: boolean;
canUrlUpload?: boolean;
isDisabled?: boolean;
......@@ -67,13 +187,124 @@ const FileSelector = ({
(v) => v.setFileUploadingCount
);
const lastEmittedValue = useRef<FileSelectorValueItemType[]>();
const skipNextCleanEcho = useRef(false);
const fetchingPreviewUrlKeys = useRef(new Set<string>());
const [fileList, setFileList] = useState<FileSelectorRenderItemType[]>(() =>
formatFileSelectorInternalValue(value)
);
useEffect(() => {
const cleanedValue = sanitizeFileSelectValue(value);
if (
skipNextCleanEcho.current &&
isFileSelectorCleanValueEcho({
value,
cleanedValue,
lastEmittedValue: lastEmittedValue.current
})
) {
skipNextCleanEcho.current = false;
return;
}
skipNextCleanEcho.current = false;
setFileList((currentFiles) => {
const nextFiles = formatFileSelectorInternalValue(value, currentFiles);
return isEqual(nextFiles, currentFiles) ? currentFiles : nextFiles;
});
lastEmittedValue.current = cleanedValue;
if (!isEqual(cleanedValue, value)) {
onChange(cleanedValue);
}
}, [onChange, value]);
const handleChangeFiles = useCallback(
(files: UserInputFileItemType[]) => {
onChange([...files]);
(files: FileSelectorRenderItemType[], emitChange = true) => {
setFileList([...files]);
if (emitChange) {
const cleanedFiles = sanitizeFileSelectValue(files);
lastEmittedValue.current = cleanedFiles;
skipNextCleanEcho.current = true;
onChange(cleanedFiles);
}
},
[onChange]
);
// 后端存储值只保留 key;组件渲染时再为 key-only 文件补临时预览 URL。
// 这里不会触发 onChange,避免把预览 URL 写回全局变量或表单存储值。
useEffect(() => {
if (!appId) return;
const filesNeedPreviewUrl = fileList.filter(
(file): file is FileSelectorRenderItemType & { key: string; url?: undefined } =>
isFileSelectorPreviewUrlMissing(file) && !fetchingPreviewUrlKeys.current.has(file.key)
);
if (filesNeedPreviewUrl.length === 0) return;
let isUnmounted = false;
filesNeedPreviewUrl.forEach((file) => {
fetchingPreviewUrlKeys.current.add(file.key);
});
void Promise.allSettled(
filesNeedPreviewUrl.map(async (file) => {
const key = file.key;
const url = await getPresignedChatFileGetUrl({
key,
appId,
outLinkAuthData
});
return {
key,
url
};
})
)
.then((results) => {
if (isUnmounted) return;
const previewUrlMap = new Map<string, string>();
results.forEach((result) => {
if (result.status === 'fulfilled') {
previewUrlMap.set(result.value.key, result.value.url);
}
});
if (previewUrlMap.size === 0) return;
setFileList((currentFiles) =>
currentFiles.map((file) => {
if (!file.key || file.url) return file;
const previewUrl = previewUrlMap.get(file.key);
if (!previewUrl) return file;
return {
...file,
url: previewUrl,
icon: getFileSelectorDisplayIcon({
...file,
url: previewUrl
})
};
})
);
})
.finally(() => {
filesNeedPreviewUrl.forEach((file) => {
fetchingPreviewUrlKeys.current.delete(file.key);
});
});
return () => {
isUnmounted = true;
};
}, [appId, fileList, outLinkAuthData]);
const fileType = useMemo(() => {
return getUploadFileType({
canSelectFile,
......@@ -122,18 +353,14 @@ const FileSelector = ({
(teamPlanStatus?.standard?.maxUploadFileSize || feConfigs?.uploadFileMaxSize || 500) *
1024 *
1024;
const canSelectFileAmount = maxSelectFiles - value.length;
const canSelectFileAmount = Math.max(maxSelectFiles - fileList.length, 0);
const isMaxSelected = canSelectFileAmount <= 0;
const uploadFiles = useCallback(
async (files: UserInputFileItemType[]) => {
const filterFiles = files.filter((item) => item.status === 0);
async (files: FileSelectorRenderItemType[]) => {
const filterFiles = markFileSelectorUploading(files);
if (filterFiles.length === 0) return;
files.forEach((file) => {
file.status = 1;
file.process = 0;
});
handleChangeFiles(files);
await Promise.allSettled(
......@@ -143,7 +370,7 @@ const FileSelector = ({
try {
// Get Upload Post Presigned URL
const { url, key, headers } = await getUploadChatFilePresignedUrl({
const { url, key, headers, previewUrl } = await getUploadChatFilePresignedUrl({
filename: file.rawFile.name,
appId,
chatId,
......@@ -163,49 +390,59 @@ const FileSelector = ({
item.process = percent;
}
});
handleChangeFiles(files);
handleChangeFiles(files, false);
},
t,
maxSize
});
const previewUrl = await getPresignedChatFileGetUrl({
key: key,
appId,
outLinkAuthData
});
// Update file url and key
files.forEach((item) => {
if (item.id === file.id) {
item.url = previewUrl;
item.key = key;
item.process = 100;
}
markFileSelectorUploadSuccess({
files,
id: file.id,
key,
url: previewUrl
});
handleChangeFiles(files);
} catch (error) {
files.forEach((item) => {
if (item.id === file.id) {
item.error = getErrText(error);
}
markFileSelectorUploadError({
files,
id: file.id,
error: getErrText(error)
});
handleChangeFiles(files);
} finally {
setFileUploadingCount((state) => Math.max(0, state - 1));
}
setFileUploadingCount((state) => state - 1);
})
);
},
[handleChangeFiles, setFileUploadingCount, appId, chatId, fileSelectConfig, outLinkAuthData]
[
handleChangeFiles,
setFileUploadingCount,
appId,
chatId,
fileSelectConfig,
outLinkAuthData,
t,
maxSize
]
);
// Selector props
const [isDragging, setIsDragging] = useState(false);
const onSelectFile = useCallback(
async (files: File[]) => {
if (files.length > maxSelectFiles) {
files = files.slice(0, maxSelectFiles);
const remainingFileAmount = Math.max(maxSelectFiles - fileList.length, 0);
if (remainingFileAmount === 0) {
toast({
status: 'warning',
title: t('chat:file_amount_over', { max: maxSelectFiles })
});
return;
}
if (files.length > remainingFileAmount) {
files = files.slice(0, remainingFileAmount);
toast({
status: 'warning',
title: t('chat:file_amount_over', { max: maxSelectFiles })
......@@ -222,12 +459,12 @@ const FileSelector = ({
const loadFiles = await Promise.all(
filterFilesByMaxSize.map(
(file) =>
new Promise<UserInputFileItemType>((resolve, reject) => {
new Promise<FileSelectorRenderItemType>((resolve, reject) => {
if (file.type.includes('image')) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const item: UserInputFileItemType = {
const item: FileSelectorRenderItemType = {
id: getNanoid(6),
rawFile: file,
type: ChatFileTypeEnum.image,
......@@ -253,11 +490,11 @@ const FileSelector = ({
})
)
);
const newFiles = [...loadFiles, ...value];
const newFiles = [...loadFiles, ...fileList];
handleChangeFiles(newFiles);
uploadFiles(newFiles);
},
[maxSelectFiles, value, handleChangeFiles, uploadFiles, toast, t, maxSize]
[maxSelectFiles, fileList, handleChangeFiles, uploadFiles, toast, t, maxSize]
);
const handleDragEnter = (e: DragEvent<HTMLDivElement>) => {
e.preventDefault();
......@@ -280,24 +517,26 @@ const FileSelector = ({
);
const items = e.dataTransfer.items;
const firstEntry = items[0].webkitGetAsEntry();
const firstEntry = getFileSystemEntry(items[0]);
if (firstEntry?.isDirectory && items.length === 1) {
{
const readFile = (entry: any) => {
return new Promise((resolve) => {
const selectedFiles: File[] = [];
const readFile = (entry: WebkitFileSystemFileEntry) => {
return new Promise<void>((resolve) => {
entry.file((file: File) => {
if (filterTypeReg.test(file?.name)) {
onSelectFile([file]);
selectedFiles.push(file);
}
resolve(file);
resolve();
});
});
};
const traverseFileTree = (dirReader: any) => {
return new Promise((resolve) => {
const traverseFileTree = (dirReader: WebkitFileSystemDirectoryReader) => {
return new Promise<void>((resolve) => {
let fileNum = 0;
dirReader.readEntries(async (entries: any[]) => {
dirReader.readEntries((entries) => {
void (async () => {
for await (const entry of entries) {
if (entry.isFile) {
await readFile(entry);
......@@ -311,22 +550,25 @@ const FileSelector = ({
if (fileNum === 100) {
await traverseFileTree(dirReader);
}
resolve('');
resolve();
})();
});
});
};
for await (const item of items) {
const entry = item.webkitGetAsEntry();
for await (const item of Array.from(items)) {
const entry = getFileSystemEntry(item);
if (entry) {
if (entry.isFile) {
await readFile(entry);
} else if (entry.isDirectory) {
//@ts-ignore
await traverseFileTree(entry.createReader());
}
}
}
if (selectedFiles.length > 0) {
await onSelectFile(selectedFiles);
}
}
} else if (firstEntry?.isFile) {
const files = Array.from(e.dataTransfer.files);
......@@ -363,32 +605,40 @@ const FileSelector = ({
const trimmedUrl = url.trim();
if (trimmedUrl) {
const type = inferFileSelectorType(trimmedUrl);
handleChangeFiles([
...value,
...fileList,
{
id: getNanoid(6),
status: 1,
type: ChatFileTypeEnum.file,
type,
url: trimmedUrl,
name: trimmedUrl,
icon: 'common/link'
icon:
type === ChatFileTypeEnum.image
? trimmedUrl
: getFileSelectorDisplayIcon({
type,
url: trimmedUrl,
name: trimmedUrl
})
}
]);
}
setUrlInput('');
},
[t, toast, handleChangeFiles, value]
[t, toast, handleChangeFiles, fileList]
);
const handleDeleteFile = useCallback(
(id: string) => {
handleChangeFiles(value.filter((file) => file.id !== id));
handleChangeFiles(fileList.filter((file) => file.id !== id));
},
[handleChangeFiles, value]
[handleChangeFiles, fileList]
);
const isUploading = value.some((file) => !file.url && !file.error);
const isUploading = fileList.some(isFileSelectorUploading);
const disabled = isDisabled || isUploading;
return (
......@@ -489,13 +739,13 @@ const FileSelector = ({
</VStack>
{/* Preview */}
{value.length > 0 && (
{fileList.length > 0 && (
<>
<MyDivider />
<VStack>
{value.map((file) => {
const fileIcon =
file.type === ChatFileTypeEnum.image ? file.url : getFileIcon(file?.name);
{fileList.map((file) => {
const fileIcon = getFileSelectorDisplayIcon(file);
const isUploadingFile = isFileSelectorUploading(file);
return (
<Box key={file?.id} w={'full'}>
<HStack py={1} px={3} bg={'white'} borderRadius={'md'} border={'sm'}>
......@@ -513,8 +763,7 @@ const FileSelector = ({
</Box>
{/* Status icon */}
<>
{!!file?.url || !!file?.error || file.process === undefined ? (
{!isUploadingFile ? (
<HStack spacing={1}>
{/* View button - 查看文件 */}
{file?.url && (
......@@ -548,7 +797,6 @@ const FileSelector = ({
/>
</HStack>
)}
</>
</HStack>
{file?.error && (
<Box mt={1} fontSize={'xs'} color={'red.600'}>
......
import type { ChatFileTypeEnum } from '@fastgpt/global/core/chat/constants';
type FileSelectorBaseItemType = {
id?: string;
type?: ChatFileTypeEnum;
name?: string;
key?: string;
url?: string;
};
export type FileSelectorValueItemType = {
type: ChatFileTypeEnum;
name: string;
} & ({ key: string; url?: never } | { key?: never; url: string });
export type FileSelectorRenderItemType = FileSelectorBaseItemType & {
id: string;
rawFile?: File;
type: ChatFileTypeEnum;
name: string;
icon?: string;
status?: 0 | 1;
process?: number;
error?: string;
};
export type FileSelectorInputObjectItemType = FileSelectorBaseItemType & {
rawFile?: File;
icon?: string;
status?: 0 | 1;
process?: number;
error?: string;
};
export type FileSelectorInputItemType = string | FileSelectorInputObjectItemType | null | undefined;
export type FileSelectorInputValueType = FileSelectorInputItemType[];
import { ChatFileTypeEnum } from '@fastgpt/global/core/chat/constants';
import { getFileIcon } from '@fastgpt/global/common/file/icon';
import { imageFileType } from '@fastgpt/global/common/file/constants';
import { isEqual } from 'lodash';
import type {
FileSelectorInputObjectItemType,
FileSelectorInputItemType,
FileSelectorInputValueType,
FileSelectorRenderItemType,
FileSelectorValueItemType
} from './type';
const isFileObject = (file: FileSelectorInputItemType): file is FileSelectorInputObjectItemType =>
!!file && typeof file === 'object';
const imageFileExtensions = imageFileType.split(',').map((item) => item.trim().toLowerCase());
export const inferFileSelectorType = (filename?: string): ChatFileTypeEnum => {
const normalizedName = (() => {
if (!filename) return '';
try {
return decodeURIComponent(new URL(filename).pathname).toLowerCase();
} catch {
return filename.split(/[?#]/)[0].toLowerCase();
}
})();
const extension = normalizedName.match(/\.[^./\\]+$/)?.[0];
return extension && imageFileExtensions.includes(extension)
? ChatFileTypeEnum.image
: ChatFileTypeEnum.file;
};
/**
* 清洗 FileSelector 对外输出的值。
*
* 组件内部会保留 rawFile、base64 icon、上传进度、错误等渲染态字段;
* 对外只允许传递后端可存储的 key/url + name/type,避免 base64 被写入变量或表单值。
*/
export const sanitizeFileSelectValue = (
value: FileSelectorInputValueType = []
): FileSelectorValueItemType[] => {
if (!Array.isArray(value)) return [];
return value
.map<FileSelectorValueItemType | undefined>((file) => {
if (typeof file === 'string') {
const trimmedFile = file.trim();
if (!trimmedFile || trimmedFile.startsWith('data:')) return;
return {
url: trimmedFile,
name: trimmedFile,
type: inferFileSelectorType(trimmedFile)
};
}
if (!isFileObject(file)) return;
const key = file.key || undefined;
const fileUrl = file.url;
const url = fileUrl && !fileUrl.startsWith('data:') ? fileUrl : undefined;
if (!key && !url) return;
const baseFile = {
name: file.name || file.key || file.url || '',
type: file.type || inferFileSelectorType(file.name || file.key || url)
};
if (key) {
return {
...baseFile,
key
};
}
if (url) {
return {
...baseFile,
url
};
}
})
.filter(Boolean) as FileSelectorValueItemType[];
};
export const isFileSelectorUploading = (
file: Pick<FileSelectorRenderItemType, 'key' | 'url' | 'error' | 'process' | 'status' | 'rawFile'>
) =>
!file.key &&
!file.url &&
!file.error &&
(!!file.rawFile || file.status === 0 || file.process !== undefined);
export const isFileSelectorPreviewUrlMissing = <
T extends Pick<FileSelectorRenderItemType, 'key' | 'url' | 'error'>
>(
file: T
): file is T & { key: string; url?: undefined; error?: undefined } =>
!!file.key && !file.url && !file.error;
/**
* 统一生成预览区图标。
* 图片优先使用可访问 URL;非图片使用文件名/URL/key 推断出的通用文件图标。
*/
export const getFileSelectorDisplayIcon = (
file: Pick<FileSelectorRenderItemType, 'type' | 'url' | 'icon' | 'name' | 'key'>
) => {
const fallbackIcon = getFileIcon(file.name || file.url || file.key);
if (file.type === ChatFileTypeEnum.image) {
return file.url || file.icon || fallbackIcon;
}
return file.icon || fallbackIcon;
};
export const isFileSelectorCleanValueEcho = ({
value,
cleanedValue,
lastEmittedValue
}: {
value: FileSelectorInputValueType;
cleanedValue: FileSelectorValueItemType[];
lastEmittedValue?: FileSelectorValueItemType[];
}) => isEqual(cleanedValue, lastEmittedValue) && isEqual(value, cleanedValue);
/**
* 将待上传文件从“已选中”推进到“上传中”,并返回这批需要真正上传的文件。
*/
export const markFileSelectorUploading = (files: FileSelectorRenderItemType[]) => {
const uploadingFiles = files.filter((item) => item.status === 0);
uploadingFiles.forEach((file) => {
file.status = 1;
file.process = 0;
delete file.error;
});
return uploadingFiles;
};
/**
* 上传成功后补齐后端 key 和临时预览 URL。后续 emit 时会由 sanitizeFileSelectValue 去掉预览 URL。
*/
export const markFileSelectorUploadSuccess = ({
files,
id,
key,
url
}: {
files: FileSelectorRenderItemType[];
id: string;
key: string;
url: string;
}) => {
files.forEach((item) => {
if (item.id === id) {
item.url = url;
item.key = key;
delete item.process;
}
});
};
/**
* 上传失败只保留错误态,不再继续把该文件当作上传中。
*/
export const markFileSelectorUploadError = ({
files,
id,
error
}: {
files: FileSelectorRenderItemType[];
id: string;
error: string;
}) => {
files.forEach((item) => {
if (item.id === id) {
item.error = error;
delete item.process;
}
});
};
......@@ -14,7 +14,7 @@ import { type AppFileSelectConfigType } from '@fastgpt/global/core/app/type/conf
import { useSystemStore } from '@/web/common/system/useSystemStore';
import { useUserStore } from '@/web/support/user/useUserStore';
import { type OutLinkChatAuthProps } from '@fastgpt/global/support/permission/chat';
import { getPresignedChatFileGetUrl, getUploadChatFilePresignedUrl } from '@/web/common/file/api';
import { getUploadChatFilePresignedUrl } from '@/web/common/file/api';
import { getUploadFileType } from '@fastgpt/global/core/app/constants';
import { putFileToS3 } from '@fastgpt/web/common/file/utils';
......@@ -186,7 +186,7 @@ export const useFileUpload = (props: UseFileUploadOptions) => {
const fileIndex = fileList.findIndex((item) => item.id === file.id)!;
// Get Upload Post Presigned URL
const { url, key, headers, maxSize } = await getUploadChatFilePresignedUrl({
const { url, key, headers, maxSize, previewUrl } = await getUploadChatFilePresignedUrl({
filename: copyFile.rawFile.name,
appId,
chatId,
......@@ -209,12 +209,6 @@ export const useFileUpload = (props: UseFileUploadOptions) => {
maxSize
});
const previewUrl = await getPresignedChatFileGetUrl({
key: key,
appId,
outLinkAuthData
});
// Update file url and key
copyFile.url = previewUrl;
copyFile.key = key;
......
......@@ -41,7 +41,8 @@ import { ChatRoleEnum, ChatStatusEnum } from '@fastgpt/global/core/chat/constant
import {
getInteractiveByHistories,
formatChatValue2InputType,
rewriteHistoriesByInteractiveResponse
rewriteHistoriesByInteractiveResponse,
stripChatValueFileUrls
} from './utils';
import { ChatTypeEnum, textareaMinH } from './constants';
import { SseResponseEventEnum } from '@fastgpt/global/core/workflow/runtime/constants';
......@@ -781,14 +782,6 @@ const ChatBox = ({
val = formatTime2YMDHMS(new Date(val));
} else if (item.type === VariableInputEnum.timeRangeSelect && val) {
val = val.map((item: string) => (item ? formatTime2YMDHMS(new Date(item)) : ''));
} else if (item.type === VariableInputEnum.file && Array.isArray(val)) {
val = val.map((item) => ({
id: item.id,
key: item.key,
url: item.key ? undefined : item.url,
name: item.name,
type: item.type
}));
}
requestVariables[item.key] = valueTypeFormat(val, item.valueType);
});
......@@ -814,7 +807,6 @@ const ChatBox = ({
type: file.type,
name: file.name,
url: file.url,
icon: file.icon || '',
key: file.key || ''
}
})),
......@@ -889,9 +881,10 @@ const ChatBox = ({
const messages = chats2GPTMessages({
messages: newChatList.slice(0, -1).map((item) => {
if (item.obj === ChatRoleEnum.Human) {
item.files?.forEach((file) => {
file.url = '';
});
return {
...item,
value: stripChatValueFileUrls(item.value)
};
}
return item;
}),
......
import { type ChatItemValueItemType } from '@fastgpt/global/core/chat/type';
import type {
ChatItemValueItemType,
UserChatItemValueItemType
} from '@fastgpt/global/core/chat/type';
import type { ChatSiteItemType } from './type';
import { type ChatBoxInputType, type UserInputFileItemType } from './type';
import { getFileIcon } from '@fastgpt/global/common/file/icon';
......@@ -47,6 +50,21 @@ export const formatChatValue2InputType = (value?: ChatItemValueItemType[]): Chat
};
};
export const stripChatValueFileUrls = (value: UserChatItemValueItemType[] = []) =>
value.map((item) => {
if ('file' in item && item.file?.key) {
return {
...item,
file: {
...item.file,
url: ''
}
};
}
return item;
});
// 用于判断当前对话框状态。所以,如果是 child 的 interactive,需要递归去找到最后一个。
export const getInteractiveByHistories = (
chatHistories: ChatSiteItemType[]
......
import React, { useCallback, useState } from 'react';
import { Controller, useFieldArray } from 'react-hook-form';
import { Controller } from 'react-hook-form';
import { Box, Button, Flex, FormControl, FormErrorMessage } from '@chakra-ui/react';
import { useTranslation } from 'next-i18next';
import { useContextSelector } from 'use-context-selector';
......@@ -7,9 +7,6 @@ import { PluginRunContext } from '../context';
import Markdown from '@/components/Markdown';
import MyIcon from '@fastgpt/web/components/common/Icon';
import FormLabel from '@fastgpt/web/components/common/MyBox/FormLabel';
import { useRequest } from '@fastgpt/web/hooks/useRequest';
import { useFileUpload } from '../../ChatBox/hooks/useFileUpload';
import FilePreview from '../../components/FilePreview';
import { type UserChatItemValueItemType } from '@fastgpt/global/core/chat/type';
import QuestionTip from '@fastgpt/web/components/common/MyTooltip/QuestionTip';
import { type ChatBoxInputFormType } from '../../ChatBox/type';
......@@ -37,46 +34,13 @@ const RenderInput = () => {
const onNewChat = useContextSelector(PluginRunContext, (v) => v.onNewChat);
const onSubmit = useContextSelector(PluginRunContext, (v) => v.onSubmit);
const isChatting = useContextSelector(PluginRunContext, (v) => v.isChatting);
const fileSelectConfig = useContextSelector(PluginRunContext, (v) => v.fileSelectConfig);
const instruction = useContextSelector(PluginRunContext, (v) => v.instruction);
const appId = useContextSelector(WorkflowRuntimeContext, (v) => v.appId);
const chatId = useContextSelector(WorkflowRuntimeContext, (v) => v.chatId);
const outLinkAuthData = useContextSelector(WorkflowRuntimeContext, (v) => v.outLinkAuthData);
const { llmModelList } = useSystemStore();
const { control, handleSubmit, reset } = variablesForm;
/* ===> Global files(abandon) */
const fileCtrl = useFieldArray({
control,
name: 'files'
});
const {
File,
onOpenSelectFile,
fileList,
onSelectFile,
uploadFiles,
selectFileIcon,
showSelectFile,
showSelectImg,
removeFiles,
hasFileUploading
} = useFileUpload({
fileSelectConfig,
fileCtrl,
outLinkAuthData,
appId,
chatId
});
useRequest(uploadFiles, {
manual: false,
errorToast: t('common:upload_file_error'),
refreshDeps: [fileList, outLinkAuthData]
});
/* Global files(abandon) <=== */
// Get plugin input components
const formatPluginInputs = useMemoEnhance(() => {
if (histories.length === 0) return pluginInputs;
......@@ -103,7 +67,6 @@ const RenderInput = () => {
const onResetDefault = useCallback(() => {
reset({
files: [],
variables: formatPluginInputs.reduce(
(acc, input) => {
acc[input.key] = input.defaultValue;
......@@ -156,21 +119,14 @@ const RenderInput = () => {
return undefined;
}
})();
// Parse history file
const historyFileList = (() => {
const historyValue = histories[0]?.value as UserChatItemValueItemType[];
return historyValue?.filter((item) => item.file).map((item) => item.file);
})();
reset({
variables: historyVariables,
files: historyFileList
variables: historyVariables
});
}, [histories, formatPluginInputs]);
const formFileUploading = useContextSelector(WorkflowRuntimeContext, (v) => v.fileUploading);
const fileUploading = formFileUploading || hasFileUploading;
const fileUploading = formFileUploading;
const hasHistory = histories.length > 0;
const isDisabledInput = !!hasHistory;
......@@ -190,35 +146,6 @@ const RenderInput = () => {
<Markdown source={instruction} />
</Box>
)}
{/* file select(Abandoned) */}
{(showSelectFile || showSelectImg) && (
<Box mb={5}>
<Flex alignItems={'center'}>
<FormLabel fontSize={'md'} fontWeight={'medium'}>
{t('chat:file_input')}
</FormLabel>
<QuestionTip ml={1} label={t('chat:file_input_tip')} />
<Box flex={1} />
{histories.length === 0 && (
<Button
leftIcon={<MyIcon name={selectFileIcon as any} w={'16px'} />}
variant={'whiteBase'}
isDisabled={isChatting || fileUploading}
onClick={() => {
onOpenSelectFile();
}}
>
{t('chat:select')}
</Button>
)}
<File onSelect={(files) => onSelectFile({ files })} />
</Flex>
<FilePreview
fileList={fileList}
removeFiles={isDisabledInput ? undefined : removeFiles}
/>
</Box>
)}
{/* Filed */}
{formatPluginInputs
.filter((input) => {
......
import React, { type ReactNode, useCallback, useMemo, useRef } from 'react';
import { createContext, useContextSelector } from 'use-context-selector';
import { type PluginRunBoxProps } from './type';
import {
type AIChatItemValueItemType,
type RuntimeUserPromptType
} from '@fastgpt/global/core/chat/type';
import { type AIChatItemValueItemType } from '@fastgpt/global/core/chat/type';
import { type FieldValues } from 'react-hook-form';
import { PluginRunBoxTabEnum } from './constants';
import { useToast } from '@fastgpt/web/hooks/useToast';
......@@ -18,8 +15,6 @@ import { chats2GPTMessages } from '@fastgpt/global/core/chat/adapt';
import { clientGetWorkflowToolRunUserQuery } from '@fastgpt/global/core/workflow/utils';
import { ChatItemContext } from '@/web/core/chat/context/chatItemContext';
import { ChatRecordContext } from '@/web/core/chat/context/chatRecordContext';
import { type AppFileSelectConfigType } from '@fastgpt/global/core/app/type/config.schema';
import { defaultAppSelectFileConfig } from '@fastgpt/global/core/app/constants';
import { mergeChatResponseData } from '@fastgpt/global/core/chat/utils';
import { getErrText } from '@fastgpt/global/common/error/utils';
import { WorkflowRuntimeContextProvider } from '@/components/core/chat/ChatContainer/context/workflowRuntimeContext';
......@@ -28,7 +23,6 @@ type PluginRunContextType = PluginRunBoxProps & {
isChatting: boolean;
onSubmit: (e: ChatBoxInputFormType) => Promise<any>;
instruction: string;
fileSelectConfig: AppFileSelectConfigType;
};
export const PluginRunContext = createContext<
......@@ -38,8 +32,7 @@ export const PluginRunContext = createContext<
onSubmit: function (e: FieldValues): Promise<any> {
throw new Error('Function not implemented.');
},
instruction: '',
fileSelectConfig: defaultAppSelectFileConfig
instruction: ''
});
const PluginRunContextProvider = ({
......@@ -56,10 +49,7 @@ const PluginRunContextProvider = ({
const setChatRecords = useContextSelector(ChatRecordContext, (v) => v.setChatRecords);
const chatRecords = useContextSelector(ChatRecordContext, (v) => v.chatRecords);
const { instruction = '', fileSelectConfig = defaultAppSelectFileConfig } = useMemo(
() => chatConfig || {},
[chatConfig]
);
const instruction = chatConfig?.instruction || '';
const { toast } = useToast();
const chatController = useRef(new AbortController());
......@@ -168,7 +158,7 @@ const PluginRunContextProvider = ({
);
const onSubmit = useCallback(
async ({ variables, files }: ChatBoxInputFormType) => {
async ({ variables }: ChatBoxInputFormType) => {
if (!onStartChat) return;
if (isChatting) {
toast({
......@@ -189,8 +179,7 @@ const PluginRunContextProvider = ({
{
...clientGetWorkflowToolRunUserQuery({
pluginInputs,
variables,
files: files as RuntimeUserPromptType['files']
variables
}),
id: humanChatItemId,
dataId: humanChatItemId,
......@@ -230,10 +219,7 @@ const PluginRunContextProvider = ({
responseChatItemId,
controller: chatController.current,
generatingMessage,
variables: {
files,
...variables
}
variables
});
setChatRecords((state) =>
......@@ -286,8 +272,7 @@ const PluginRunContextProvider = ({
...props,
isChatting,
onSubmit,
instruction,
fileSelectConfig
instruction
};
return (
<WorkflowRuntimeContextProvider
......
......@@ -3,8 +3,7 @@ import type {
GetHelperBotChatRecordsParamsType,
DeleteHelperBotChatParamsType,
GetHelperBotChatRecordsResponseType,
GetHelperBotFilePresignParamsType,
GetHelperBotFilePreviewParamsType
GetHelperBotFilePresignParamsType
} from '@fastgpt/global/openapi/core/chat/helperBot/api';
import type { CreatePostPresignedUrlResponseType } from '@fastgpt/global/common/file/s3/type';
......@@ -16,6 +15,3 @@ export const deleteHelperBotChatRecord = (data: DeleteHelperBotChatParamsType) =
export const getHelperBotFilePresign = (data: GetHelperBotFilePresignParamsType) =>
POST<CreatePostPresignedUrlResponseType>('/core/chat/helperBot/getFilePresign', data);
export const getHelperBotFilePreview = (data: GetHelperBotFilePreviewParamsType) =>
POST<string>('/core/chat/helperBot/getFilePreview', data);
......@@ -12,11 +12,9 @@ import { type UseFieldArrayReturn } from 'react-hook-form';
import type { ChatBoxInputFormType, UserInputFileItemType } from '../../ChatContainer/ChatBox/type';
import { type AppFileSelectConfigType } from '@fastgpt/global/core/app/type/config.schema';
import { useSystemStore } from '@/web/common/system/useSystemStore';
import { type OutLinkChatAuthProps } from '@fastgpt/global/support/permission/chat';
import { getPresignedChatFileGetUrl, getUploadChatFilePresignedUrl } from '@/web/common/file/api';
import { getUploadFileType } from '@fastgpt/global/core/app/constants';
import type { HelperBotTypeEnumType } from '@fastgpt/global/core/chat/helperBot/type';
import { getHelperBotFilePresign, getHelperBotFilePreview } from '../api';
import { getHelperBotFilePresign } from '../api';
import { useRequest } from '@fastgpt/web/hooks/useRequest';
import { putFileToS3 } from '@fastgpt/web/common/file/utils';
......@@ -177,7 +175,7 @@ export const useFileUpload = (props: UseFileUploadOptions) => {
const fileIndex = fileList.findIndex((item) => item.id === file.id)!;
// Get Upload Post Presigned URL
const { url, key, headers, maxSize } = await getHelperBotFilePresign({
const { url, key, headers, maxSize, previewUrl } = await getHelperBotFilePresign({
type,
chatId,
filename: copyFile.rawFile.name
......@@ -198,10 +196,6 @@ export const useFileUpload = (props: UseFileUploadOptions) => {
maxSize
});
const previewUrl = await getHelperBotFilePreview({
key: key
});
// Update file url and key
copyFile.url = previewUrl;
copyFile.key = key;
......
import React, { useEffect } from 'react';
import React from 'react';
import { Box, Button, Flex, FormControl, FormErrorMessage } from '@chakra-ui/react';
import { Controller, useForm, type UseFormHandleSubmit } from 'react-hook-form';
import Markdown from '@/components/Markdown';
......@@ -12,10 +12,22 @@ import InputRender from '@/components/core/app/formRender';
import { nodeInputTypeToInputType } from '@/components/core/app/formRender/utils';
import FormLabel from '@fastgpt/web/components/common/MyBox/FormLabel';
import LeftRadio from '@fastgpt/web/components/common/Radio/LeftRadio';
import { getPresignedChatFileGetUrl } from '@/web/common/file/api';
import { useTranslation } from 'next-i18next';
import { useContextSelector } from 'use-context-selector';
import { WorkflowRuntimeContext } from '@/components/core/chat/ChatContainer/context/workflowRuntimeContext';
import { useTranslation } from 'next-i18next';
type FormFileValue = {
key?: unknown;
url?: unknown;
error?: unknown;
};
const isPendingFileValue = (file: unknown) => {
if (!file || typeof file !== 'object') return false;
const { key, url, error } = file as FormFileValue;
return !key && !url && !error;
};
const DescriptionBox = React.memo(function DescriptionBox({
description
......@@ -80,64 +92,26 @@ export const FormInputComponent = React.memo(function FormInputComponent({
}) {
const { t } = useTranslation();
const { handleSubmit, control, watch, setValue } = useForm({
const { handleSubmit, control, watch } = useForm({
defaultValues
});
const appId = useContextSelector(WorkflowRuntimeContext, (v) => v.appId);
const outLinkAuthData = useContextSelector(WorkflowRuntimeContext, (v) => v.outLinkAuthData);
const runtimeFileUploading = useContextSelector(WorkflowRuntimeContext, (v) => v.fileUploading);
const formValues = watch();
// 刷新文件 URL(处理 TTL 过期)
useEffect(() => {
if (!submitted || !inputForm) return;
const refreshFileUrls = async () => {
for (const item of inputForm) {
if (item.type === 'fileSelect' && defaultValues[item.key]) {
const files = defaultValues[item.key];
if (Array.isArray(files) && files.length > 0 && files[0]?.key) {
try {
const refreshedFiles = await Promise.all(
files.map(async (file: any) => {
if (file.key) {
try {
const newUrl = await getPresignedChatFileGetUrl({
key: file.key,
appId,
outLinkAuthData
});
return {
...file,
url: newUrl,
icon: file.type === 'image' ? newUrl : file.icon
};
} catch (e) {}
}
return file;
})
);
setValue(item.key, refreshedFiles);
} catch (e) {}
}
}
}
};
refreshFileUrls();
}, [submitted, inputForm, defaultValues, appId, outLinkAuthData, setValue]);
const isFileUploading = React.useMemo(() => {
if (runtimeFileUploading) return true;
return inputForm.some((input) => {
if (input.type === 'fileSelect') {
const files = formValues[input.key];
if (Array.isArray(files)) {
return files.some((file: any) => !file.url && !file.error);
return files.some(isPendingFileValue);
}
}
return false;
});
}, [inputForm, formValues]);
}, [inputForm, formValues, runtimeFileUploading]);
return (
<Box>
......
......@@ -11,7 +11,7 @@ import { getErrText } from '@fastgpt/global/common/error/utils';
import { type UseFieldArrayReturn } from 'react-hook-form';
import { useSystemStore } from '@/web/common/system/useSystemStore';
import { useUserStore } from '@/web/support/user/useUserStore';
import { getPresignedChatFileGetUrl, getUploadChatFilePresignedUrl } from '@/web/common/file/api';
import { getUploadChatFilePresignedUrl } from '@/web/common/file/api';
import { putFileToS3 } from '@fastgpt/web/common/file/utils';
import type { PreviewInputFormType, UserInputFileItemType } from './type';
......@@ -128,6 +128,7 @@ export const usePreviewFileUpload = ({ fileCtrl, appId, chatId }: UsePreviewFile
url,
key,
headers,
previewUrl,
maxSize: uploadMaxSize
} = await getUploadChatFilePresignedUrl({
filename: copyFile.rawFile.name,
......@@ -154,12 +155,6 @@ export const usePreviewFileUpload = ({ fileCtrl, appId, chatId }: UsePreviewFile
maxSize: uploadMaxSize
});
// TODO: 替换为 skill 运行预览专用的文件预览 API
const previewUrl = await getPresignedChatFileGetUrl({
key,
appId,
outLinkAuthData: undefined
});
copyFile.url = previewUrl;
copyFile.key = key;
updateFiles(fileIndex, copyFile);
......
import type { ApiRequestProps, ApiResponseType } from '@fastgpt/service/type/next';
import type { ApiRequestProps } from '@fastgpt/service/type/next';
import { NextAPI } from '@/service/middleware/entry';
import type { GetHelperBotFilePresignParamsType } from '@fastgpt/global/openapi/core/chat/helperBot/api';
import type { CreatePostPresignedUrlResponseType } from '@fastgpt/global/common/file/s3/type';
......@@ -23,8 +23,7 @@ const authUploadLimit = (tmbId: string) => {
};
async function handler(
req: ApiRequestProps<getFilePresignBody, getFilePresignQuery>,
res: ApiResponseType<any>
req: ApiRequestProps<getFilePresignBody, getFilePresignQuery>
): Promise<getFilePresignResponse> {
const { type, chatId, filename } = req.body;
......@@ -37,14 +36,12 @@ async function handler(
await authUploadLimit(userId);
const data = await getS3HelperBotSource().createUploadFileURL({
return await getS3HelperBotSource().createUploadFileURL({
type,
chatId,
userId,
filename
});
return data;
}
export default NextAPI(handler);
import type { ApiRequestProps, ApiResponseType } from '@fastgpt/service/type/next';
import type { ApiRequestProps } from '@fastgpt/service/type/next';
import { NextAPI } from '@/service/middleware/entry';
import {
GetHelperBotChatRecordsParamsSchema,
......@@ -8,6 +8,8 @@ import {
import { authHelperBotChatCrud } from '@/service/support/permission/auth/chat';
import { MongoHelperBotChatItem } from '../../../../../../../../packages/service/core/chat/HelperBot/chatItemSchema';
import { parsePaginationRequest } from '@fastgpt/service/common/api/pagination';
import { addPreviewUrlToChatItems } from '@fastgpt/service/core/chat/utils';
import type { ChatItemMiniType } from '@fastgpt/global/core/chat/type';
export type getRecordsQuery = GetHelperBotChatRecordsParamsType;
......@@ -16,8 +18,7 @@ export type getRecordsBody = {};
export type getRecordsResponse = GetHelperBotChatRecordsResponseType;
async function handler(
req: ApiRequestProps<getRecordsBody, getRecordsQuery>,
res: ApiResponseType<any>
req: ApiRequestProps<getRecordsBody, getRecordsQuery>
): Promise<getRecordsResponse> {
const { type, chatId } = GetHelperBotChatRecordsParamsSchema.parse(req.query);
const { userId } = await authHelperBotChatCrud({
......@@ -34,6 +35,7 @@ async function handler(
MongoHelperBotChatItem.countDocuments({ userId, chatId })
]);
histories.reverse();
await addPreviewUrlToChatItems(histories as unknown as ChatItemMiniType[], 'chatFlow');
return {
total,
......
......@@ -45,6 +45,14 @@ async function handler(req: NextApiRequest, res: NextApiResponse): Promise<InitC
// get app and history
const { nodes, chatConfig } = await getAppLatestVersion(app._id, app);
const systemConfigNode = getGuideModule(nodes);
const appChatConfig = getAppChatConfig({
chatConfig,
systemConfigNode,
storeVariables: chat?.variableList,
storeWelcomeText: chat?.welcomeText,
isPublicFetch: false
});
const pluginInputs =
chat?.pluginInputs ??
nodes?.find((node) => node.flowNodeType === FlowNodeTypeEnum.pluginInput)?.inputs ??
......@@ -52,7 +60,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse): Promise<InitC
const variables = await presignVariablesFileUrls({
variables: chat?.variables,
variableConfig: chat?.variableList
variableConfig: appChatConfig.variables
});
return {
......@@ -64,13 +72,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse): Promise<InitC
chatGenerateStatus: chat?.chatGenerateStatus,
hasBeenRead: chat?.hasBeenRead,
app: {
chatConfig: getAppChatConfig({
chatConfig,
systemConfigNode: getGuideModule(nodes),
storeVariables: chat?.variableList,
storeWelcomeText: chat?.welcomeText,
isPublicFetch: false
}),
chatConfig: appChatConfig,
chatModels: getChatModelNameListByModules(nodes),
name: app.name,
avatar: app.avatar,
......
......@@ -41,6 +41,14 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
}
const { nodes, chatConfig } = await getAppLatestVersion(app._id, app);
const systemConfigNode = getGuideModule(nodes);
const appChatConfig = getAppChatConfig({
chatConfig,
systemConfigNode,
storeVariables: chat?.variableList,
storeWelcomeText: chat?.welcomeText,
isPublicFetch: false
});
const pluginInputs =
chat?.pluginInputs ??
nodes?.find((node) => node.flowNodeType === FlowNodeTypeEnum.pluginInput)?.inputs ??
......@@ -48,7 +56,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
const variables = await presignVariablesFileUrls({
variables: chat?.variables,
variableConfig: chat?.variableList
variableConfig: appChatConfig.variables
});
return {
......@@ -60,13 +68,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
chatGenerateStatus: chat?.chatGenerateStatus,
hasBeenRead: chat?.hasBeenRead,
app: {
chatConfig: getAppChatConfig({
chatConfig,
systemConfigNode: getGuideModule(nodes),
storeVariables: chat?.variableList,
storeWelcomeText: chat?.welcomeText,
isPublicFetch: false
}),
chatConfig: appChatConfig,
name: app.name,
avatar: app.avatar,
intro: app.intro,
......
......@@ -60,6 +60,14 @@ async function handler(req: ApiRequestProps<InitTeamChatQueryType>, res: NextApi
// get app and history
const { nodes, chatConfig } = await getAppLatestVersion(app._id, app);
const systemConfigNode = getGuideModule(nodes);
const appChatConfig = getAppChatConfig({
chatConfig,
systemConfigNode,
storeVariables: chat?.variableList,
storeWelcomeText: chat?.welcomeText,
isPublicFetch: false
});
const pluginInputs =
chat?.pluginInputs ??
nodes?.find((node) => node.flowNodeType === FlowNodeTypeEnum.pluginInput)?.inputs ??
......@@ -67,7 +75,7 @@ async function handler(req: ApiRequestProps<InitTeamChatQueryType>, res: NextApi
const variables = await presignVariablesFileUrls({
variables: chat?.variables,
variableConfig: chat?.variableList
variableConfig: appChatConfig.variables
});
jsonRes<InitChatResponseType>(res, {
......@@ -80,13 +88,7 @@ async function handler(req: ApiRequestProps<InitTeamChatQueryType>, res: NextApi
chatGenerateStatus: chat?.chatGenerateStatus,
hasBeenRead: chat?.hasBeenRead,
app: {
chatConfig: getAppChatConfig({
chatConfig,
systemConfigNode: getGuideModule(nodes),
storeVariables: chat?.variableList,
storeWelcomeText: chat?.welcomeText,
isPublicFetch: false
}),
chatConfig: appChatConfig,
chatModels: getChatModelNameListByModules(nodes),
name: app.name,
avatar: app.avatar,
......
......@@ -8,14 +8,13 @@ import { WritePermissionVal } from '@fastgpt/global/support/permission/constant'
import { getTeamPlanStatus } from '@fastgpt/service/support/wallet/sub/utils';
import {
PresignDatasetFilePostUrlBodySchema,
PresignDatasetFilePostUrlResponseSchema,
type PresignDatasetFilePostUrlBody,
type PresignDatasetFilePostUrlResponse
type PresignDatasetFilePostUrlBody
} from '@fastgpt/global/openapi/core/dataset/file/api';
import type { CreatePostPresignedUrlResponseType } from '@fastgpt/global/common/file/s3/type';
async function handler(
req: ApiRequestProps<PresignDatasetFilePostUrlBody>
): Promise<PresignDatasetFilePostUrlResponse> {
): Promise<CreatePostPresignedUrlResponseType> {
const { filename, datasetId } = PresignDatasetFilePostUrlBodySchema.parse(req.body);
const { teamId, userId } = await authDataset({
......@@ -33,13 +32,11 @@ async function handler(
expiredTime: addSeconds(new Date(), 30) // 30s
});
const result = await getS3DatasetSource().createUploadDatasetFileURL({
return getS3DatasetSource().createUploadDatasetFileURL({
datasetId,
filename,
maxFileSize: planStatus.standard?.maxUploadFileSize ?? global.feConfigs.uploadFileMaxSize
});
return PresignDatasetFilePostUrlResponseSchema.parse(result);
}
export default NextAPI(handler);
......@@ -2,12 +2,12 @@ import { POST } from '@/web/common/api/request';
import type {
GetPreviewChunksBody,
GetPreviewChunksResponse,
PresignDatasetFilePostUrlBody,
PresignDatasetFilePostUrlResponse
PresignDatasetFilePostUrlBody
} from '@fastgpt/global/openapi/core/dataset/file/api';
import type { CreatePostPresignedUrlResponseType } from '@fastgpt/global/common/file/s3/type';
export const getUploadDatasetFilePresignedUrl = (params: PresignDatasetFilePostUrlBody) =>
POST<PresignDatasetFilePostUrlResponse>('/core/dataset/file/presignDatasetFilePostUrl', params);
POST<CreatePostPresignedUrlResponseType>('/core/dataset/file/presignDatasetFilePostUrl', params);
export const getPreviewChunks = (data: GetPreviewChunksBody) =>
POST<GetPreviewChunksResponse>('/core/dataset/file/getPreviewChunks', data, {
......
import { describe, expect, it } from 'vitest';
import type { FileSelectorRenderItemType } from '@/components/core/app/FileSelector/type';
import {
getFileSelectorDisplayIcon,
inferFileSelectorType,
isFileSelectorCleanValueEcho,
isFileSelectorPreviewUrlMissing,
isFileSelectorUploading,
markFileSelectorUploadError,
markFileSelectorUploading,
markFileSelectorUploadSuccess,
sanitizeFileSelectValue
} from '@/components/core/app/FileSelector/utils';
import { ChatFileTypeEnum } from '@fastgpt/global/core/chat/constants';
describe('sanitizeFileSelectValue', () => {
it('清洗 S3 文件对象,移除 base64 预览和上传态字段', () => {
expect(
sanitizeFileSelectValue([
{
id: 'file-id',
key: 'apps/app/chat/file.png',
url: 'https://signed-url.example.com/file.png',
name: 'file.png',
type: ChatFileTypeEnum.image,
icon: 'data:image/png;base64,abc',
rawFile: new File(['file'], 'file.png'),
process: 100,
status: 1,
error: 'ignored'
}
])
).toEqual([
{
key: 'apps/app/chat/file.png',
name: 'file.png',
type: ChatFileTypeEnum.image
}
]);
});
it('保留 URL 上传文件的 url,并兼容非 base64 字符串 URL', () => {
expect(
sanitizeFileSelectValue([
{
id: 'url-id',
url: 'https://example.com/file.pdf',
name: 'https://example.com/file.pdf',
type: ChatFileTypeEnum.file,
icon: 'common/link'
},
'https://example.com/legacy.pdf',
'data:image/png;base64,abc'
])
).toEqual([
{
url: 'https://example.com/file.pdf',
name: 'https://example.com/file.pdf',
type: ChatFileTypeEnum.file
},
{
url: 'https://example.com/legacy.pdf',
name: 'https://example.com/legacy.pdf',
type: ChatFileTypeEnum.file
}
]);
});
it('兼容缺少 type 的历史文件对象,并按文件名推断图片类型', () => {
expect(
sanitizeFileSelectValue([
{
key: 'chat/files/image.png',
name: 'image.png'
},
{
url: 'https://example.com/report.pdf',
name: 'report.pdf'
},
'https://example.com/legacy.jpg'
])
).toEqual([
{
key: 'chat/files/image.png',
name: 'image.png',
type: ChatFileTypeEnum.image
},
{
url: 'https://example.com/report.pdf',
name: 'report.pdf',
type: ChatFileTypeEnum.file
},
{
url: 'https://example.com/legacy.jpg',
name: 'https://example.com/legacy.jpg',
type: ChatFileTypeEnum.image
}
]);
});
it('过滤仅存在于组件内部上传态的未完成文件', () => {
expect(
sanitizeFileSelectValue([
{
id: 'uploading',
name: 'uploading.png',
type: ChatFileTypeEnum.image,
icon: 'data:image/png;base64,abc',
rawFile: new File(['file'], 'uploading.png'),
status: 0,
process: 30
}
])
).toEqual([]);
});
it('空数组返回空数组', () => {
expect(sanitizeFileSelectValue([])).toEqual([]);
});
it('兼容历史脏数据中的 null 和 undefined 文件项', () => {
expect(sanitizeFileSelectValue([null, undefined])).toEqual([]);
});
});
describe('inferFileSelectorType', () => {
it('按 URL 或文件名扩展名推断图片类型,未知类型兜底普通文件', () => {
expect(inferFileSelectorType('https://example.com/image.png?token=1')).toBe(
ChatFileTypeEnum.image
);
expect(inferFileSelectorType('report.unknown')).toBe(ChatFileTypeEnum.file);
});
});
describe('FileSelector upload state', () => {
it('仅将本次待上传文件置为上传态,不影响已完成文件', () => {
const doneFile: FileSelectorRenderItemType = {
id: 'done',
key: 'apps/app/chat/done.png',
name: 'done.png',
type: ChatFileTypeEnum.image,
status: 1,
process: 100
};
const pendingFile: FileSelectorRenderItemType = {
id: 'pending',
name: 'pending.html',
type: ChatFileTypeEnum.file,
status: 0,
process: 80,
error: 'old error',
rawFile: new File(['html'], 'pending.html')
};
const files = [doneFile, pendingFile];
const uploadingFiles = markFileSelectorUploading(files);
expect(uploadingFiles.map((file) => file.id)).toEqual(['pending']);
expect(doneFile.process).toBe(100);
expect(doneFile.status).toBe(1);
expect(pendingFile.status).toBe(1);
expect(pendingFile.process).toBe(0);
expect(pendingFile.error).toBeUndefined();
});
it('有 key 或 url 的文件即使保留历史 process,也不应显示上传中', () => {
expect(
isFileSelectorUploading({
status: 1,
key: 'apps/app/chat/file.png',
process: 100
})
).toBe(false);
expect(
isFileSelectorUploading({
status: 1,
url: 'https://example.com/file.png',
process: 100
})
).toBe(false);
expect(
isFileSelectorUploading({
status: 1,
process: 30
})
).toBe(true);
expect(
isFileSelectorUploading({
status: 1,
error: 'upload failed',
process: 30
})
).toBe(false);
});
it('上传成功或失败后清理 process,避免完成文件继续显示 loading', () => {
const files: FileSelectorRenderItemType[] = [
{
id: 'file-id',
name: 'file.png',
type: ChatFileTypeEnum.image,
status: 1,
process: 100
}
];
markFileSelectorUploadSuccess({
files,
id: 'file-id',
key: 'apps/app/chat/file.png',
url: 'https://signed-url.example.com/file.png'
});
expect(files[0]).toMatchObject({
key: 'apps/app/chat/file.png',
url: 'https://signed-url.example.com/file.png'
});
expect(files[0].process).toBeUndefined();
expect(isFileSelectorUploading(files[0])).toBe(false);
files[0].process = 60;
markFileSelectorUploadError({
files,
id: 'file-id',
error: 'upload failed'
});
expect(files[0].error).toBe('upload failed');
expect(files[0].process).toBeUndefined();
expect(isFileSelectorUploading(files[0])).toBe(false);
});
it('刚选择的本地文件即使还没有 process,也应视为上传中', () => {
expect(
isFileSelectorUploading({
status: 0,
rawFile: new File(['file'], 'image.png')
})
).toBe(true);
});
});
describe('FileSelector display icon', () => {
it('图片历史值缺少预览 url 时,使用文件名图标兜底', () => {
expect(
getFileSelectorDisplayIcon({
type: ChatFileTypeEnum.image,
name: 'image.png',
key: 'chat/files/image.png'
})
).toBe('image');
});
it('非图片 URL 文件缺少名称时,使用 URL 推断文件图标', () => {
expect(
getFileSelectorDisplayIcon({
type: ChatFileTypeEnum.file,
name: '',
url: 'https://example.com/demo.pdf'
})
).toBe('file/fill/pdf');
});
});
describe('FileSelector preview url', () => {
it('只有 key 但缺少 url 的有效文件需要补预览链接', () => {
expect(
isFileSelectorPreviewUrlMissing({
key: 'apps/app/chat/image.png'
})
).toBe(true);
expect(
isFileSelectorPreviewUrlMissing({
key: 'apps/app/chat/image.png',
url: 'https://signed-url.example.com/image.png'
})
).toBe(false);
expect(
isFileSelectorPreviewUrlMissing({
key: 'apps/app/chat/image.png',
error: 'upload failed'
})
).toBe(false);
});
});
describe('FileSelector external sync', () => {
it('后端补充同 key 的预览字段时,不应被当成清洗值回写跳过', () => {
const cleanedValue = [
{
id: 'file-id',
key: 'apps/app/chat/image.png',
name: 'image.png',
type: ChatFileTypeEnum.image
}
];
expect(
isFileSelectorCleanValueEcho({
value: cleanedValue,
cleanedValue,
lastEmittedValue: cleanedValue
})
).toBe(true);
expect(
isFileSelectorCleanValueEcho({
value: [
{
...cleanedValue[0],
url: 'https://signed-url.example.com/image.png'
}
],
cleanedValue,
lastEmittedValue: cleanedValue
})
).toBe(false);
});
});
import { describe, expect, it } from 'vitest';
import { ChatFileTypeEnum } from '@fastgpt/global/core/chat/constants';
import type { ChatItemValueItemType } from '@fastgpt/global/core/chat/type';
import { stripChatValueFileUrls } from '@/components/core/chat/ChatContainer/ChatBox/utils';
describe('stripChatValueFileUrls', () => {
it('removes signed urls from keyed files before sending messages', () => {
const value: ChatItemValueItemType[] = [
{
file: {
type: ChatFileTypeEnum.image,
name: 'image.png',
key: 'chat/files/image.png',
url: 'https://preview.example.com/image.png'
}
},
{
file: {
type: ChatFileTypeEnum.file,
name: 'external.pdf',
url: 'https://external.example.com/external.pdf'
}
},
{
text: {
content: 'hello'
}
}
];
expect(stripChatValueFileUrls(value)).toEqual([
{
file: {
type: ChatFileTypeEnum.image,
name: 'image.png',
key: 'chat/files/image.png',
url: ''
}
},
{
file: {
type: ChatFileTypeEnum.file,
name: 'external.pdf',
url: 'https://external.example.com/external.pdf'
}
},
{
text: {
content: 'hello'
}
}
]);
expect(value[0].file.url).toBe('https://preview.example.com/image.png');
});
});
......@@ -220,9 +220,15 @@ vi.mock('@fastgpt/service/common/s3/sources/chat/index', () => ({
fields: { key: 'mock-key' },
maxSize: 5 * 1024 * 1024
}),
createGetChatFileURL: vi.fn(async ({ key }: { key: string }) => ({
url: `http://localhost:9000/mock-bucket/${key}`
})),
deleteChatFilesByPrefix: vi.fn().mockResolvedValue(undefined),
deleteChatFile: vi.fn().mockResolvedValue(undefined)
}))
})),
createChatFilePreviewUrlGetter: vi.fn(
() => async (key: string) => `http://localhost:9000/mock-bucket/${key}`
)
}));
// Mock S3 initialization
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment