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
...@@ -58,6 +58,11 @@ jobs: ...@@ -58,6 +58,11 @@ jobs:
ghcr.io/${{ github.repository_owner }}/fastgpt-pr:admin_${SHA} ghcr.io/${{ github.repository_owner }}/fastgpt-pr:admin_${SHA}
docker push 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 - name: Add PR comment on success
if: success() && steps.pr.outputs.number != '' if: success() && steps.pr.outputs.number != ''
uses: actions/github-script@v7 uses: actions/github-script@v7
...@@ -82,6 +87,8 @@ jobs: ...@@ -82,6 +87,8 @@ jobs:
\`\`\` \`\`\`
ghcr.io/${{ github.repository_owner }}/fastgpt-pr:admin_${{ steps.pr.outputs.sha }} ghcr.io/${{ github.repository_owner }}/fastgpt-pr:admin_${{ steps.pr.outputs.sha }}
\`\`\` \`\`\`
🕒 Time: ${{ steps.preview_time.outputs.value }}
`; `;
if (existingComment) { if (existingComment) {
......
...@@ -74,6 +74,11 @@ jobs: ...@@ -74,6 +74,11 @@ jobs:
kubectl --kubeconfig "$KUBECONFIG_FILE" annotate deployment/fastgpt-docs-preview \ kubectl --kubeconfig "$KUBECONFIG_FILE" annotate deployment/fastgpt-docs-preview \
originImageName="ghcr.io/${{ github.repository_owner }}/fastgpt-docs-pr:${{ steps.pr.outputs.sha }}" --overwrite 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 - name: Add PR comment on success
if: success() && steps.pr.outputs.number != '' if: success() && steps.pr.outputs.number != ''
uses: actions/github-script@v7 uses: actions/github-script@v7
...@@ -100,6 +105,8 @@ jobs: ...@@ -100,6 +105,8 @@ jobs:
\`\`\` \`\`\`
ghcr.io/${{ github.repository_owner }}/fastgpt-docs-pr:${{ steps.pr.outputs.sha }} ghcr.io/${{ github.repository_owner }}/fastgpt-docs-pr:${{ steps.pr.outputs.sha }}
\`\`\` \`\`\`
🕒 Time: ${{ steps.preview_time.outputs.value }}
`; `;
if (existingComment) { if (existingComment) {
......
...@@ -75,6 +75,11 @@ jobs: ...@@ -75,6 +75,11 @@ jobs:
ghcr.io/${{ github.repository_owner }}/fastgpt-pr:${{ matrix.image }}_${SHA} ghcr.io/${{ github.repository_owner }}/fastgpt-pr:${{ matrix.image }}_${SHA}
docker push 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 - name: Add PR comment on success
if: success() && steps.pr.outputs.number != '' if: success() && steps.pr.outputs.number != ''
uses: actions/github-script@v7 uses: actions/github-script@v7
...@@ -99,6 +104,8 @@ jobs: ...@@ -99,6 +104,8 @@ jobs:
\`\`\` \`\`\`
ghcr.io/${{ github.repository_owner }}/fastgpt-pr:${{ matrix.image }}_${{ steps.pr.outputs.sha }} ghcr.io/${{ github.repository_owner }}/fastgpt-pr:${{ matrix.image }}_${{ steps.pr.outputs.sha }}
\`\`\` \`\`\`
🕒 Time: ${{ steps.preview_time.outputs.value }}
`; `;
if (existingComment) { if (existingComment) {
......
...@@ -4,6 +4,7 @@ export const CreatePostPresignedUrlResponseSchema = z.object({ ...@@ -4,6 +4,7 @@ export const CreatePostPresignedUrlResponseSchema = z.object({
url: z.string().nonempty(), url: z.string().nonempty(),
key: z.string().nonempty(), key: z.string().nonempty(),
headers: z.record(z.string(), z.string()), headers: z.record(z.string(), z.string()),
previewUrl: z.string().nonempty(),
maxSize: z.number().positive().optional() // bytes maxSize: z.number().positive().optional() // bytes
}); });
export type CreatePostPresignedUrlResponseType = z.infer< export type CreatePostPresignedUrlResponseType = z.infer<
......
...@@ -61,11 +61,7 @@ export const valToStr = (val: any) => { ...@@ -61,11 +61,7 @@ export const valToStr = (val: any) => {
}; };
// replace {{variable}} to value // replace {{variable}} to value
export function replaceVariable( export function replaceVariable(text: any, obj: Record<string, any>, depth = 0) {
text: any,
obj: Record<string, string | number | undefined>,
depth = 0
) {
if (typeof text !== 'string') return text; if (typeof text !== 'string') return text;
if (checkStrOversize(text)) { if (checkStrOversize(text)) {
throw new Error('Text length exceeds 100,000,000 characters.'); throw new Error('Text length exceeds 100,000,000 characters.');
......
...@@ -146,6 +146,18 @@ export const UserChatItemFileItemSchema = z.object({ ...@@ -146,6 +146,18 @@ export const UserChatItemFileItemSchema = z.object({
}); });
export type UserChatItemFileItemType = z.infer<typeof UserChatItemFileItemSchema>; 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({ export const UserChatItemValueItemSchema = z.object({
planId: z.string().nullish(), planId: z.string().nullish(),
text: z text: z
......
...@@ -26,7 +26,7 @@ import type { ...@@ -26,7 +26,7 @@ import type {
} from '../template/system/interactive/type'; } from '../template/system/interactive/type';
import { SearchDataResponseItemSchema } from '../../dataset/type'; import { SearchDataResponseItemSchema } from '../../dataset/type';
import type { localeType } from '../../../common/i18n/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 { DatasetSearchModeEnum } from '../../dataset/constants';
import { ChatRoleEnum } from '../../chat/constants'; import { ChatRoleEnum } from '../../chat/constants';
import z from 'zod'; import z from 'zod';
...@@ -48,6 +48,16 @@ export type ExternalProviderType = { ...@@ -48,6 +48,16 @@ export type ExternalProviderType = {
externalWorkflowVariables?: Record<string, string>; 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 */ /* workflow props */
export type ChatDispatchProps = { export type ChatDispatchProps = {
res?: NextApiResponse; res?: NextApiResponse;
...@@ -78,7 +88,7 @@ export type ChatDispatchProps = { ...@@ -78,7 +88,7 @@ export type ChatDispatchProps = {
chatId: string; chatId: string;
responseChatItemId?: string; responseChatItemId?: string;
histories: ChatItemMiniType[]; histories: ChatItemMiniType[];
variables: Record<string, any>; // global variable variableState: WorkflowVariableStateLike; // global variable state
query: UserChatItemValueItemType[]; // trigger query query: UserChatItemValueItemType[]; // trigger query
chatConfig: AppSchemaType['chatConfig']; chatConfig: AppSchemaType['chatConfig'];
lastInteractive?: WorkflowInteractiveResponseType; // last interactive response lastInteractive?: WorkflowInteractiveResponseType; // last interactive response
...@@ -360,7 +370,6 @@ export type DispatchNodeResultType<T = {}, ERR = { [NodeOutputKeyEnum.errorText] ...@@ -360,7 +370,6 @@ export type DispatchNodeResultType<T = {}, ERR = { [NodeOutputKeyEnum.errorText]
[DispatchNodeResponseKeyEnum.assistantResponses]?: AIChatItemValueItemType[]; // Assistant response(Store to db) [DispatchNodeResponseKeyEnum.assistantResponses]?: AIChatItemValueItemType[]; // Assistant response(Store to db)
[DispatchNodeResponseKeyEnum.rewriteHistories]?: ChatItemMiniType[]; [DispatchNodeResponseKeyEnum.rewriteHistories]?: ChatItemMiniType[];
[DispatchNodeResponseKeyEnum.runTimes]?: number; [DispatchNodeResponseKeyEnum.runTimes]?: number;
[DispatchNodeResponseKeyEnum.newVariables]?: Record<string, any>;
[DispatchNodeResponseKeyEnum.memories]?: Record<string, any>; [DispatchNodeResponseKeyEnum.memories]?: Record<string, any>;
[DispatchNodeResponseKeyEnum.interactive]?: InteractiveNodeResponseType; [DispatchNodeResponseKeyEnum.interactive]?: InteractiveNodeResponseType;
[DispatchNodeResponseKeyEnum.customFeedbacks]?: string[]; [DispatchNodeResponseKeyEnum.customFeedbacks]?: string[];
......
...@@ -301,7 +301,7 @@ export const getReferenceVariableValue = ({ ...@@ -301,7 +301,7 @@ export const getReferenceVariableValue = ({
}: { }: {
value?: ReferenceValueType; value?: ReferenceValueType;
nodesMap: Record<string, RuntimeNodeItemType> | Map<string, RuntimeNodeItemType>; nodesMap: Record<string, RuntimeNodeItemType> | Map<string, RuntimeNodeItemType>;
variables: Record<string, any>; variables: Record<string, unknown>;
}) => { }) => {
if (!value) return value; if (!value) return value;
...@@ -394,7 +394,7 @@ export function replaceEditorVariable({ ...@@ -394,7 +394,7 @@ export function replaceEditorVariable({
}: { }: {
text: any; text: any;
nodesMap: Record<string, RuntimeNodeItemType> | Map<string, RuntimeNodeItemType>; nodesMap: Record<string, RuntimeNodeItemType> | Map<string, RuntimeNodeItemType>;
variables: Record<string, any>; // global variables variables: Record<string, unknown>; // runtime global variables
depth?: number; depth?: number;
}) { }) {
const getNode = (nodeId: string) => { const getNode = (nodeId: string) => {
......
...@@ -278,7 +278,10 @@ export const appData2FlowNodeIO = ({ ...@@ -278,7 +278,10 @@ export const appData2FlowNodeIO = ({
[VariableInputEnum.timeRangeSelect]: [FlowNodeInputTypeEnum.timeRangeSelect], [VariableInputEnum.timeRangeSelect]: [FlowNodeInputTypeEnum.timeRangeSelect],
[VariableInputEnum.switch]: [FlowNodeInputTypeEnum.switch], [VariableInputEnum.switch]: [FlowNodeInputTypeEnum.switch],
[VariableInputEnum.password]: [FlowNodeInputTypeEnum.password], [VariableInputEnum.password]: [FlowNodeInputTypeEnum.password],
[VariableInputEnum.file]: [FlowNodeInputTypeEnum.fileSelect], [VariableInputEnum.file]: [
FlowNodeInputTypeEnum.fileSelect,
FlowNodeInputTypeEnum.reference
],
[VariableInputEnum.llmSelect]: [FlowNodeInputTypeEnum.selectLLMModel], [VariableInputEnum.llmSelect]: [FlowNodeInputTypeEnum.selectLLMModel],
[VariableInputEnum.datasetSelect]: [FlowNodeInputTypeEnum.selectDataset], [VariableInputEnum.datasetSelect]: [FlowNodeInputTypeEnum.selectDataset],
[VariableInputEnum.internal]: [FlowNodeInputTypeEnum.hidden], [VariableInputEnum.internal]: [FlowNodeInputTypeEnum.hidden],
......
...@@ -2,13 +2,11 @@ import { PaginationResponseSchema } from '../../../api'; ...@@ -2,13 +2,11 @@ import { PaginationResponseSchema } from '../../../api';
import { PaginationSchema } from '../../../api'; import { PaginationSchema } from '../../../api';
import { import {
HelperBotChatItemSiteSchema, HelperBotChatItemSiteSchema,
type HelperBotChatItemSiteType,
HelperBotTypeEnum, HelperBotTypeEnum,
HelperBotTypeEnumSchema HelperBotTypeEnumSchema
} from '../../../../core/chat/helperBot/type'; } from '../../../../core/chat/helperBot/type';
import { topAgentParamsSchema } from '../../../../core/chat/helperBot/topAgent/type'; import { topAgentParamsSchema } from '../../../../core/chat/helperBot/topAgent/type';
import { z } from 'zod'; import { z } from 'zod';
import type { PaginationResponse } from '../../../api';
import { ChatFileTypeEnum } from '../../../../core/chat/constants'; import { ChatFileTypeEnum } from '../../../../core/chat/constants';
// 分页获取记录 // 分页获取记录
......
...@@ -2,7 +2,6 @@ import { z } from 'zod'; ...@@ -2,7 +2,6 @@ import { z } from 'zod';
import { ObjectIdSchema } from '../../../../common/type/mongo'; import { ObjectIdSchema } from '../../../../common/type/mongo';
import { DatasetSourceReadTypeEnum } from '../../../../core/dataset/constants'; import { DatasetSourceReadTypeEnum } from '../../../../core/dataset/constants';
import { ChunkSettingsSchema } from '../../../../core/dataset/type'; import { ChunkSettingsSchema } from '../../../../core/dataset/type';
import { CreatePostPresignedUrlResponseSchema } from '../../../../common/file/s3/type';
/* ============================================================================ /* ============================================================================
* API: 预览文件分块 * API: 预览文件分块
...@@ -69,10 +68,3 @@ export const PresignDatasetFilePostUrlBodySchema = z.object({ ...@@ -69,10 +68,3 @@ export const PresignDatasetFilePostUrlBodySchema = z.object({
}) })
}); });
export type PresignDatasetFilePostUrlBody = z.infer<typeof PresignDatasetFilePostUrlBodySchema>; 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'; ...@@ -3,9 +3,9 @@ import { TagsMap } from '../../../tag';
import { import {
GetPreviewChunksBodySchema, GetPreviewChunksBodySchema,
GetPreviewChunksResponseSchema, GetPreviewChunksResponseSchema,
PresignDatasetFilePostUrlBodySchema, PresignDatasetFilePostUrlBodySchema
PresignDatasetFilePostUrlResponseSchema
} from './api'; } from './api';
import { CreatePostPresignedUrlResponseSchema } from '../../../../common/file/s3/type';
export const DatasetFilePath: OpenAPIPath = { export const DatasetFilePath: OpenAPIPath = {
'/core/dataset/file/getPreviewChunks': { '/core/dataset/file/getPreviewChunks': {
...@@ -49,7 +49,7 @@ export const DatasetFilePath: OpenAPIPath = { ...@@ -49,7 +49,7 @@ export const DatasetFilePath: OpenAPIPath = {
description: '成功返回预签名上传 URL、key、请求头和最大文件大小', description: '成功返回预签名上传 URL、key、请求头和最大文件大小',
content: { content: {
'application/json': { 'application/json': {
schema: PresignDatasetFilePostUrlResponseSchema schema: CreatePostPresignedUrlResponseSchema
} }
} }
} }
......
...@@ -8,7 +8,7 @@ import { ...@@ -8,7 +8,7 @@ import {
getWorkflowEntryNodeIds, getWorkflowEntryNodeIds,
storeNodes2RuntimeNodes, storeNodes2RuntimeNodes,
filterWorkflowEdges, filterWorkflowEdges,
getReferenceVariableValue, getReferenceVariableValue as baseGetReferenceVariableValue,
formatVariableValByType, formatVariableValByType,
replaceEditorVariable, replaceEditorVariable,
textAdaptGptResponse, textAdaptGptResponse,
...@@ -34,6 +34,17 @@ import type { ...@@ -34,6 +34,17 @@ import type {
import type { StoreNodeItemType } from '@fastgpt/global/core/workflow/type/node'; import type { StoreNodeItemType } from '@fastgpt/global/core/workflow/type/node';
import type { ChatItemMiniType } from '@fastgpt/global/core/chat/type'; 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', () => { describe('extractDeepestInteractive', () => {
it('should return the same interactive when no childrenResponse', () => { it('should return the same interactive when no childrenResponse', () => {
const interactive = { const interactive = {
......
...@@ -735,7 +735,8 @@ describe('appData2FlowNodeIO', () => { ...@@ -735,7 +735,8 @@ describe('appData2FlowNodeIO', () => {
{ key: 'textVar', label: 'Text', type: VariableInputEnum.input, description: '' }, { key: 'textVar', label: 'Text', type: VariableInputEnum.input, description: '' },
{ key: 'numVar', label: 'Number', type: VariableInputEnum.numberInput, description: '' }, { key: 'numVar', label: 'Number', type: VariableInputEnum.numberInput, description: '' },
{ key: 'selectVar', label: 'Select', type: VariableInputEnum.select, 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', () => { ...@@ -751,6 +752,12 @@ describe('appData2FlowNodeIO', () => {
const switchVar = result.inputs.find((i) => i.key === 'switchVar'); const switchVar = result.inputs.find((i) => i.key === 'switchVar');
expect(switchVar?.renderTypeList).toContain(FlowNodeInputTypeEnum.switch); 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', () => { it('should map text input variable with non-string valueType to JSONEditor', () => {
......
import { import { S3Error, InvalidObjectNameError, InvalidXMLError } from 'minio';
Client,
type RemoveOptions,
type CopyConditions,
S3Error,
InvalidObjectNameError,
InvalidXMLError
} from 'minio';
import { import {
type CreatePostPresignedUrlOptions, type CreatePostPresignedUrlOptions,
type CreatePostPresignedUrlParams, type CreatePostPresignedUrlParams,
...@@ -186,6 +179,11 @@ export class S3BaseBucket { ...@@ -186,6 +179,11 @@ export class S3BaseBucket {
}); });
} }
const { url: previewUrl } = await this.createExternalUrl({
key: params.rawKey,
expiredHours
});
return { return {
url: jwtSignS3UploadToken({ url: jwtSignS3UploadToken({
objectKey: params.rawKey, objectKey: params.rawKey,
...@@ -199,6 +197,7 @@ export class S3BaseBucket { ...@@ -199,6 +197,7 @@ export class S3BaseBucket {
headers: { headers: {
'content-type': resolvedUploadConstraints.defaultContentType 'content-type': resolvedUploadConstraints.defaultContentType
}, },
previewUrl,
maxSize: formatMaxFileSize maxSize: formatMaxFileSize
}; };
} catch (error) { } catch (error) {
......
...@@ -58,6 +58,7 @@ export const CreatePostPresignedUrlResultSchema = z.object({ ...@@ -58,6 +58,7 @@ export const CreatePostPresignedUrlResultSchema = z.object({
url: z.string().nonempty(), url: z.string().nonempty(),
key: z.string().nonempty(), key: z.string().nonempty(),
headers: z.record(z.string(), z.string()), headers: z.record(z.string(), z.string()),
previewUrl: z.string().nonempty(),
maxSize: z.number().positive().optional() maxSize: z.number().positive().optional()
}); });
export type CreatePostPresignedUrlResult = z.infer<typeof CreatePostPresignedUrlResultSchema>; export type CreatePostPresignedUrlResult = z.infer<typeof CreatePostPresignedUrlResultSchema>;
......
...@@ -127,3 +127,19 @@ export function getS3ChatSource() { ...@@ -127,3 +127,19 @@ export function getS3ChatSource() {
global.chatBucket = new S3ChatSource(); global.chatBucket = new S3ChatSource();
return global.chatBucket; 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 ...@@ -37,6 +37,7 @@ import type { WorkflowInteractiveResponseType } from '@fastgpt/global/core/workf
import { getFlatAppResponses } from '@fastgpt/global/core/chat/utils'; import { getFlatAppResponses } from '@fastgpt/global/core/chat/utils';
import { getErrText } from '@fastgpt/global/common/error/utils'; import { getErrText } from '@fastgpt/global/common/error/utils';
import { getNanoid } from '@fastgpt/global/common/string/tools'; import { getNanoid } from '@fastgpt/global/common/string/tools';
import { normalizeChatFileStoreValues } from './fileStoreValue';
export type Props = { export type Props = {
chatId: string; chatId: string;
...@@ -73,6 +74,11 @@ const beforeProcess = (props: Props) => { ...@@ -73,6 +74,11 @@ const beforeProcess = (props: Props) => {
// Remove url // Remove url
stripUserContentFileUrls(props.userContent); 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 ({ const afterProcess = async ({
contents, contents,
variables, variables,
...@@ -84,77 +90,79 @@ const afterProcess = async ({ ...@@ -84,77 +90,79 @@ const afterProcess = async ({
variableList?: VariableItemType[]; variableList?: VariableItemType[];
session: ClientSession; session: ClientSession;
}) => { }) => {
const contentFileKeys = contents // 移除 s3 ttl
.map((item) => { {
if (item.value && Array.isArray(item.value)) { const contentFileKeys = contents
return item.value.flatMap((valueItem) => { .map((item) => {
const keys: string[] = []; if (item.value && Array.isArray(item.value)) {
return item.value.flatMap((valueItem) => {
// 1. chat file const keys: string[] = [];
if ('file' in valueItem && valueItem.file?.key) {
keys.push(valueItem.file.key); // 1. chat file
} if ('file' in valueItem && valueItem.file?.key) {
keys.push(valueItem.file.key);
}
// 2. plugin input // 2. query 是特殊格式的(工作流工具 + 表单输入)
if ('text' in valueItem && valueItem.text?.content) { if ('text' in valueItem && valueItem.text?.content) {
try { try {
const parsed = JSON.parse(valueItem.text.content); const parsed = JSON.parse(valueItem.text.content);
// 2.1 plugin input - 数组格式 // 2.1 plugin input - 数组格式
if (Array.isArray(parsed)) { if (Array.isArray(parsed)) {
parsed.forEach((field) => { parsed.forEach((field) => {
if (field.value && Array.isArray(field.value)) { if (field.value && Array.isArray(field.value)) {
field.value.forEach((file: { key: string }) => { field.value.forEach((file: { key: string }) => {
if (file.key && typeof file.key === 'string') { if (file.key && typeof file.key === 'string') {
keys.push(file.key); keys.push(file.key);
} }
}); });
} }
}); });
} }
// 2.2 form input - 对象格式 { "字段名": [{ key, url, ... }] } // 2.2 form input - 对象格式 { "字段名": [{ key, url, ... }] }
else if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { else if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
Object.values(parsed).forEach((fieldValue) => { Object.values(parsed).forEach((fieldValue) => {
if (Array.isArray(fieldValue)) { if (Array.isArray(fieldValue)) {
fieldValue.forEach((file: any) => { fieldValue.forEach((file) => {
if ( if (isFileValueWithKey(file)) {
file && keys.push(file.key);
typeof file === 'object' && }
file.key && });
typeof file.key === 'string' }
) { });
keys.push(file.key); }
} } catch (err) {}
}); }
}
});
}
} catch (err) {}
}
return keys; return keys;
}); });
}
return [];
})
.flat()
.filter(Boolean) as string[];
const variableFileKeys: string[] = [];
if (variables && variableList) {
variableList.forEach((varItem) => {
if (varItem.type === VariableInputEnum.file) {
const varValue = variables[varItem.key];
if (Array.isArray(varValue)) {
variableFileKeys.push(...varValue.map((item) => item.key));
} }
} return [];
}); })
} .flat()
.filter(Boolean) as string[];
const variableFileKeys: string[] = [];
if (variables && variableList) {
variableList.forEach((varItem) => {
if (varItem.type === VariableInputEnum.file) {
const varValue = variables[varItem.key];
if (Array.isArray(varValue)) {
variableFileKeys.push(
...varValue
.map((item) => (isFileValueWithKey(item) ? item.key : undefined))
.filter((key): key is string => typeof key === 'string' && !!key)
);
}
}
});
}
const allFileKeys = [...new Set([...contentFileKeys, ...variableFileKeys])]; const allFileKeys = [...new Set([...contentFileKeys, ...variableFileKeys])];
if (allFileKeys.length > 0) { if (allFileKeys.length > 0) {
await removeS3TTL({ key: allFileKeys, bucketName: 'private', session }); await removeS3TTL({ key: allFileKeys, bucketName: 'private', session });
}
} }
}; };
...@@ -963,6 +971,13 @@ export const updateInteractiveChat = async ({ ...@@ -963,6 +971,13 @@ export const updateInteractiveChat = async ({
}; };
} }
if (item.type === FlowNodeInputTypeEnum.fileSelect) {
return {
...item,
value: normalizeChatFileStoreValues(itemValue)
};
}
return { return {
...item, ...item,
value: itemValue value: itemValue
......
import { ChatRoleEnum } from '@fastgpt/global/core/chat/constants'; import { ChatRoleEnum } from '@fastgpt/global/core/chat/constants';
import type { ChatItemMiniType } from '@fastgpt/global/core/chat/type'; import type { ChatItemMiniType, UserChatItemFileItemType } from '@fastgpt/global/core/chat/type';
import { getS3ChatSource } from '../../common/s3/sources/chat'; import { createChatFilePreviewUrlGetter } from '../../common/s3/sources/chat';
import type { FlowNodeInputItemType } from '@fastgpt/global/core/workflow/type/io'; import type { FlowNodeInputItemType } from '@fastgpt/global/core/workflow/type/io';
import { FlowNodeInputTypeEnum } from '@fastgpt/global/core/workflow/node/constant'; import { FlowNodeInputTypeEnum } from '@fastgpt/global/core/workflow/node/constant';
import type { VariableItemType } from '@fastgpt/global/core/app/type'; import type { VariableItemType } from '@fastgpt/global/core/app/type';
import { VariableInputEnum } from '@fastgpt/global/core/workflow/constants'; 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 ( export const addPreviewUrlToChatItems = async (
histories: ChatItemMiniType[], histories: ChatItemMiniType[],
type: 'chatFlow' | 'workflowTool' type: 'chatFlow' | 'workflowTool'
) => { ) => {
async function addToChatflow(item: ChatItemMiniType) { const getPreviewUrl = createChatFilePreviewUrlGetter();
for await (const value of item.value) {
if ('file' in value && value.file && value.file.key) { async function addPreviewUrlToFileValue(files: ChatFileValueWithPreview[]) {
const { url } = await s3ChatSource.createGetChatFileURL({ await Promise.all(
key: value.file.key, files.map(async (file) => {
external: true if (!file || typeof file !== 'object') return;
});
value.file.url = url; 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) {
await Promise.all(
item.value.map(async (value) => {
if ('file' in value && value.file && value.file.key) {
await addPreviewUrlToFileValue([value.file]);
}
if ('interactive' in value && value.interactive) {
await addToInteractive(value.interactive);
}
})
);
}
async function addToWorkflowTool(item: ChatItemMiniType) { async function addToWorkflowTool(item: ChatItemMiniType) {
if (item.obj !== ChatRoleEnum.Human || !Array.isArray(item.value)) return; if (item.obj !== ChatRoleEnum.Human || !Array.isArray(item.value)) return;
for (let j = 0; j < item.value.length; j++) { await Promise.all(
const value = item.value[j]; item.value.map(async (value, index) => {
if (!('text' in value)) continue; if (!('text' in value)) return;
const inputValueString = value.text?.content || ''; const inputValueString = value.text?.content || '';
const parsedInputValue = JSON.parse(inputValueString) as FlowNodeInputItemType[]; 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;
}
}
item.value[j].text = { await Promise.all(
...value.text, parsedInputValue.map(async (input) => {
content: JSON.stringify(parsedInputValue) if (!input.renderTypeList?.includes(FlowNodeInputTypeEnum.fileSelect)) {
}; return;
} }
const files = formatFileValueList(input.value);
await addPreviewUrlToFileValue(files);
})
);
item.value[index].text = {
...value.text,
content: JSON.stringify(parsedInputValue)
};
})
);
} }
// Presign file urls // Presign file urls
const s3ChatSource = getS3ChatSource(); await Promise.all(
for await (const item of histories) { histories.map(async (item) => {
if (type === 'chatFlow') { if (type === 'chatFlow') {
await addToChatflow(item); await addToChatflow(item);
} else if (type === 'workflowTool') { } else if (type === 'workflowTool') {
await addToWorkflowTool(item); await addToWorkflowTool(item);
} }
} })
);
}; };
// Presign variables file urls // Presign variables file urls
...@@ -72,33 +127,30 @@ export const presignVariablesFileUrls = async ({ ...@@ -72,33 +127,30 @@ export const presignVariablesFileUrls = async ({
variables, variables,
variableConfig variableConfig
}: { }: {
variables?: Record<string, any>; variables?: RuntimeVariableMap;
variableConfig?: VariableItemType[]; variableConfig?: VariableItemType[];
}) => { }) => {
if (!variables || !variableConfig) return variables; if (!variables || !variableConfig) return variables;
const cloneVars = cloneDeep(variables); const cloneVars: RuntimeVariableMap = { ...variables };
const getPreviewUrl = createChatFilePreviewUrlGetter();
await Promise.all( await Promise.all(
variableConfig.map(async (item) => { variableConfig.map(async (item) => {
if (item.type === VariableInputEnum.file) { if (item.type === VariableInputEnum.file) {
const val = cloneVars[item.key]; const files = formatFileValueList(variables[item.key]);
if (Array.isArray(val)) { cloneVars[item.key] = await Promise.all(
cloneVars[item.key] = await Promise.all( files.map(async (file) => {
val.map(async (item) => { if (!file.key) {
if (!item.key) return item; return file;
}
const { url } = await getS3ChatSource().createGetChatFileURL({
key: item.key, return {
external: true ...file,
}); url: await getPreviewUrl(file.key)
};
return { })
...item, ).then((urls) => urls.filter(Boolean));
url
};
})
).then((urls) => urls.filter(Boolean));
}
} }
}) })
); );
......
...@@ -14,10 +14,12 @@ import { ...@@ -14,10 +14,12 @@ import {
import type { NodeInputKeyEnum, NodeOutputKeyEnum } from '@fastgpt/global/core/workflow/constants'; import type { NodeInputKeyEnum, NodeOutputKeyEnum } from '@fastgpt/global/core/workflow/constants';
import { DispatchNodeResponseKeyEnum } from '@fastgpt/global/core/workflow/runtime/constants'; import { DispatchNodeResponseKeyEnum } from '@fastgpt/global/core/workflow/runtime/constants';
import { getHistories } from '../utils'; import { getHistories } from '../utils';
import { WorkflowVariableState } from '../utils/variables';
import { chatValue2RuntimePrompt, runtimePrompt2ChatsValue } from '@fastgpt/global/core/chat/adapt'; import { chatValue2RuntimePrompt, runtimePrompt2ChatsValue } from '@fastgpt/global/core/chat/adapt';
import { type DispatchNodeResultType } from '@fastgpt/global/core/workflow/runtime/type'; import { type DispatchNodeResultType } from '@fastgpt/global/core/workflow/runtime/type';
import { authAppByTmbId } from '../../../../support/permission/app/auth'; import { authAppByTmbId } from '../../../../support/permission/app/auth';
import { ReadPermissionVal } from '@fastgpt/global/support/permission/constant'; import { ReadPermissionVal } from '@fastgpt/global/support/permission/constant';
import { getUserChatInfo } from '../../../../support/user/team/utils';
type Props = ModuleDispatchProps<{ type Props = ModuleDispatchProps<{
[NodeInputKeyEnum.userChatInput]: string; [NodeInputKeyEnum.userChatInput]: string;
...@@ -35,6 +37,7 @@ export const dispatchAppRequest = async (props: Props): Promise<Response> => { ...@@ -35,6 +37,7 @@ export const dispatchAppRequest = async (props: Props): Promise<Response> => {
workflowStreamResponse, workflowStreamResponse,
histories, histories,
query, query,
variableState,
params: { userChatInput, history, app } params: { userChatInput, history, app }
} = props; } = props;
...@@ -58,26 +61,42 @@ export const dispatchAppRequest = async (props: Props): Promise<Response> => { ...@@ -58,26 +61,42 @@ export const dispatchAppRequest = async (props: Props): Promise<Response> => {
const chatHistories = getHistories(history, histories); const chatHistories = getHistories(history, histories);
const { files } = chatValue2RuntimePrompt(query); const { files } = chatValue2RuntimePrompt(query);
const childRunningAppInfo = {
id: String(appData._id),
name: appData.name,
teamId: String(appData.teamId),
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({ const { flowResponses, flowUsages, assistantResponses, system_memories } = await runWorkflow({
...props, ...props,
runningAppInfo: { runningAppInfo: childRunningAppInfo,
id: String(appData._id),
name: appData.name,
teamId: String(appData.teamId),
tmbId: String(appData.tmbId)
},
runtimeNodes: storeNodes2RuntimeNodes( runtimeNodes: storeNodes2RuntimeNodes(
appData.modules, appData.modules,
getWorkflowEntryNodeIds(appData.modules) getWorkflowEntryNodeIds(appData.modules)
), ),
runtimeEdges: storeEdges2RuntimeEdges(appData.edges), runtimeEdges: storeEdges2RuntimeEdges(appData.edges),
variableState: childVariableState,
chatConfig: appData.chatConfig,
histories: chatHistories, histories: chatHistories,
query: runtimePrompt2ChatsValue({ query: runtimePrompt2ChatsValue({
files, files,
text: userChatInput text: userChatInput
}), })
variables: props.variables
}); });
const completeMessages = chatHistories.concat([ const completeMessages = chatHistories.concat([
......
...@@ -56,7 +56,6 @@ export const dispatchLoop = async (props: Props): Promise<Response> => { ...@@ -56,7 +56,6 @@ export const dispatchLoop = async (props: Props): Promise<Response> => {
let assistantResponses: AIChatItemValueItemType[] = []; let assistantResponses: AIChatItemValueItemType[] = [];
const customFeedbacks: string[] = []; const customFeedbacks: string[] = [];
let totalPoints = 0; let totalPoints = 0;
let newVariables: Record<string, any> = props.variables;
let interactiveResponse: WorkflowInteractiveResponseType | undefined = undefined; let interactiveResponse: WorkflowInteractiveResponseType | undefined = undefined;
let index = 0; let index = 0;
...@@ -89,7 +88,6 @@ export const dispatchLoop = async (props: Props): Promise<Response> => { ...@@ -89,7 +88,6 @@ export const dispatchLoop = async (props: Props): Promise<Response> => {
const response = await runWorkflow({ const response = await runWorkflow({
...props, ...props,
lastInteractive: interactiveData?.childrenResponse, lastInteractive: interactiveData?.childrenResponse,
variables: newVariables,
runtimeNodes, runtimeNodes,
runtimeEdges: cloneDeep( runtimeEdges: cloneDeep(
storeEdges2RuntimeEdges(runtimeEdges, interactiveData?.childrenResponse) storeEdges2RuntimeEdges(runtimeEdges, interactiveData?.childrenResponse)
...@@ -112,12 +110,6 @@ export const dispatchLoop = async (props: Props): Promise<Response> => { ...@@ -112,12 +110,6 @@ export const dispatchLoop = async (props: Props): Promise<Response> => {
collectResponseFeedbacks(response, customFeedbacks); collectResponseFeedbacks(response, customFeedbacks);
// Concat new variables
newVariables = {
...newVariables,
...response.newVariables
};
// handle interactive response // handle interactive response
if (response.workflowInteractiveResponse) { if (response.workflowInteractiveResponse) {
interactiveResponse = response.workflowInteractiveResponse; interactiveResponse = response.workflowInteractiveResponse;
...@@ -151,7 +143,6 @@ export const dispatchLoop = async (props: Props): Promise<Response> => { ...@@ -151,7 +143,6 @@ export const dispatchLoop = async (props: Props): Promise<Response> => {
loopDetail: loopResponseDetail, loopDetail: loopResponseDetail,
mergeSignId: props.node.nodeId mergeSignId: props.node.nodeId
}, },
[DispatchNodeResponseKeyEnum.newVariables]: newVariables,
[DispatchNodeResponseKeyEnum.customFeedbacks]: [DispatchNodeResponseKeyEnum.customFeedbacks]:
customFeedbacks.length > 0 ? customFeedbacks : undefined customFeedbacks.length > 0 ? customFeedbacks : undefined
}; };
......
...@@ -80,7 +80,6 @@ export const masterCall = async ({ ...@@ -80,7 +80,6 @@ export const masterCall = async ({
runningAppInfo, runningAppInfo,
chatId, chatId,
uid, uid,
variables,
externalProvider, externalProvider,
stream, stream,
workflowStreamResponse, workflowStreamResponse,
......
...@@ -19,6 +19,7 @@ import { serverGetWorkflowToolRunUserQuery } from '../../../../../../app/tool/wo ...@@ -19,6 +19,7 @@ import { serverGetWorkflowToolRunUserQuery } from '../../../../../../app/tool/wo
import { getWorkflowToolInputsFromStoreNodes } from '@fastgpt/global/core/app/tool/workflowTool/utils'; import { getWorkflowToolInputsFromStoreNodes } from '@fastgpt/global/core/app/tool/workflowTool/utils';
import type { RunWorkflowProps } from '../../../../../../../core/workflow/dispatch'; import type { RunWorkflowProps } from '../../../../../../../core/workflow/dispatch';
import { anyValueDecrypt } from '../../../../../../../common/secret/utils'; import { anyValueDecrypt } from '../../../../../../../common/secret/utils';
import { WorkflowVariableState } from '../../../../utils/variables';
type Props = Pick< type Props = Pick<
RunWorkflowProps, RunWorkflowProps,
...@@ -28,6 +29,9 @@ type Props = Pick< ...@@ -28,6 +29,9 @@ type Props = Pick<
| 'mode' | 'mode'
| 'timezone' | 'timezone'
| 'externalProvider' | 'externalProvider'
| 'uid'
| 'chatId'
| 'responseChatItemId'
| 'runningAppInfo' | 'runningAppInfo'
| 'runningUserInfo' | 'runningUserInfo'
| 'retainDatasetCite' | 'retainDatasetCite'
...@@ -35,7 +39,7 @@ type Props = Pick< ...@@ -35,7 +39,7 @@ type Props = Pick<
| 'workflowDispatchDeep' | 'workflowDispatchDeep'
| 'responseAllData' | 'responseAllData'
| 'responseDetail' | 'responseDetail'
| 'variables' | 'variableState'
> & { > & {
app: { app: {
name: string; name: string;
...@@ -51,7 +55,7 @@ export const dispatchApp = async (props: Props): Promise<DispatchSubAppResponse> ...@@ -51,7 +55,7 @@ export const dispatchApp = async (props: Props): Promise<DispatchSubAppResponse>
runningAppInfo, runningAppInfo,
runningUserInfo, runningUserInfo,
app, app,
variables, variableState,
customAppVariables, customAppVariables,
userChatInput, userChatInput,
...data ...data
...@@ -70,16 +74,25 @@ export const dispatchApp = async (props: Props): Promise<DispatchSubAppResponse> ...@@ -70,16 +74,25 @@ export const dispatchApp = async (props: Props): Promise<DispatchSubAppResponse>
// Rewrite children app variables // Rewrite children app variables
const { externalProvider } = await getUserChatInfo(appData.tmbId); const { externalProvider } = await getUserChatInfo(appData.tmbId);
const childrenRunVariables = { const childRunningAppInfo = {
userId: variables.userId, id: String(appData._id),
appId: String(appData._id), teamId: String(appData.teamId),
chatId: variables.chatId, tmbId: String(appData.tmbId),
responseChatItemId: variables.responseChatItemId, name: appData.name,
histories: [], isChildApp: true
cTime: variables.cTime,
...customAppVariables,
...(externalProvider ? externalProvider.externalWorkflowVariables : {})
}; };
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( const runtimeNodes = rewriteNodeOutputByHistories(
storeNodes2RuntimeNodes(nodes, getWorkflowEntryNodeIds(nodes)) storeNodes2RuntimeNodes(nodes, getWorkflowEntryNodeIds(nodes))
...@@ -88,9 +101,6 @@ export const dispatchApp = async (props: Props): Promise<DispatchSubAppResponse> ...@@ -88,9 +101,6 @@ export const dispatchApp = async (props: Props): Promise<DispatchSubAppResponse>
const { assistantResponses, flowUsages } = await runWorkflow({ const { assistantResponses, flowUsages } = await runWorkflow({
...data, ...data,
uid: variables.userId,
chatId: variables.chatId,
responseChatItemId: variables.responseChatItemId,
runningAppInfo: { runningAppInfo: {
id: String(appData._id), id: String(appData._id),
name: appData.name, name: appData.name,
...@@ -103,7 +113,7 @@ export const dispatchApp = async (props: Props): Promise<DispatchSubAppResponse> ...@@ -103,7 +113,7 @@ export const dispatchApp = async (props: Props): Promise<DispatchSubAppResponse>
runtimeEdges, runtimeEdges,
chatConfig, chatConfig,
histories: [], histories: [],
variables: childrenRunVariables, variableState: childrenVariableState,
query: [ query: [
{ {
text: { text: {
...@@ -138,7 +148,7 @@ export const dispatchPlugin = async (props: Props): Promise<DispatchSubAppRespon ...@@ -138,7 +148,7 @@ export const dispatchPlugin = async (props: Props): Promise<DispatchSubAppRespon
runningAppInfo, runningAppInfo,
runningUserInfo, runningUserInfo,
app, app,
variables, variableState,
customAppVariables, customAppVariables,
userChatInput, userChatInput,
...data ...data
...@@ -157,16 +167,26 @@ export const dispatchPlugin = async (props: Props): Promise<DispatchSubAppRespon ...@@ -157,16 +167,26 @@ export const dispatchPlugin = async (props: Props): Promise<DispatchSubAppRespon
// Rewrite children app variables // Rewrite children app variables
const { externalProvider } = await getUserChatInfo(appData.tmbId); const { externalProvider } = await getUserChatInfo(appData.tmbId);
const childrenRunVariables: Record<string, any> = { const childRunningAppInfo = {
userId: variables.userId, id: String(appData._id),
appId: String(appData._id), teamId: String(appData.teamId || runningAppInfo.teamId),
chatId: variables.chatId, tmbId: String(appData.tmbId || runningAppInfo.tmbId),
responseChatItemId: variables.responseChatItemId, name: appData.name,
histories: [], isChildApp: true
cTime: variables.cTime,
...customAppVariables,
...(externalProvider ? externalProvider.externalWorkflowVariables : {})
}; };
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( const runtimeNodes = storeNodes2RuntimeNodes(nodes, getWorkflowEntryNodeIds(nodes)).map(
(node) => { (node) => {
// Update plugin input value // Update plugin input value
...@@ -213,9 +233,6 @@ export const dispatchPlugin = async (props: Props): Promise<DispatchSubAppRespon ...@@ -213,9 +233,6 @@ export const dispatchPlugin = async (props: Props): Promise<DispatchSubAppRespon
const { flowResponses, flowUsages, runTimes } = await runWorkflow({ const { flowResponses, flowUsages, runTimes } = await runWorkflow({
...data, ...data,
uid: variables.userId,
chatId: variables.chatId,
responseChatItemId: variables.responseChatItemId,
runningAppInfo: { runningAppInfo: {
id: String(appData._id), id: String(appData._id),
// 如果系统插件有 teamId 和 tmbId,则使用系统插件的 teamId 和 tmbId(管理员指定了插件作为系统插件) // 如果系统插件有 teamId 和 tmbId,则使用系统插件的 teamId 和 tmbId(管理员指定了插件作为系统插件)
...@@ -229,7 +246,7 @@ export const dispatchPlugin = async (props: Props): Promise<DispatchSubAppRespon ...@@ -229,7 +246,7 @@ export const dispatchPlugin = async (props: Props): Promise<DispatchSubAppRespon
runtimeEdges, runtimeEdges,
chatConfig, chatConfig,
histories: [], histories: [],
variables: childrenRunVariables, variableState: childrenVariableState,
query: serverGetWorkflowToolRunUserQuery({ query: serverGetWorkflowToolRunUserQuery({
pluginInputs: getWorkflowToolInputsFromStoreNodes(nodes), pluginInputs: getWorkflowToolInputsFromStoreNodes(nodes),
variables: childrenRunVariables variables: childrenRunVariables
......
...@@ -43,7 +43,7 @@ export type Props = { ...@@ -43,7 +43,7 @@ export type Props = {
runningAppInfo: ChatDispatchProps['runningAppInfo']; runningAppInfo: ChatDispatchProps['runningAppInfo'];
chatId: ChatDispatchProps['chatId']; chatId: ChatDispatchProps['chatId'];
uid: ChatDispatchProps['uid']; uid: ChatDispatchProps['uid'];
variables: ChatDispatchProps['variables']; variableState: ChatDispatchProps['variableState'];
workflowStreamResponse: ChatDispatchProps['workflowStreamResponse']; workflowStreamResponse: ChatDispatchProps['workflowStreamResponse'];
}; };
...@@ -54,7 +54,7 @@ export const dispatchTool = async ({ ...@@ -54,7 +54,7 @@ export const dispatchTool = async ({
runningAppInfo, runningAppInfo,
chatId, chatId,
uid, uid,
variables, variableState,
workflowStreamResponse workflowStreamResponse
}: Props): Promise<DispatchSubAppResponse> => { }: Props): Promise<DispatchSubAppResponse> => {
const getNodeResponse = ({ const getNodeResponse = ({
...@@ -115,7 +115,7 @@ export const dispatchTool = async ({ ...@@ -115,7 +115,7 @@ export const dispatchTool = async ({
inputs, inputs,
systemVar: { systemVar: {
user: { user: {
id: variables.userId, id: uid,
username: runningUserInfo.username, username: runningUserInfo.username,
contact: runningUserInfo.contact, contact: runningUserInfo.contact,
membername: runningUserInfo.memberName, membername: runningUserInfo.memberName,
...@@ -136,7 +136,7 @@ export const dispatchTool = async ({ ...@@ -136,7 +136,7 @@ export const dispatchTool = async ({
uId: uid uId: uid
}) })
}, },
time: variables.cTime time: String(variableState.get('cTime') ?? '')
}, },
onMessage: ({ type, content }) => { onMessage: ({ type, content }) => {
if (workflowStreamResponse && content) { if (workflowStreamResponse && content) {
......
...@@ -111,7 +111,7 @@ export type ToolDispatchContext = Pick< ...@@ -111,7 +111,7 @@ export type ToolDispatchContext = Pick<
| 'runningAppInfo' | 'runningAppInfo'
| 'chatId' | 'chatId'
| 'uid' | 'uid'
| 'variables' | 'variableState'
| 'externalProvider' | 'externalProvider'
| 'lang' | 'lang'
| 'requestOrigin' | 'requestOrigin'
...@@ -144,7 +144,7 @@ export const getExecuteTool = ({ ...@@ -144,7 +144,7 @@ export const getExecuteTool = ({
runningAppInfo, runningAppInfo,
chatId, chatId,
uid, uid,
variables, variableState,
externalProvider, externalProvider,
stream, stream,
streamResponseFn, streamResponseFn,
...@@ -330,7 +330,7 @@ export const getExecuteTool = ({ ...@@ -330,7 +330,7 @@ export const getExecuteTool = ({
runningAppInfo, runningAppInfo,
chatId, chatId,
uid, uid,
variables, variableState,
workflowStreamResponse: streamResponseFn workflowStreamResponse: streamResponseFn
}); });
...@@ -356,12 +356,14 @@ export const getExecuteTool = ({ ...@@ -356,12 +356,14 @@ export const getExecuteTool = ({
mode, mode,
timezone, timezone,
externalProvider, externalProvider,
chatId,
uid,
runningAppInfo, runningAppInfo,
runningUserInfo, runningUserInfo,
retainDatasetCite, retainDatasetCite,
maxRunTimes, maxRunTimes,
workflowDispatchDeep, workflowDispatchDeep,
variables variableState
}); });
return { return {
...@@ -384,12 +386,14 @@ export const getExecuteTool = ({ ...@@ -384,12 +386,14 @@ export const getExecuteTool = ({
mode, mode,
timezone, timezone,
externalProvider, externalProvider,
chatId,
uid,
runningAppInfo, runningAppInfo,
runningUserInfo, runningUserInfo,
retainDatasetCite, retainDatasetCite,
maxRunTimes, maxRunTimes,
workflowDispatchDeep, workflowDispatchDeep,
variables variableState
}); });
return { return {
......
...@@ -13,7 +13,8 @@ import { ...@@ -13,7 +13,8 @@ import {
import type { NodeInputKeyEnum } from '@fastgpt/global/core/workflow/constants'; import type { NodeInputKeyEnum } from '@fastgpt/global/core/workflow/constants';
import { NodeOutputKeyEnum } from '@fastgpt/global/core/workflow/constants'; import { NodeOutputKeyEnum } from '@fastgpt/global/core/workflow/constants';
import { DispatchNodeResponseKeyEnum } from '@fastgpt/global/core/workflow/runtime/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 { chatValue2RuntimePrompt, runtimePrompt2ChatsValue } from '@fastgpt/global/core/chat/adapt';
import { type DispatchNodeResultType } from '@fastgpt/global/core/workflow/runtime/type'; import { type DispatchNodeResultType } from '@fastgpt/global/core/workflow/runtime/type';
import { authAppByTmbId } from '../../../../support/permission/app/auth'; import { authAppByTmbId } from '../../../../support/permission/app/auth';
...@@ -44,7 +45,7 @@ export const dispatchRunAppNode = async (props: Props): Promise<Response> => { ...@@ -44,7 +45,7 @@ export const dispatchRunAppNode = async (props: Props): Promise<Response> => {
node: { pluginId: appId, version }, node: { pluginId: appId, version },
workflowStreamResponse, workflowStreamResponse,
params, params,
variables variableState
} = props; } = props;
const { const {
...@@ -101,24 +102,25 @@ export const dispatchRunAppNode = async (props: Props): Promise<Response> => { ...@@ -101,24 +102,25 @@ export const dispatchRunAppNode = async (props: Props): Promise<Response> => {
// Rewrite children app variables // Rewrite children app variables
const { externalProvider } = await getUserChatInfo(appData.tmbId); const { externalProvider } = await getUserChatInfo(appData.tmbId);
const childrenRunVariables = { const childRunningAppInfo = {
...(await getSystemVariables({ id: String(appData._id),
timezone: props.timezone, teamId: appData.teamId,
runningAppInfo: { tmbId: appData.tmbId,
id: String(appData._id), name: appData.name,
teamId: appData.teamId, isChildApp: true
tmbId: appData.tmbId,
name: appData.name
},
chatId: props.chatId,
responseChatItemId: props.responseChatItemId,
histories: chatHistories,
uid: props.uid,
chatConfig,
variables: childrenAppVariables
})),
...(externalProvider ? externalProvider.externalWorkflowVariables : {})
}; };
const childrenVariableState = await WorkflowVariableState.create({
timezone: props.timezone,
runningAppInfo: childRunningAppInfo,
chatId: props.chatId,
responseChatItemId: props.responseChatItemId,
histories: chatHistories,
uid: props.uid,
variablesConfig: chatConfig.variables,
inputVariables: childrenAppVariables,
externalVariables: externalProvider?.externalWorkflowVariables,
sourceVariableState: variableState
});
const childrenInteractive = const childrenInteractive =
lastInteractive?.type === 'childrenInteractive' lastInteractive?.type === 'childrenInteractive'
...@@ -166,7 +168,7 @@ export const dispatchRunAppNode = async (props: Props): Promise<Response> => { ...@@ -166,7 +168,7 @@ export const dispatchRunAppNode = async (props: Props): Promise<Response> => {
runtimeNodes, runtimeNodes,
runtimeEdges, runtimeEdges,
histories: chatHistories, histories: chatHistories,
variables: childrenRunVariables, variableState: childrenVariableState,
query: theQuery, query: theQuery,
chatConfig chatConfig
}); });
......
...@@ -48,10 +48,11 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo ...@@ -48,10 +48,11 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo
params, params,
runningUserInfo, runningUserInfo,
runningAppInfo, runningAppInfo,
variables, variableState,
workflowStreamResponse, workflowStreamResponse,
node: { name, avatar, toolConfig, version, catchError } node: { name, avatar, toolConfig, version, catchError }
} = props; } = props;
const cTime = String(variableState.get('cTime') ?? '');
const { const {
uid: uId, uid: uId,
...@@ -101,7 +102,7 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo ...@@ -101,7 +102,7 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo
inputs, inputs,
systemVar: { systemVar: {
user: { user: {
id: variables.userId, id: props.uid,
username: runningUserInfo.username, username: runningUserInfo.username,
contact: runningUserInfo.contact, contact: runningUserInfo.contact,
membername: runningUserInfo.memberName, membername: runningUserInfo.memberName,
...@@ -118,7 +119,7 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo ...@@ -118,7 +119,7 @@ export const dispatchRunTool = async (props: RunToolProps): Promise<RunToolRespo
version: version || tool.versionList?.[0]?.value || '', version: version || tool.versionList?.[0]?.value || '',
prefix: getS3ChatSource().getToolFilePrefix({ appId, chatId, uId }) prefix: getS3ChatSource().getToolFilePrefix({ appId, chatId, uId })
}, },
time: variables.cTime time: cTime
}, },
onMessage: ({ type, content }) => { onMessage: ({ type, content }) => {
if (workflowStreamResponse && content) { if (workflowStreamResponse && content) {
......
...@@ -44,12 +44,8 @@ import type { ChatNodeUsageType } from '@fastgpt/global/support/wallet/bill/type ...@@ -44,12 +44,8 @@ import type { ChatNodeUsageType } from '@fastgpt/global/support/wallet/bill/type
import { getLogger, LogCategories } from '../../../common/logger'; import { getLogger, LogCategories } from '../../../common/logger';
import { surrenderProcess } from '../../../common/system/tools'; import { surrenderProcess } from '../../../common/system/tools';
import type { DispatchFlowResponse, WorkflowDebugResponse } from './type'; import type { DispatchFlowResponse, WorkflowDebugResponse } from './type';
import { import { rewriteRuntimeWorkFlow, filterOrphanEdges } from './utils';
rewriteRuntimeWorkFlow, import { WorkflowVariableState } from './utils/variables';
runtimeSystemVar2StoreType,
filterOrphanEdges,
getSystemVariables
} from './utils';
import { getHandleId } from '@fastgpt/global/core/workflow/utils'; import { getHandleId } from '@fastgpt/global/core/workflow/utils';
import { callbackMap } from './constants'; import { callbackMap } from './constants';
import { getUserChatInfo } from '../../../support/user/team/utils'; import { getUserChatInfo } from '../../../support/user/team/utils';
...@@ -57,7 +53,7 @@ import { checkTeamAIPoints } from '../../../support/permission/teamLimit'; ...@@ -57,7 +53,7 @@ import { checkTeamAIPoints } from '../../../support/permission/teamLimit';
import type { UsageSourceEnum } from '@fastgpt/global/support/wallet/usage/constants'; import type { UsageSourceEnum } from '@fastgpt/global/support/wallet/usage/constants';
import { createChatUsageRecord, pushChatItemUsage } from '../../../support/wallet/usage/controller'; import { createChatUsageRecord, pushChatItemUsage } from '../../../support/wallet/usage/controller';
import type { RequireOnlyOne } from '@fastgpt/global/common/type/utils'; 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 { addPreviewUrlToChatItems } from '../../chat/utils';
import { TeamErrEnum } from '@fastgpt/global/common/error/code/team'; import { TeamErrEnum } from '@fastgpt/global/common/error/code/team';
import { i18nT } from '../../../../web/i18n/utils'; import { i18nT } from '../../../../web/i18n/utils';
...@@ -72,8 +68,9 @@ const logger = getLogger(LogCategories.MODULE.WORKFLOW.DISPATCH); ...@@ -72,8 +68,9 @@ const logger = getLogger(LogCategories.MODULE.WORKFLOW.DISPATCH);
type Props = Omit< type Props = Omit<
ChatDispatchProps, ChatDispatchProps,
'checkIsStopping' | 'workflowDispatchDeep' | 'timezone' | 'externalProvider' 'checkIsStopping' | 'workflowDispatchDeep' | 'timezone' | 'externalProvider' | 'variableState'
> & { > & {
variables: Record<string, any>;
runtimeNodes: RuntimeNodeItemType[]; runtimeNodes: RuntimeNodeItemType[];
runtimeEdges: RuntimeEdgeItemType[]; runtimeEdges: RuntimeEdgeItemType[];
defaultSkipNodeQueue?: WorkflowDebugResponse['skipNodeQueue']; defaultSkipNodeQueue?: WorkflowDebugResponse['skipNodeQueue'];
...@@ -188,6 +185,8 @@ export async function dispatchWorkFlow({ ...@@ -188,6 +185,8 @@ export async function dispatchWorkFlow({
// Check point // Check point
await checkTeamAIPoints(runningUserInfo.teamId); await checkTeamAIPoints(runningUserInfo.teamId);
const getPreviewUrl = createChatFilePreviewUrlGetter();
const [{ timezone, externalProvider }, newUsageId] = await Promise.all([ const [{ timezone, externalProvider }, newUsageId] = await Promise.all([
getUserChatInfo(runningUserInfo.tmbId), getUserChatInfo(runningUserInfo.tmbId),
(() => { (() => {
...@@ -206,15 +205,11 @@ export async function dispatchWorkFlow({ ...@@ -206,15 +205,11 @@ export async function dispatchWorkFlow({
return usageId; return usageId;
})(), })(),
// Add preview url to chat items // Add preview url to chat items
await addPreviewUrlToChatItems(histories, 'chatFlow'), addPreviewUrlToChatItems(histories, 'chatFlow'),
// Add preview url to query // Add preview url to query
...query.map(async (item) => { ...query.map(async (item) => {
if (!item.file?.key) return; if (!item.file?.key) return;
const { url } = await getS3ChatSource().createGetChatFileURL({ item.file.url = await getPreviewUrl(item.file.key);
key: item.file.key,
external: true
});
item.file.url = url;
}), }),
// Remove stopping sign // Remove stopping sign
delAgentRuntimeStopSign({ delAgentRuntimeStopSign({
...@@ -252,20 +247,17 @@ export async function dispatchWorkFlow({ ...@@ -252,20 +247,17 @@ export async function dispatchWorkFlow({
} }
} }
// Get default variables const variableState = await WorkflowVariableState.create({
const defaultVariables = { timezone,
...externalProvider.externalWorkflowVariables, runningAppInfo,
...(await getSystemVariables({ uid: data.uid,
runningAppInfo: runningAppInfo, chatId,
chatId: chatId, responseChatItemId: data.responseChatItemId,
responseChatItemId: data.responseChatItemId, histories,
histories: histories, variablesConfig: data.chatConfig?.variables,
uid: data.uid, inputVariables: data.variables,
chatConfig: data.chatConfig, externalVariables: externalProvider.externalWorkflowVariables
variables: data.variables, });
timezone: timezone
}))
};
// Stop sign(没有 apiVersion,说明不会有暂停) // Stop sign(没有 apiVersion,说明不会有暂停)
let stopping = false; let stopping = false;
...@@ -309,7 +301,7 @@ export async function dispatchWorkFlow({ ...@@ -309,7 +301,7 @@ export async function dispatchWorkFlow({
histories, histories,
timezone, timezone,
externalProvider, externalProvider,
variables: defaultVariables, variableState,
workflowDispatchDeep: 0, workflowDispatchDeep: 0,
usageId: newUsageId, usageId: newUsageId,
concatUsage concatUsage
...@@ -838,6 +830,7 @@ export class WorkflowQueue { ...@@ -838,6 +830,7 @@ export class WorkflowQueue {
} }
: {}; : {};
const runtimeVariables = this.data.variableState.toRuntimeRecord();
node.inputs.forEach((input) => { node.inputs.forEach((input) => {
// Special input, not format // Special input, not format
if (input.key === dynamicInput?.key) return; if (input.key === dynamicInput?.key) return;
...@@ -856,14 +849,14 @@ export class WorkflowQueue { ...@@ -856,14 +849,14 @@ export class WorkflowQueue {
let value = replaceEditorVariable({ let value = replaceEditorVariable({
text: input.value, text: input.value,
nodesMap: this.runtimeNodesMap, nodesMap: this.runtimeNodesMap,
variables: this.data.variables variables: runtimeVariables
}); });
// replace reference variables // replace reference variables
value = getReferenceVariableValue({ value = getReferenceVariableValue({
value, value,
nodesMap: this.runtimeNodesMap, nodesMap: this.runtimeNodesMap,
variables: this.data.variables variables: runtimeVariables
}); });
// Dynamic input is stored in the dynamic key // Dynamic input is stored in the dynamic key
...@@ -897,7 +890,6 @@ export class WorkflowQueue { ...@@ -897,7 +890,6 @@ export class WorkflowQueue {
lastInteractive: this.data.lastInteractive?.entryNodeIds?.includes(node.nodeId) lastInteractive: this.data.lastInteractive?.entryNodeIds?.includes(node.nodeId)
? this.data.lastInteractive ? this.data.lastInteractive
: undefined, : undefined,
variables: this.data.variables,
histories: this.data.histories, histories: this.data.histories,
retainDatasetCite: this.data.retainDatasetCite, retainDatasetCite: this.data.retainDatasetCite,
node, node,
...@@ -1035,14 +1027,6 @@ export class WorkflowQueue { ...@@ -1035,14 +1027,6 @@ export class WorkflowQueue {
}); });
} }
// Update new variables
if (dispatchRes[DispatchNodeResponseKeyEnum.newVariables]) {
this.data.variables = {
...this.data.variables,
...dispatchRes[DispatchNodeResponseKeyEnum.newVariables]
};
}
// Error // Error
if (dispatchRes?.responseData?.error) { if (dispatchRes?.responseData?.error) {
if (stepSpan) { if (stepSpan) {
...@@ -1519,11 +1503,7 @@ export const runWorkflow = async (data: RunWorkflowProps): Promise<DispatchFlowR ...@@ -1519,11 +1503,7 @@ export const runWorkflow = async (data: RunWorkflowProps): Promise<DispatchFlowR
[DispatchNodeResponseKeyEnum.runTimes]: 1, [DispatchNodeResponseKeyEnum.runTimes]: 1,
[DispatchNodeResponseKeyEnum.assistantResponses]: [], [DispatchNodeResponseKeyEnum.assistantResponses]: [],
[DispatchNodeResponseKeyEnum.toolResponses]: null, [DispatchNodeResponseKeyEnum.toolResponses]: null,
[DispatchNodeResponseKeyEnum.newVariables]: runtimeSystemVar2StoreType({ [DispatchNodeResponseKeyEnum.newVariables]: data.variableState.toStoreRecord(),
variables: data.variables,
removeObj: data.externalProvider.externalWorkflowVariables,
userVariablesConfigs: data.chatConfig?.variables
}),
durationSeconds: 0 durationSeconds: 0
}; };
} }
...@@ -1639,11 +1619,7 @@ export const runWorkflow = async (data: RunWorkflowProps): Promise<DispatchFlowR ...@@ -1639,11 +1619,7 @@ export const runWorkflow = async (data: RunWorkflowProps): Promise<DispatchFlowR
workflowQueue.chatAssistantResponse workflowQueue.chatAssistantResponse
), ),
[DispatchNodeResponseKeyEnum.toolResponses]: workflowQueue.toolRunResponse, [DispatchNodeResponseKeyEnum.toolResponses]: workflowQueue.toolRunResponse,
[DispatchNodeResponseKeyEnum.newVariables]: runtimeSystemVar2StoreType({ [DispatchNodeResponseKeyEnum.newVariables]: data.variableState.toStoreRecord(),
variables: data.variables,
removeObj: data.externalProvider.externalWorkflowVariables,
userVariablesConfigs: data.chatConfig?.variables
}),
[DispatchNodeResponseKeyEnum.memories]: [DispatchNodeResponseKeyEnum.memories]:
Object.keys(workflowQueue.system_memories).length > 0 Object.keys(workflowQueue.system_memories).length > 0
? workflowQueue.system_memories ? workflowQueue.system_memories
......
export const dispatchSystemConfig = (props: Record<string, any>) => { export const dispatchSystemConfig = (props: Record<string, any>) => {
const { variables } = props; return props.variableState.toRuntimeRecord();
return variables;
}; };
...@@ -17,7 +17,7 @@ type Response = DispatchNodeResultType<{ ...@@ -17,7 +17,7 @@ type Response = DispatchNodeResultType<{
export const dispatchWorkflowStart = async (props: Record<string, any>): Promise<Response> => { export const dispatchWorkflowStart = async (props: Record<string, any>): Promise<Response> => {
const { const {
query, query,
variables, variableState,
params: { userChatInput } params: { userChatInput }
} = props as UserChatInputProps; } = props as UserChatInputProps;
...@@ -28,9 +28,8 @@ export const dispatchWorkflowStart = async (props: Record<string, any>): Promise ...@@ -28,9 +28,8 @@ export const dispatchWorkflowStart = async (props: Record<string, any>): Promise
return item?.url ?? ''; return item?.url ?? '';
}) })
.filter(Boolean); .filter(Boolean);
const variablesFiles: string[] = Array.isArray(variables?.fileUrlList) const fileUrlList = variableState.get('fileUrlList');
? variables.fileUrlList const variablesFiles: string[] = Array.isArray(fileUrlList) ? fileUrlList : [];
: [];
return { return {
[DispatchNodeResponseKeyEnum.nodeResponse]: {}, [DispatchNodeResponseKeyEnum.nodeResponse]: {},
......
...@@ -10,6 +10,7 @@ import type { UserInputFormItemType } from '@fastgpt/global/core/workflow/templa ...@@ -10,6 +10,7 @@ import type { UserInputFormItemType } from '@fastgpt/global/core/workflow/templa
import { FlowNodeInputTypeEnum } from '@fastgpt/global/core/workflow/node/constant'; import { FlowNodeInputTypeEnum } from '@fastgpt/global/core/workflow/node/constant';
import { anyValueDecrypt } from '../../../../common/secret/utils'; import { anyValueDecrypt } from '../../../../common/secret/utils';
import { getLogger, LogCategories } from '../../../../common/logger'; import { getLogger, LogCategories } from '../../../../common/logger';
import { createChatFilePreviewUrlGetter } from '../../../../common/s3/sources/chat';
const logger = getLogger(LogCategories.MODULE.WORKFLOW.INTERACTIVE); const logger = getLogger(LogCategories.MODULE.WORKFLOW.INTERACTIVE);
...@@ -17,11 +18,36 @@ type Props = ModuleDispatchProps<{ ...@@ -17,11 +18,36 @@ type Props = ModuleDispatchProps<{
[NodeInputKeyEnum.description]: string; [NodeInputKeyEnum.description]: string;
[NodeInputKeyEnum.userInputForms]: UserInputFormItemType[]; [NodeInputKeyEnum.userInputForms]: UserInputFormItemType[];
}>; }>;
type FormInputValueMap = Record<string, unknown>;
type FormInputResponse = DispatchNodeResultType<{ type FormInputResponse = DispatchNodeResultType<{
[NodeOutputKeyEnum.formInputResult]?: Record<string, any>; [NodeOutputKeyEnum.formInputResult]?: FormInputValueMap;
[key: string]: any; [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 中获取。 用户输入都内容,将会以 JSON 字符串格式进入工作流,可以从 query 的 text 中获取。
*/ */
...@@ -51,7 +77,7 @@ export const dispatchFormInput = async (props: Props): Promise<FormInputResponse ...@@ -51,7 +77,7 @@ export const dispatchFormInput = async (props: Props): Promise<FormInputResponse
node.isEntry = false; node.isEntry = false;
const { text } = chatValue2RuntimePrompt(query); const { text } = chatValue2RuntimePrompt(query);
const rawUserInputVal: Record<string, any> = (() => { const rawUserInputVal: FormInputValueMap = (() => {
try { try {
return JSON.parse(text); return JSON.parse(text);
} catch (error) { } catch (error) {
...@@ -60,31 +86,22 @@ export const dispatchFormInput = async (props: Props): Promise<FormInputResponse ...@@ -60,31 +86,22 @@ export const dispatchFormInput = async (props: Props): Promise<FormInputResponse
} }
})(); })();
const userInputVal = Object.entries(rawUserInputVal).reduce( const getPreviewUrl = createChatFilePreviewUrlGetter({ expiredHours: 1 });
(acc, [key, value]) => { const inputConfigMap = new Map(userInputForms.map((form) => [form.key, form]));
const inputConfig = userInputForms.find((form) => form.key === key); const userInputEntries = await Promise.all(
Object.entries(rawUserInputVal).map(async ([key, value]) => {
const inputConfig = inputConfigMap.get(key);
if (inputConfig?.type === FlowNodeInputTypeEnum.password) { if (inputConfig?.type === FlowNodeInputTypeEnum.password) {
acc[key] = anyValueDecrypt(value); return [key, anyValueDecrypt(value)] as const;
} 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;
}
} else {
acc[key] = value;
} }
if (inputConfig?.type === FlowNodeInputTypeEnum.fileSelect) {
return acc; return [key, await formatFileSelectRuntimeValue(value, getPreviewUrl)] as const;
}, }
{} as Record<string, any> return [key, value] as const;
})
); );
const userInputVal = Object.fromEntries(userInputEntries) as FormInputValueMap;
return { return {
data: { data: {
......
...@@ -104,7 +104,6 @@ export const dispatchLoopRun = async (props: Props): Promise<Response> => { ...@@ -104,7 +104,6 @@ export const dispatchLoopRun = async (props: Props): Promise<Response> => {
const assistantResponses: AIChatItemValueItemType[] = []; const assistantResponses: AIChatItemValueItemType[] = [];
const customFeedbacks: string[] = []; const customFeedbacks: string[] = [];
let totalPoints = 0; let totalPoints = 0;
let newVariables: Record<string, any> = props.variables;
let interactiveResponse: WorkflowInteractiveResponseType | undefined; let interactiveResponse: WorkflowInteractiveResponseType | undefined;
// Pre-interrupt children of the in-flight iteration survive across resume here, // Pre-interrupt children of the in-flight iteration survive across resume here,
// so pushIterationDetail can stitch them back with the resumed iteration's // so pushIterationDetail can stitch them back with the resumed iteration's
...@@ -163,7 +162,6 @@ export const dispatchLoopRun = async (props: Props): Promise<Response> => { ...@@ -163,7 +162,6 @@ export const dispatchLoopRun = async (props: Props): Promise<Response> => {
const response = await runWorkflow({ const response = await runWorkflow({
...props, ...props,
lastInteractive: interactiveData?.childrenResponse, lastInteractive: interactiveData?.childrenResponse,
variables: newVariables,
runtimeNodes: isolatedNodes, runtimeNodes: isolatedNodes,
runtimeEdges: cloneDeep( runtimeEdges: cloneDeep(
storeEdges2RuntimeEdges(isolatedEdges, interactiveData?.childrenResponse) storeEdges2RuntimeEdges(isolatedEdges, interactiveData?.childrenResponse)
...@@ -190,7 +188,6 @@ export const dispatchLoopRun = async (props: Props): Promise<Response> => { ...@@ -190,7 +188,6 @@ export const dispatchLoopRun = async (props: Props): Promise<Response> => {
}); });
totalPoints += iterationTotalPoints; totalPoints += iterationTotalPoints;
collectResponseFeedbacks(response, customFeedbacks); collectResponseFeedbacks(response, customFeedbacks);
newVariables = { ...newVariables, ...response.newVariables };
// Pause: stash accumulated children so the next resume still sees pre-interrupt // Pause: stash accumulated children so the next resume still sees pre-interrupt
// nodes (supports multiple interrupts in the same iteration). // nodes (supports multiple interrupts in the same iteration).
...@@ -206,7 +203,7 @@ export const dispatchLoopRun = async (props: Props): Promise<Response> => { ...@@ -206,7 +203,7 @@ export const dispatchLoopRun = async (props: Props): Promise<Response> => {
const customOutputs = readCustomOutputSnapshot({ const customOutputs = readCustomOutputSnapshot({
customOutputInputs, customOutputInputs,
runtimeNodes: isolatedNodes, runtimeNodes: isolatedNodes,
variables: newVariables, variableState: props.variableState,
finishedNodeIds, finishedNodeIds,
childrenNodeIdList childrenNodeIdList
}); });
...@@ -292,7 +289,6 @@ export const dispatchLoopRun = async (props: Props): Promise<Response> => { ...@@ -292,7 +289,6 @@ export const dispatchLoopRun = async (props: Props): Promise<Response> => {
} }
} }
: undefined, : undefined,
[DispatchNodeResponseKeyEnum.newVariables]: newVariables,
[DispatchNodeResponseKeyEnum.nodeResponse]: { [DispatchNodeResponseKeyEnum.nodeResponse]: {
totalPoints, totalPoints,
loopRunInput: mode === LoopRunModeEnum.array ? inputArray : undefined, loopRunInput: mode === LoopRunModeEnum.array ? inputArray : undefined,
......
...@@ -7,7 +7,10 @@ import { ...@@ -7,7 +7,10 @@ import {
formatVariableValByType, formatVariableValByType,
getReferenceVariableValue getReferenceVariableValue
} from '@fastgpt/global/core/workflow/runtime/utils'; } 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 { import type {
FlowNodeInputItemType, FlowNodeInputItemType,
FlowNodeOutputItemType FlowNodeOutputItemType
...@@ -54,13 +57,13 @@ export const extractFinishedNodeIds = (flowResponses: ChatHistoryItemResType[]): ...@@ -54,13 +57,13 @@ export const extractFinishedNodeIds = (flowResponses: ChatHistoryItemResType[]):
export const readCustomOutputSnapshot = ({ export const readCustomOutputSnapshot = ({
customOutputInputs, customOutputInputs,
runtimeNodes, runtimeNodes,
variables, variableState,
finishedNodeIds, finishedNodeIds,
childrenNodeIdList childrenNodeIdList
}: { }: {
customOutputInputs: FlowNodeInputItemType[]; customOutputInputs: FlowNodeInputItemType[];
runtimeNodes: RuntimeNodeItemType[]; runtimeNodes: RuntimeNodeItemType[];
variables: Record<string, any>; variableState: WorkflowVariableStateLike;
finishedNodeIds?: Set<string>; finishedNodeIds?: Set<string>;
childrenNodeIdList?: string[]; childrenNodeIdList?: string[];
}): Record<string, any> => { }): Record<string, any> => {
...@@ -98,7 +101,7 @@ export const readCustomOutputSnapshot = ({ ...@@ -98,7 +101,7 @@ export const readCustomOutputSnapshot = ({
const resolved = getReferenceVariableValue({ const resolved = getReferenceVariableValue({
value: refValue, value: refValue,
nodesMap, nodesMap,
variables variables: variableState.toRuntimeRecord()
}); });
snapshot[item.key] = formatVariableValByType(resolved, item.valueType); snapshot[item.key] = formatVariableValByType(resolved, item.valueType);
} }
......
...@@ -9,7 +9,6 @@ import { ...@@ -9,7 +9,6 @@ import {
import { serviceEnv } from '../../../../env'; import { serviceEnv } from '../../../../env';
import { runWorkflow } from '..'; import { runWorkflow } from '..';
import { cloneDeep } from 'lodash';
import { import {
clampParallelConcurrency, clampParallelConcurrency,
clampParallelRetryTimes, clampParallelRetryTimes,
...@@ -84,7 +83,7 @@ export const dispatchParallelRun = async (props: Props): Promise<Response> => { ...@@ -84,7 +83,7 @@ export const dispatchParallelRun = async (props: Props): Promise<Response> => {
try { try {
const response = await runWorkflow({ const response = await runWorkflow({
...props, ...props,
variables: cloneDeep(props.variables), variableState: props.variableState.clone(),
runtimeNodes: taskRuntimeNodes, runtimeNodes: taskRuntimeNodes,
runtimeEdges: taskRuntimeEdges runtimeEdges: taskRuntimeEdges
}); });
......
...@@ -17,7 +17,7 @@ import { type DispatchNodeResultType } from '@fastgpt/global/core/workflow/runti ...@@ -17,7 +17,7 @@ import { type DispatchNodeResultType } from '@fastgpt/global/core/workflow/runti
import { authWorkflowToolByTmbId } from '../../../../support/permission/app/auth'; import { authWorkflowToolByTmbId } from '../../../../support/permission/app/auth';
import { ReadPermissionVal } from '@fastgpt/global/support/permission/constant'; import { ReadPermissionVal } from '@fastgpt/global/support/permission/constant';
import { computedAppToolUsage } from '../../../app/tool/runtime/utils'; import { computedAppToolUsage } from '../../../app/tool/runtime/utils';
import { filterSystemVariables, getNodeErrResponse } from '../utils'; import { getNodeErrResponse } from '../utils';
import { serverGetWorkflowToolRunUserQuery } from '../../../app/tool/workflowTool/utils'; import { serverGetWorkflowToolRunUserQuery } from '../../../app/tool/workflowTool/utils';
import { import {
type NodeInputKeyEnum, type NodeInputKeyEnum,
...@@ -31,6 +31,7 @@ import { anyValueDecrypt } from '../../../../common/secret/utils'; ...@@ -31,6 +31,7 @@ import { anyValueDecrypt } from '../../../../common/secret/utils';
import { getAppVersionById } from '../../../app/version/controller'; import { getAppVersionById } from '../../../app/version/controller';
import { parseI18nString } from '@fastgpt/global/common/i18n/utils'; import { parseI18nString } from '@fastgpt/global/common/i18n/utils';
import { getSystemToolByIdAndVersionId } from '../../../app/tool/controller'; import { getSystemToolByIdAndVersionId } from '../../../app/tool/controller';
import { WorkflowVariableState } from '../utils/variables';
type RunPluginProps = ModuleDispatchProps<{ type RunPluginProps = ModuleDispatchProps<{
[NodeInputKeyEnum.forbidStream]?: boolean; [NodeInputKeyEnum.forbidStream]?: boolean;
...@@ -176,11 +177,26 @@ export const dispatchRunPlugin = async (props: RunPluginProps): Promise<RunPlugi ...@@ -176,11 +177,26 @@ export const dispatchRunPlugin = async (props: RunPluginProps): Promise<RunPlugi
}); });
const { externalProvider } = await getUserChatInfo(runningAppInfo.tmbId); const { externalProvider } = await getUserChatInfo(runningAppInfo.tmbId);
const runtimeVariables = { const childRunningAppInfo = {
...filterSystemVariables(props.variables), id: String(workflowTool.id),
appId: String(workflowTool.id), name: workflowTool.name,
...(externalProvider ? externalProvider.externalWorkflowVariables : {}) 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 { const {
flowResponses, flowResponses,
flowUsages, flowUsages,
...@@ -205,7 +221,7 @@ export const dispatchRunPlugin = async (props: RunPluginProps): Promise<RunPlugi ...@@ -205,7 +221,7 @@ export const dispatchRunPlugin = async (props: RunPluginProps): Promise<RunPlugi
tmbId: workflowTool.tmbId || runningAppInfo.tmbId, tmbId: workflowTool.tmbId || runningAppInfo.tmbId,
isChildApp: true isChildApp: true
}, },
variables: runtimeVariables, variableState: childVariableState,
query: serverGetWorkflowToolRunUserQuery({ query: serverGetWorkflowToolRunUserQuery({
pluginInputs: getWorkflowToolInputsFromStoreNodes(workflowTool.nodes), pluginInputs: getWorkflowToolInputsFromStoreNodes(workflowTool.nodes),
variables: runtimeVariables, variables: runtimeVariables,
......
...@@ -6,7 +6,7 @@ import type { ...@@ -6,7 +6,7 @@ import type {
DispatchNodeResultType, DispatchNodeResultType,
ModuleDispatchProps ModuleDispatchProps
} from '@fastgpt/global/core/workflow/runtime/type'; } 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<{ export type PluginInputProps = ModuleDispatchProps<{
[key: string]: any; [key: string]: any;
...@@ -16,11 +16,24 @@ export type PluginInputResponse = DispatchNodeResultType<{ ...@@ -16,11 +16,24 @@ export type PluginInputResponse = DispatchNodeResultType<{
[key: string]: any; [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 ( export const dispatchPluginInput = async (
props: PluginInputProps props: PluginInputProps
): Promise<PluginInputResponse> => { ): Promise<PluginInputResponse> => {
const { params, query } = props; const { params, query } = props;
const { files } = chatValue2RuntimePrompt(query); const { files } = chatValue2RuntimePrompt(query);
const getPreviewUrl = createChatFilePreviewUrlGetter({ expiredHours: 1 });
/* /*
对 params 中文件类型数据进行处理 对 params 中文件类型数据进行处理
...@@ -30,29 +43,22 @@ export const dispatchPluginInput = async ( ...@@ -30,29 +43,22 @@ export const dispatchPluginInput = async (
TODO: 需要 filter max files TODO: 需要 filter max files
*/ */
for (const key in params) { await Promise.all(
const val = params[key]; Object.keys(params).map(async (key) => {
if ( const val = params[key];
Array.isArray(val) && if (Array.isArray(val) && val.every(isPluginFileItem)) {
val.every( // 为文件对象重新签发 URL(如果有 key 但没有 url)
(item) => item.type === ChatFileTypeEnum.file || item.type === ChatFileTypeEnum.image await Promise.all(
) val.map(async (fileItem) => {
) { if (fileItem.key && !fileItem.url) {
// 为文件对象重新签发 URL(如果有 key 但没有 url) fileItem.url = await getPreviewUrl(fileItem.key);
for (let i = 0; i < val.length; i++) { }
const fileItem = val[i]; })
if (fileItem.key && !fileItem.url) { );
const { url } = await getS3ChatSource().createGetChatFileURL({ params[key] = val.map((item) => item.url);
key: fileItem.key,
external: true,
expiredHours: 1
});
val[i].url = url;
}
} }
params[key] = val.map((item) => item.url); })
} );
}
return { return {
data: { data: {
......
...@@ -8,7 +8,6 @@ import { ...@@ -8,7 +8,6 @@ import {
WorkflowIOValueTypeEnum WorkflowIOValueTypeEnum
} from '@fastgpt/global/core/workflow/constants'; } from '@fastgpt/global/core/workflow/constants';
import { DispatchNodeResponseKeyEnum } from '@fastgpt/global/core/workflow/runtime/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 DispatchNodeResultType } from '@fastgpt/global/core/workflow/runtime/type';
import type { import type {
ModuleDispatchProps, ModuleDispatchProps,
...@@ -17,7 +16,8 @@ import type { ...@@ -17,7 +16,8 @@ import type {
import { import {
formatVariableValByType, formatVariableValByType,
getReferenceVariableValue, getReferenceVariableValue,
replaceEditorVariable replaceEditorVariable,
valueTypeFormat
} from '@fastgpt/global/core/workflow/runtime/utils'; } from '@fastgpt/global/core/workflow/runtime/utils';
import json5 from 'json5'; import json5 from 'json5';
import { JSONPath } from 'jsonpath-plus'; import { JSONPath } from 'jsonpath-plus';
...@@ -66,7 +66,7 @@ export const dispatchHttp468Request = async (props: HttpRequestProps): Promise<H ...@@ -66,7 +66,7 @@ export const dispatchHttp468Request = async (props: HttpRequestProps): Promise<H
runningAppInfo: { id: appId }, runningAppInfo: { id: appId },
chatId, chatId,
responseChatItemId, responseChatItemId,
variables, variableState,
node, node,
runtimeNodesMap, runtimeNodesMap,
histories, histories,
...@@ -96,7 +96,7 @@ export const dispatchHttp468Request = async (props: HttpRequestProps): Promise<H ...@@ -96,7 +96,7 @@ export const dispatchHttp468Request = async (props: HttpRequestProps): Promise<H
histories: histories?.slice(-10) || [] histories: histories?.slice(-10) || []
}; };
const concatVariables = { const concatVariables = {
...variables, ...variableState.toRuntimeRecord(),
...body, ...body,
...systemVariables ...systemVariables
}; };
...@@ -177,7 +177,10 @@ export const dispatchHttp468Request = async (props: HttpRequestProps): Promise<H ...@@ -177,7 +177,10 @@ export const dispatchHttp468Request = async (props: HttpRequestProps): Promise<H
if (httpContentType === ContentTypes.json) { if (httpContentType === ContentTypes.json) {
httpJsonBody = replaceJsonBodyString( httpJsonBody = replaceJsonBodyString(
{ text: httpJsonBody }, { text: httpJsonBody },
{ variables, allVariables, runtimeNodesMap } {
allVariables,
runtimeNodesMap
}
); );
return json5.parse(httpJsonBody); return json5.parse(httpJsonBody);
} }
...@@ -303,12 +306,11 @@ export const dispatchHttp468Request = async (props: HttpRequestProps): Promise<H ...@@ -303,12 +306,11 @@ export const dispatchHttp468Request = async (props: HttpRequestProps): Promise<H
export const replaceJsonBodyString = ( export const replaceJsonBodyString = (
{ text, depth = 0 }: { text: string; depth?: number }, { text, depth = 0 }: { text: string; depth?: number },
props: { props: {
variables: Record<string, any>;
allVariables: Record<string, any>; allVariables: Record<string, any>;
runtimeNodesMap: Map<string, RuntimeNodeItemType>; runtimeNodesMap: Map<string, RuntimeNodeItemType>;
} }
) => { ) => {
const { variables, allVariables, runtimeNodesMap } = props; const { allVariables, runtimeNodesMap } = props;
const MAX_REPLACEMENT_DEPTH = 10; const MAX_REPLACEMENT_DEPTH = 10;
const processedVariables = new Set<string>(); const processedVariables = new Set<string>();
...@@ -401,7 +403,7 @@ export const replaceJsonBodyString = ( ...@@ -401,7 +403,7 @@ export const replaceJsonBodyString = (
const variableVal = (() => { const variableVal = (() => {
if (nodeId === VARIABLE_NODE_ID) { if (nodeId === VARIABLE_NODE_ID) {
return variables[id]; return allVariables[id];
} }
// Find upstream node input/output // Find upstream node input/output
const node = runtimeNodesMap.get(nodeId); const node = runtimeNodesMap.get(nodeId);
...@@ -415,7 +417,7 @@ export const replaceJsonBodyString = ( ...@@ -415,7 +417,7 @@ export const replaceJsonBodyString = (
return getReferenceVariableValue({ return getReferenceVariableValue({
value: input.value, value: input.value,
nodesMap: runtimeNodesMap, nodesMap: runtimeNodesMap,
variables variables: allVariables
}); });
} }
})(); })();
......
...@@ -3,7 +3,8 @@ import { NodeOutputKeyEnum } from '@fastgpt/global/core/workflow/constants'; ...@@ -3,7 +3,8 @@ import { NodeOutputKeyEnum } from '@fastgpt/global/core/workflow/constants';
import { DispatchNodeResponseKeyEnum } from '@fastgpt/global/core/workflow/runtime/constants'; import { DispatchNodeResponseKeyEnum } from '@fastgpt/global/core/workflow/runtime/constants';
import { import {
type RuntimeNodeItemType, type RuntimeNodeItemType,
type DispatchNodeResultType type DispatchNodeResultType,
type WorkflowVariableStateLike
} from '@fastgpt/global/core/workflow/runtime/type'; } from '@fastgpt/global/core/workflow/runtime/type';
import { import {
IfElseResultEnum, IfElseResultEnum,
...@@ -104,16 +105,17 @@ function checkCondition(condition: VariableConditionEnum, inputValue: any, value ...@@ -104,16 +105,17 @@ function checkCondition(condition: VariableConditionEnum, inputValue: any, value
function getResult( function getResult(
condition: IfElseConditionType, condition: IfElseConditionType,
list: ConditionListItemType[], list: ConditionListItemType[],
variables: Record<string, any>, variableState: WorkflowVariableStateLike,
runtimeNodesMap: Map<string, RuntimeNodeItemType> runtimeNodesMap: Map<string, RuntimeNodeItemType>
) { ) {
const runtimeVariables = variableState.toRuntimeRecord();
const listResult = list.map((item) => { const listResult = list.map((item) => {
const { variable, condition: variableCondition, value, valueType } = item; const { variable, condition: variableCondition, value, valueType } = item;
if (!variableCondition) return; if (!variableCondition) return;
const conditionLeftValue = getReferenceVariableValue({ const conditionLeftValue = getReferenceVariableValue({
value: variable, value: variable,
variables, variables: runtimeVariables,
nodesMap: runtimeNodesMap nodesMap: runtimeNodesMap
}); });
...@@ -121,7 +123,7 @@ function getResult( ...@@ -121,7 +123,7 @@ function getResult(
valueType === 'reference' valueType === 'reference'
? getReferenceVariableValue({ ? getReferenceVariableValue({
value: value as ReferenceItemValueType, value: value as ReferenceItemValueType,
variables, variables: runtimeVariables,
nodesMap: runtimeNodesMap nodesMap: runtimeNodesMap
}) })
: value; : value;
...@@ -136,7 +138,7 @@ export const dispatchIfElse = async (props: Props): Promise<Response> => { ...@@ -136,7 +138,7 @@ export const dispatchIfElse = async (props: Props): Promise<Response> => {
const { const {
params, params,
runtimeNodesMap, runtimeNodesMap,
variables, variableState,
node: { nodeId } node: { nodeId }
} = props; } = props;
const { ifElseList } = params; const { ifElseList } = params;
...@@ -144,7 +146,7 @@ export const dispatchIfElse = async (props: Props): Promise<Response> => { ...@@ -144,7 +146,7 @@ export const dispatchIfElse = async (props: Props): Promise<Response> => {
let res = IfElseResultEnum.ELSE as string; let res = IfElseResultEnum.ELSE as string;
for (let i = 0; i < ifElseList.length; i++) { for (let i = 0; i < ifElseList.length; i++) {
const item = ifElseList[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) { if (result) {
res = getElseIFLabel(i); res = getElseIFLabel(i);
break; break;
......
...@@ -29,7 +29,7 @@ export const dispatchLafRequest = async (props: LafRequestProps): Promise<LafRes ...@@ -29,7 +29,7 @@ export const dispatchLafRequest = async (props: LafRequestProps): Promise<LafRes
runningAppInfo: { id: appId }, runningAppInfo: { id: appId },
chatId, chatId,
responseChatItemId, responseChatItemId,
variables, variableState,
node: { outputs }, node: { outputs },
histories, histories,
params: { params: {
...@@ -38,6 +38,7 @@ export const dispatchLafRequest = async (props: LafRequestProps): Promise<LafRes ...@@ -38,6 +38,7 @@ export const dispatchLafRequest = async (props: LafRequestProps): Promise<LafRes
...body ...body
} }
} = props; } = props;
const variables = variableState.toRuntimeRecord();
if (!httpReqUrl) { if (!httpReqUrl) {
return Promise.reject('Http url is empty'); return Promise.reject('Http url is empty');
......
...@@ -12,7 +12,6 @@ import { ...@@ -12,7 +12,6 @@ import {
} from '@fastgpt/global/core/workflow/runtime/utils'; } from '@fastgpt/global/core/workflow/runtime/utils';
import { type TUpdateListItem } from '@fastgpt/global/core/workflow/template/system/variableUpdate/type'; import { type TUpdateListItem } from '@fastgpt/global/core/workflow/template/system/variableUpdate/type';
import { type ModuleDispatchProps } from '@fastgpt/global/core/workflow/runtime/type'; import { type ModuleDispatchProps } from '@fastgpt/global/core/workflow/runtime/type';
import { runtimeSystemVar2StoreType } from '../utils';
import { isValidReferenceValue } from '@fastgpt/global/core/workflow/utils'; import { isValidReferenceValue } from '@fastgpt/global/core/workflow/utils';
import { valueTypeFormat } from '@fastgpt/global/core/workflow/runtime/utils'; import { valueTypeFormat } from '@fastgpt/global/core/workflow/runtime/utils';
import { getLogger, LogCategories } from '../../../../common/logger'; import { getLogger, LogCategories } from '../../../../common/logger';
...@@ -66,43 +65,40 @@ type Props = ModuleDispatchProps<{ ...@@ -66,43 +65,40 @@ type Props = ModuleDispatchProps<{
type Response = DispatchNodeResultType<{}>; type Response = DispatchNodeResultType<{}>;
export const dispatchUpdateVariable = async (props: Props): Promise<Response> => { export const dispatchUpdateVariable = async (props: Props): Promise<Response> => {
const { const { params, variableState, runtimeNodesMap, workflowStreamResponse, runningAppInfo } = props;
chatConfig,
params,
variables,
runtimeNodesMap,
workflowStreamResponse,
externalProvider,
runningAppInfo
} = props;
const { updateList } = params; const { updateList } = params;
const nodeIds = Array.from(runtimeNodesMap.keys()); const nodeIds = Array.from(runtimeNodesMap.keys());
// 顺序执行:同一节点多条 update 依次写入,后一条读到前一条的新值 // 顺序执行:同一节点多条 update 依次写入,后一条读到前一条的新值
const result = updateList.map((item) => { const result = [];
for (const item of updateList) {
const variable = item.variable; const variable = item.variable;
if (!isValidReferenceValue(variable, nodeIds)) { if (!isValidReferenceValue(variable, nodeIds)) {
return null; result.push(null);
continue;
} }
const varNodeId = variable[0]; const varNodeId = variable[0];
const varKey = variable[1]; const varKey = variable[1];
if (!varKey) { if (!varKey) {
return null; result.push(null);
continue;
} }
const isInput = item.renderType === FlowNodeInputTypeEnum.input; const isInput = item.renderType === FlowNodeInputTypeEnum.input;
const isArrayVar = isArrayValueType(item.valueType); const isArrayVar = isArrayValueType(item.valueType);
const isArrayClear = isArrayVar && item.arrayMode === 'clear'; const isArrayClear = isArrayVar && item.arrayMode === 'clear';
const isArrayAppend = isArrayVar && item.arrayMode === 'append'; const isArrayAppend = isArrayVar && item.arrayMode === 'append';
const runtimeVariables = variableState.toRuntimeRecord();
// 读 oldValue(Number 公式 / Boolean negate / Array append 需要) // 读 oldValue(Number 公式 / Boolean negate / Array append 需要)
const oldValue = const oldValue =
varNodeId === VARIABLE_NODE_ID varNodeId === VARIABLE_NODE_ID
? variables[varKey] ? variableState.get(varKey)
: runtimeNodesMap.get(varNodeId)?.outputs?.find((o) => o.id === varKey)?.value; : runtimeNodesMap.get(varNodeId)?.outputs?.find((o) => o.id === varKey)?.value;
// 计算原始输入值(clear 分支无输入) // 计算原始输入值(clear 分支无输入)
...@@ -115,7 +111,7 @@ export const dispatchUpdateVariable = async (props: Props): Promise<Response> => ...@@ -115,7 +111,7 @@ export const dispatchUpdateVariable = async (props: Props): Promise<Response> =>
? replaceEditorVariable({ ? replaceEditorVariable({
text: item.value?.[1], text: item.value?.[1],
nodesMap: runtimeNodesMap, nodesMap: runtimeNodesMap,
variables variables: runtimeVariables
}) })
: item.value?.[1]; : item.value?.[1];
...@@ -127,7 +123,7 @@ export const dispatchUpdateVariable = async (props: Props): Promise<Response> => ...@@ -127,7 +123,7 @@ export const dispatchUpdateVariable = async (props: Props): Promise<Response> =>
// reference // reference
return getReferenceVariableValue({ return getReferenceVariableValue({
value: item.value!, value: item.value!,
variables, variables: runtimeVariables,
nodesMap: runtimeNodesMap nodesMap: runtimeNodesMap
}); });
})(); })();
...@@ -163,7 +159,7 @@ export const dispatchUpdateVariable = async (props: Props): Promise<Response> => ...@@ -163,7 +159,7 @@ export const dispatchUpdateVariable = async (props: Props): Promise<Response> =>
// 写回 // 写回
if (varNodeId === VARIABLE_NODE_ID) { if (varNodeId === VARIABLE_NODE_ID) {
variables[varKey] = value; value = await variableState.set(varKey, value);
} else { } else {
const node = runtimeNodesMap.get(varNodeId); const node = runtimeNodesMap.get(varNodeId);
node?.outputs?.find((output) => { node?.outputs?.find((output) => {
...@@ -174,22 +170,17 @@ export const dispatchUpdateVariable = async (props: Props): Promise<Response> => ...@@ -174,22 +170,17 @@ export const dispatchUpdateVariable = async (props: Props): Promise<Response> =>
}); });
} }
return value; result.push(value);
}); }
if (!runningAppInfo.isChildApp) { if (!runningAppInfo.isChildApp) {
workflowStreamResponse?.({ workflowStreamResponse?.({
event: SseResponseEventEnum.updateVariables, event: SseResponseEventEnum.updateVariables,
data: runtimeSystemVar2StoreType({ data: variableState.toStoreRecord()
variables,
removeObj: externalProvider.externalWorkflowVariables,
userVariablesConfigs: chatConfig?.variables
})
}); });
} }
return { return {
[DispatchNodeResponseKeyEnum.newVariables]: variables,
[DispatchNodeResponseKeyEnum.nodeResponse]: { [DispatchNodeResponseKeyEnum.nodeResponse]: {
updateVarResult: result updateVarResult: result
} }
......
...@@ -15,7 +15,7 @@ type Response = DispatchNodeResultType<{ ...@@ -15,7 +15,7 @@ type Response = DispatchNodeResultType<{
export const dispatchTextEditor = (props: Record<string, any>): Response => { export const dispatchTextEditor = (props: Record<string, any>): Response => {
const { const {
variables, variableState,
params: { system_textareaInput: text = '', system_addInputParam: customVariables = {} } params: { system_textareaInput: text = '', system_addInputParam: customVariables = {} }
} = props as Props; } = props as Props;
...@@ -36,7 +36,7 @@ export const dispatchTextEditor = (props: Record<string, any>): Response => { ...@@ -36,7 +36,7 @@ export const dispatchTextEditor = (props: Record<string, any>): Response => {
const textResult = replaceVariable(text, { const textResult = replaceVariable(text, {
...customVariables, ...customVariables,
...variables ...variableState.toRuntimeRecord()
}); });
return { return {
......
...@@ -41,7 +41,7 @@ export type DispatchFlowResponse = { ...@@ -41,7 +41,7 @@ export type DispatchFlowResponse = {
[DispatchNodeResponseKeyEnum.runTimes]: number; [DispatchNodeResponseKeyEnum.runTimes]: number;
[DispatchNodeResponseKeyEnum.memories]?: Record<string, any>; [DispatchNodeResponseKeyEnum.memories]?: Record<string, any>;
[DispatchNodeResponseKeyEnum.customFeedbacks]?: string[]; [DispatchNodeResponseKeyEnum.customFeedbacks]?: string[];
[DispatchNodeResponseKeyEnum.newVariables]: Record<string, string>; [DispatchNodeResponseKeyEnum.newVariables]: Record<string, any>;
durationSeconds: number; durationSeconds: number;
}; };
......
import path from 'path';
import { getErrText } from '@fastgpt/global/common/error/utils'; import { getErrText } from '@fastgpt/global/common/error/utils';
import { ChatRoleEnum } from '@fastgpt/global/core/chat/constants'; import { ChatRoleEnum } from '@fastgpt/global/core/chat/constants';
import type { ChatItemMiniType } from '@fastgpt/global/core/chat/type'; import type { ChatItemMiniType } from '@fastgpt/global/core/chat/type';
import type { ChatNodeUsageType } from '@fastgpt/global/support/wallet/bill/type'; import type { ChatNodeUsageType } from '@fastgpt/global/support/wallet/bill/type';
import type { DispatchFlowResponse } from './type'; import type { DispatchFlowResponse } from '../type';
import { import { NodeInputKeyEnum, NodeOutputKeyEnum } from '@fastgpt/global/core/workflow/constants';
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 { import {
type RuntimeNodeItemType, type RuntimeNodeItemType,
type SystemVariablesType type SystemVariablesType
} from '@fastgpt/global/core/workflow/runtime/type'; } from '@fastgpt/global/core/workflow/runtime/type';
import type { RuntimeEdgeItemType } from '@fastgpt/global/core/workflow/type/edge'; 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 { type NextApiResponse } from 'next';
import { import {
DispatchNodeResponseKeyEnum, DispatchNodeResponseKeyEnum,
...@@ -32,85 +23,17 @@ import { ...@@ -32,85 +23,17 @@ import {
parseHttpToolConfig parseHttpToolConfig
} from '@fastgpt/global/core/app/tool/httpTool/utils'; } from '@fastgpt/global/core/app/tool/httpTool/utils';
import { FlowNodeTypeEnum } from '@fastgpt/global/core/workflow/node/constant'; import { FlowNodeTypeEnum } from '@fastgpt/global/core/workflow/node/constant';
import { MongoApp } from '../../../core/app/schema'; import { MongoApp } from '../../../app/schema';
import { getMCPChildren } from '../../../core/app/mcp'; import { getMCPChildren } from '../../../app/mcp';
import { getSystemToolRunTimeNodeFromSystemToolset } from '../utils'; import { getSystemToolRunTimeNodeFromSystemToolset } from '../../utils';
import type { localeType } from '@fastgpt/global/common/i18n/type'; import type { localeType } from '@fastgpt/global/common/i18n/type';
import type { HttpToolConfigType } from '@fastgpt/global/core/app/tool/httpTool/type'; import type { HttpToolConfigType } from '@fastgpt/global/core/app/tool/httpTool/type';
import type { WorkflowResponseType } from './type'; import type { WorkflowResponseType } from '../type';
import { getLogger, LogCategories } from '../../../common/logger'; 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 { parsetMcpToolConfig } from '@fastgpt/global/core/app/tool/mcpTool/utils'; import { parsetMcpToolConfig } from '@fastgpt/global/core/app/tool/mcpTool/utils';
import { getMcpToolsets } from '../../app/tool/mcpTool/entity'; import { getMcpToolsets } from '../../../app/tool/mcpTool/entity';
import { getHttpToolsets } from '../../app/tool/httpTool/entity'; import { getHttpToolsets } from '../../../app/tool/httpTool/entity';
import { getHTTPToolList } from '../../app/http'; 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)
};
};
export const getWorkflowResponseWrite = ({ export const getWorkflowResponseWrite = ({
res, res,
...@@ -293,74 +216,6 @@ export const checkQuoteQAValue = (quoteQA?: SearchDataResponseItemType[]) => { ...@@ -293,74 +216,6 @@ export const checkQuoteQAValue = (quoteQA?: SearchDataResponseItemType[]) => {
return quoteQA; 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 => { export const filterSystemVariables = (variables: Record<string, any>): SystemVariablesType => {
return { return {
userId: variables.userId, userId: variables.userId,
...@@ -569,21 +424,18 @@ export const getNodeErrResponse = ({ ...@@ -569,21 +424,18 @@ export const getNodeErrResponse = ({
customErr, customErr,
responseData, responseData,
runTimes, runTimes,
newVariables,
system_memories system_memories
}: { }: {
error: any; error: any;
customErr?: Record<string, any>; customErr?: Record<string, any>;
[DispatchNodeResponseKeyEnum.nodeResponse]?: Record<string, any>; [DispatchNodeResponseKeyEnum.nodeResponse]?: Record<string, any>;
[DispatchNodeResponseKeyEnum.runTimes]?: number; [DispatchNodeResponseKeyEnum.runTimes]?: number;
[DispatchNodeResponseKeyEnum.newVariables]?: Record<string, any>;
[DispatchNodeResponseKeyEnum.memories]?: Record<string, any>; [DispatchNodeResponseKeyEnum.memories]?: Record<string, any>;
}) => { }) => {
const errorText = getErrText(error); const errorText = getErrText(error);
return { return {
[DispatchNodeResponseKeyEnum.runTimes]: runTimes, [DispatchNodeResponseKeyEnum.runTimes]: runTimes,
[DispatchNodeResponseKeyEnum.newVariables]: newVariables,
[DispatchNodeResponseKeyEnum.memories]: system_memories, [DispatchNodeResponseKeyEnum.memories]: system_memories,
error: { error: {
[NodeOutputKeyEnum.errorText]: errorText, [NodeOutputKeyEnum.errorText]: errorText,
......
...@@ -891,7 +891,6 @@ describe('pushChatRecords', () => { ...@@ -891,7 +891,6 @@ describe('pushChatRecords', () => {
chatId: props.chatId, chatId: props.chatId,
obj: ChatRoleEnum.AI obj: ChatRoleEnum.AI
}); });
console.log(chatItem?.value, 1212);
if (chatItem) { if (chatItem) {
if (chatItem.obj === ChatRoleEnum.AI) { if (chatItem.obj === ChatRoleEnum.AI) {
const lastValue = chatItem.value[chatItem.value.length - 1]; const lastValue = chatItem.value[chatItem.value.length - 1];
...@@ -997,6 +996,133 @@ describe('pushChatRecords', () => { ...@@ -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 () => { it('should persist agentPlanAskQuery answer before pushing new records', async () => {
await MongoChatItem.create({ await MongoChatItem.create({
chatId: 'test-chat-id', 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 ...@@ -7,6 +7,7 @@ import { NodeInputKeyEnum, NodeOutputKeyEnum } from '@fastgpt/global/core/workfl
import { DispatchNodeResponseKeyEnum } from '@fastgpt/global/core/workflow/runtime/constants'; import { DispatchNodeResponseKeyEnum } from '@fastgpt/global/core/workflow/runtime/constants';
import { LoopRunModeEnum } from '@fastgpt/global/core/workflow/template/system/loopRun/loopRun'; import { LoopRunModeEnum } from '@fastgpt/global/core/workflow/template/system/loopRun/loopRun';
import type { RuntimeNodeItemType } from '@fastgpt/global/core/workflow/runtime/type'; 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 { FlowNodeInputItemType } from '@fastgpt/global/core/workflow/type/io';
import type { ChatHistoryItemResType } from '@fastgpt/global/core/chat/type'; import type { ChatHistoryItemResType } from '@fastgpt/global/core/chat/type';
import type { DispatchFlowResponse } from '@fastgpt/service/core/workflow/dispatch/type'; import type { DispatchFlowResponse } from '@fastgpt/service/core/workflow/dispatch/type';
...@@ -148,6 +149,20 @@ const makeResponseItem = (nodeId: string, override: Partial<ChatHistoryItemResTy ...@@ -148,6 +149,20 @@ const makeResponseItem = (nodeId: string, override: Partial<ChatHistoryItemResTy
...override ...override
}) as ChatHistoryItemResType; }) 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 = ( const makeProps = (
params: any, params: any,
opts: { withBreak?: boolean; childrenNodeIdList?: string[] } = {} opts: { withBreak?: boolean; childrenNodeIdList?: string[] } = {}
...@@ -169,7 +184,7 @@ const makeProps = ( ...@@ -169,7 +184,7 @@ const makeProps = (
runtimeNodes, runtimeNodes,
runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])), runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])),
runtimeEdges: [], runtimeEdges: [],
variables: {}, variableState: makeVariableState(),
usagePush: vi.fn(), usagePush: vi.fn(),
lastInteractive: undefined, lastInteractive: undefined,
checkIsStopping: () => false checkIsStopping: () => false
...@@ -215,7 +230,7 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => { ...@@ -215,7 +230,7 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => {
runtimeNodes, runtimeNodes,
runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])), runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])),
runtimeEdges: [], runtimeEdges: [],
variables: {}, variableState: makeVariableState(),
usagePush: vi.fn(), usagePush: vi.fn(),
lastInteractive: undefined, lastInteractive: undefined,
checkIsStopping: () => false checkIsStopping: () => false
...@@ -233,6 +248,28 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => { ...@@ -233,6 +248,28 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => {
expect(result.error).toBeUndefined(); 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 () => { it('array mode 第 2 轮节点出错 → 本轮 success:false, 失败轮快照对未跑节点返回 undefined', async () => {
let iter = 0; let iter = 0;
runWorkflowMock.mockImplementation((args: any) => { runWorkflowMock.mockImplementation((args: any) => {
...@@ -268,7 +305,7 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => { ...@@ -268,7 +305,7 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => {
runtimeNodes, runtimeNodes,
runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])), runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])),
runtimeEdges: [], runtimeEdges: [],
variables: {}, variableState: makeVariableState(),
usagePush: vi.fn(), usagePush: vi.fn(),
lastInteractive: undefined, lastInteractive: undefined,
checkIsStopping: () => false checkIsStopping: () => false
...@@ -476,7 +513,7 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => { ...@@ -476,7 +513,7 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => {
runtimeNodes, runtimeNodes,
runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])), runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])),
runtimeEdges: [], runtimeEdges: [],
variables: {}, variableState: makeVariableState(),
usagePush: vi.fn(), usagePush: vi.fn(),
lastInteractive: { lastInteractive: {
type: 'loopRunInteractive', type: 'loopRunInteractive',
...@@ -528,7 +565,7 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => { ...@@ -528,7 +565,7 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => {
runtimeNodes, runtimeNodes,
runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])), runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])),
runtimeEdges: [], runtimeEdges: [],
variables: {}, variableState: makeVariableState(),
usagePush: vi.fn(), usagePush: vi.fn(),
lastInteractive: { lastInteractive: {
type: 'loopRunInteractive', type: 'loopRunInteractive',
...@@ -614,7 +651,7 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => { ...@@ -614,7 +651,7 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => {
runtimeNodes, runtimeNodes,
runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])), runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])),
runtimeEdges: [], runtimeEdges: [],
variables: {}, variableState: makeVariableState(),
usagePush: vi.fn(), usagePush: vi.fn(),
lastInteractive: undefined, lastInteractive: undefined,
checkIsStopping: () => false checkIsStopping: () => false
...@@ -785,7 +822,7 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => { ...@@ -785,7 +822,7 @@ describe('runLoopRun (integration with mocked runWorkflow)', () => {
runtimeNodes, runtimeNodes,
runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])), runtimeNodesMap: new Map(runtimeNodes.map((n) => [n.nodeId, n])),
runtimeEdges: [], runtimeEdges: [],
variables: {}, variableState: makeVariableState(),
usagePush: vi.fn(), usagePush: vi.fn(),
checkIsStopping: () => false, checkIsStopping: () => false,
lastInteractive: { lastInteractive: {
......
...@@ -5,7 +5,10 @@ import { ...@@ -5,7 +5,10 @@ import {
} from '@fastgpt/global/core/workflow/node/constant'; } from '@fastgpt/global/core/workflow/node/constant';
import { NodeInputKeyEnum } from '@fastgpt/global/core/workflow/constants'; import { NodeInputKeyEnum } from '@fastgpt/global/core/workflow/constants';
import { LoopRunModeEnum } from '@fastgpt/global/core/workflow/template/system/loopRun/loopRun'; 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 { import type {
FlowNodeInputItemType, FlowNodeInputItemType,
FlowNodeOutputItemType FlowNodeOutputItemType
...@@ -65,6 +68,18 @@ const makeResponse = (override: Partial<ChatHistoryItemResType>): ChatHistoryIte ...@@ -65,6 +68,18 @@ const makeResponse = (override: Partial<ChatHistoryItemResType>): ChatHistoryIte
...override ...override
}) as ChatHistoryItemResType; }) 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 ──────────────────────────────────────────────────────────────────── // ─── Tests ────────────────────────────────────────────────────────────────────
describe('loopRun/service', () => { describe('loopRun/service', () => {
...@@ -155,7 +170,7 @@ describe('loopRun/service', () => { ...@@ -155,7 +170,7 @@ describe('loopRun/service', () => {
const snapshot = readCustomOutputSnapshot({ const snapshot = readCustomOutputSnapshot({
customOutputInputs, customOutputInputs,
runtimeNodes: [nodeA, nodeB], runtimeNodes: [nodeA, nodeB],
variables: {} variableState: makeVariableState()
}); });
expect(snapshot).toEqual({ a: 'valueFromA', b: 'valueFromB' }); expect(snapshot).toEqual({ a: 'valueFromA', b: 'valueFromB' });
}); });
...@@ -168,7 +183,7 @@ describe('loopRun/service', () => { ...@@ -168,7 +183,7 @@ describe('loopRun/service', () => {
const snapshot = readCustomOutputSnapshot({ const snapshot = readCustomOutputSnapshot({
customOutputInputs, customOutputInputs,
runtimeNodes: [nodeA, nodeB], runtimeNodes: [nodeA, nodeB],
variables: {}, variableState: makeVariableState(),
finishedNodeIds: new Set(['A']) // 只有 A 跑过 finishedNodeIds: new Set(['A']) // 只有 A 跑过
}); });
expect(snapshot).toEqual({ a: 'valueFromA', b: undefined }); expect(snapshot).toEqual({ a: 'valueFromA', b: undefined });
...@@ -181,7 +196,7 @@ describe('loopRun/service', () => { ...@@ -181,7 +196,7 @@ describe('loopRun/service', () => {
const snapshot = readCustomOutputSnapshot({ const snapshot = readCustomOutputSnapshot({
customOutputInputs, customOutputInputs,
runtimeNodes: [nodeA], runtimeNodes: [nodeA],
variables: {}, variableState: makeVariableState(),
finishedNodeIds: new Set() finishedNodeIds: new Set()
}); });
expect(snapshot).toEqual({ a: undefined }); expect(snapshot).toEqual({ a: undefined });
...@@ -194,7 +209,7 @@ describe('loopRun/service', () => { ...@@ -194,7 +209,7 @@ describe('loopRun/service', () => {
const snapshot = readCustomOutputSnapshot({ const snapshot = readCustomOutputSnapshot({
customOutputInputs, customOutputInputs,
runtimeNodes: [], runtimeNodes: [],
variables: { globalKey: 'globalValue' }, variableState: makeVariableState({ globalKey: 'globalValue' }),
finishedNodeIds: new Set() finishedNodeIds: new Set()
}); });
expect(snapshot).toEqual({ g: 'globalValue' }); expect(snapshot).toEqual({ g: 'globalValue' });
...@@ -204,7 +219,7 @@ describe('loopRun/service', () => { ...@@ -204,7 +219,7 @@ describe('loopRun/service', () => {
const snapshot = readCustomOutputSnapshot({ const snapshot = readCustomOutputSnapshot({
customOutputInputs: [], customOutputInputs: [],
runtimeNodes: [], runtimeNodes: [],
variables: {} variableState: makeVariableState()
}); });
expect(snapshot).toEqual({}); expect(snapshot).toEqual({});
}); });
...@@ -219,7 +234,7 @@ describe('loopRun/service', () => { ...@@ -219,7 +234,7 @@ describe('loopRun/service', () => {
const snapshot = readCustomOutputSnapshot({ const snapshot = readCustomOutputSnapshot({
customOutputInputs, customOutputInputs,
runtimeNodes: [nodeA, nodeB], runtimeNodes: [nodeA, nodeB],
variables: {}, variableState: makeVariableState(),
finishedNodeIds: new Set(['B']), // 只有 B(循环体内)跑过 finishedNodeIds: new Set(['B']), // 只有 B(循环体内)跑过
childrenNodeIdList: ['B'] // A 在循环体外 childrenNodeIdList: ['B'] // A 在循环体外
}); });
...@@ -234,7 +249,7 @@ describe('loopRun/service', () => { ...@@ -234,7 +249,7 @@ describe('loopRun/service', () => {
const snapshot = readCustomOutputSnapshot({ const snapshot = readCustomOutputSnapshot({
customOutputInputs, customOutputInputs,
runtimeNodes: [nodeA, nodeB], runtimeNodes: [nodeA, nodeB],
variables: {}, variableState: makeVariableState(),
finishedNodeIds: new Set(['B']), finishedNodeIds: new Set(['B']),
childrenNodeIdList: ['A', 'B'] // 都在循环体内,A 本轮未跑 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 { 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 { FlowNodeInputTypeEnum } from '@fastgpt/global/core/workflow/node/constant';
import type { TUpdateListItem } from '@fastgpt/global/core/workflow/template/system/variableUpdate/type'; 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 基础设施依赖 // Logger 不走真实实现,避免 log 基础设施依赖
vi.mock('../../../../../../../../packages/service/common/logger', () => ({ vi.mock('../../../../../../../../packages/service/common/logger', () => ({
...@@ -21,6 +27,11 @@ 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 AnyProps = Parameters<typeof dispatchUpdateVariable>[0];
type BuildOpts = { type BuildOpts = {
...@@ -29,8 +40,41 @@ type BuildOpts = { ...@@ -29,8 +40,41 @@ type BuildOpts = {
isChildApp?: boolean; isChildApp?: boolean;
chatConfig?: any; chatConfig?: any;
externalWorkflowVariables?: Record<string, 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 = ( const buildProps = (
variables: Record<string, any>, variables: Record<string, any>,
updateList: TUpdateListItem[], updateList: TUpdateListItem[],
...@@ -40,7 +84,11 @@ const buildProps = ( ...@@ -40,7 +84,11 @@ const buildProps = (
return { return {
chatConfig: opts.chatConfig ?? {}, chatConfig: opts.chatConfig ?? {},
params: { updateList }, params: { updateList },
variables, variableState: createTestVariableState({
variables,
storeVariables: opts.storeVariables,
chatConfig: opts.chatConfig
}),
runtimeNodesMap, runtimeNodesMap,
workflowStreamResponse: opts.workflowStreamResponse, workflowStreamResponse: opts.workflowStreamResponse,
externalProvider: { externalWorkflowVariables: opts.externalWorkflowVariables ?? {} }, externalProvider: { externalWorkflowVariables: opts.externalWorkflowVariables ?? {} },
...@@ -50,6 +98,113 @@ const buildProps = ( ...@@ -50,6 +98,113 @@ const buildProps = (
const ref = (key: string) => [VARIABLE_NODE_ID, key] as [string, string]; 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 公式', () => { describe('dispatchUpdateVariable — Number 公式', () => {
it.each([ it.each([
['+', 10, 3, 13], ['+', 10, 3, 13],
...@@ -171,6 +326,39 @@ describe('dispatchUpdateVariable — Boolean', () => { ...@@ -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', () => { describe('dispatchUpdateVariable — Array', () => {
it('append:旧值数组', async () => { it('append:旧值数组', async () => {
const variables = { list: [1, 2] }; const variables = { list: [1, 2] };
...@@ -441,7 +629,7 @@ describe('dispatchUpdateVariable — 老数据向前兼容(无新字段)', ( ...@@ -441,7 +629,7 @@ describe('dispatchUpdateVariable — 老数据向前兼容(无新字段)', (
expect(variables.mixed).toEqual({ x: 1 }); expect(variables.mixed).toEqual({ x: 1 });
}); });
it('返回值结构:newVariables + updateVarResult 与老接口一致', async () => { it('返回值结构:仅返回 updateVarResult,变量由 variableState 统一保存', async () => {
const variables = { a: 0, b: 0 }; const variables = { a: 0, b: 0 };
const res = await dispatchUpdateVariable( const res = await dispatchUpdateVariable(
buildProps(variables, [ buildProps(variables, [
...@@ -459,8 +647,9 @@ describe('dispatchUpdateVariable — 老数据向前兼容(无新字段)', ( ...@@ -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((res as any).responseData?.updateVarResult).toEqual([1, null]);
expect(variables.a).toBe(1);
}); });
}); });
...@@ -624,4 +813,48 @@ describe('dispatchUpdateVariable — 多条 update 的顺序语义', () => { ...@@ -624,4 +813,48 @@ describe('dispatchUpdateVariable — 多条 update 的顺序语义', () => {
// 第一条:counter = 5;第二条:5 + 3 = 8 // 第一条:counter = 5;第二条:5 + 3 = 8
expect(variables.counter).toBe(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');
});
}); });
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 ({ ...@@ -141,7 +141,6 @@ export const putFileToS3 = async ({
maxSize?: number; maxSize?: number;
t: any; t: any;
}) => { }) => {
console.log(headers);
try { try {
const res = await axios.put(url, file, { const res = await axios.put(url, file, {
headers: { headers: {
......
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 ...@@ -14,7 +14,7 @@ import { type AppFileSelectConfigType } from '@fastgpt/global/core/app/type/conf
import { useSystemStore } from '@/web/common/system/useSystemStore'; import { useSystemStore } from '@/web/common/system/useSystemStore';
import { useUserStore } from '@/web/support/user/useUserStore'; import { useUserStore } from '@/web/support/user/useUserStore';
import { type OutLinkChatAuthProps } from '@fastgpt/global/support/permission/chat'; 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 { getUploadFileType } from '@fastgpt/global/core/app/constants';
import { putFileToS3 } from '@fastgpt/web/common/file/utils'; import { putFileToS3 } from '@fastgpt/web/common/file/utils';
...@@ -186,7 +186,7 @@ export const useFileUpload = (props: UseFileUploadOptions) => { ...@@ -186,7 +186,7 @@ export const useFileUpload = (props: UseFileUploadOptions) => {
const fileIndex = fileList.findIndex((item) => item.id === file.id)!; const fileIndex = fileList.findIndex((item) => item.id === file.id)!;
// Get Upload Post Presigned URL // Get Upload Post Presigned URL
const { url, key, headers, maxSize } = await getUploadChatFilePresignedUrl({ const { url, key, headers, maxSize, previewUrl } = await getUploadChatFilePresignedUrl({
filename: copyFile.rawFile.name, filename: copyFile.rawFile.name,
appId, appId,
chatId, chatId,
...@@ -209,12 +209,6 @@ export const useFileUpload = (props: UseFileUploadOptions) => { ...@@ -209,12 +209,6 @@ export const useFileUpload = (props: UseFileUploadOptions) => {
maxSize maxSize
}); });
const previewUrl = await getPresignedChatFileGetUrl({
key: key,
appId,
outLinkAuthData
});
// Update file url and key // Update file url and key
copyFile.url = previewUrl; copyFile.url = previewUrl;
copyFile.key = key; copyFile.key = key;
......
...@@ -41,7 +41,8 @@ import { ChatRoleEnum, ChatStatusEnum } from '@fastgpt/global/core/chat/constant ...@@ -41,7 +41,8 @@ import { ChatRoleEnum, ChatStatusEnum } from '@fastgpt/global/core/chat/constant
import { import {
getInteractiveByHistories, getInteractiveByHistories,
formatChatValue2InputType, formatChatValue2InputType,
rewriteHistoriesByInteractiveResponse rewriteHistoriesByInteractiveResponse,
stripChatValueFileUrls
} from './utils'; } from './utils';
import { ChatTypeEnum, textareaMinH } from './constants'; import { ChatTypeEnum, textareaMinH } from './constants';
import { SseResponseEventEnum } from '@fastgpt/global/core/workflow/runtime/constants'; import { SseResponseEventEnum } from '@fastgpt/global/core/workflow/runtime/constants';
...@@ -781,14 +782,6 @@ const ChatBox = ({ ...@@ -781,14 +782,6 @@ const ChatBox = ({
val = formatTime2YMDHMS(new Date(val)); val = formatTime2YMDHMS(new Date(val));
} else if (item.type === VariableInputEnum.timeRangeSelect && val) { } else if (item.type === VariableInputEnum.timeRangeSelect && val) {
val = val.map((item: string) => (item ? formatTime2YMDHMS(new Date(item)) : '')); 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); requestVariables[item.key] = valueTypeFormat(val, item.valueType);
}); });
...@@ -814,7 +807,6 @@ const ChatBox = ({ ...@@ -814,7 +807,6 @@ const ChatBox = ({
type: file.type, type: file.type,
name: file.name, name: file.name,
url: file.url, url: file.url,
icon: file.icon || '',
key: file.key || '' key: file.key || ''
} }
})), })),
...@@ -889,9 +881,10 @@ const ChatBox = ({ ...@@ -889,9 +881,10 @@ const ChatBox = ({
const messages = chats2GPTMessages({ const messages = chats2GPTMessages({
messages: newChatList.slice(0, -1).map((item) => { messages: newChatList.slice(0, -1).map((item) => {
if (item.obj === ChatRoleEnum.Human) { if (item.obj === ChatRoleEnum.Human) {
item.files?.forEach((file) => { return {
file.url = ''; ...item,
}); value: stripChatValueFileUrls(item.value)
};
} }
return item; 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 { ChatSiteItemType } from './type';
import { type ChatBoxInputType, type UserInputFileItemType } from './type'; import { type ChatBoxInputType, type UserInputFileItemType } from './type';
import { getFileIcon } from '@fastgpt/global/common/file/icon'; import { getFileIcon } from '@fastgpt/global/common/file/icon';
...@@ -47,6 +50,21 @@ export const formatChatValue2InputType = (value?: ChatItemValueItemType[]): Chat ...@@ -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,需要递归去找到最后一个。 // 用于判断当前对话框状态。所以,如果是 child 的 interactive,需要递归去找到最后一个。
export const getInteractiveByHistories = ( export const getInteractiveByHistories = (
chatHistories: ChatSiteItemType[] chatHistories: ChatSiteItemType[]
......
import React, { useCallback, useState } from 'react'; 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 { Box, Button, Flex, FormControl, FormErrorMessage } from '@chakra-ui/react';
import { useTranslation } from 'next-i18next'; import { useTranslation } from 'next-i18next';
import { useContextSelector } from 'use-context-selector'; import { useContextSelector } from 'use-context-selector';
...@@ -7,9 +7,6 @@ import { PluginRunContext } from '../context'; ...@@ -7,9 +7,6 @@ import { PluginRunContext } from '../context';
import Markdown from '@/components/Markdown'; import Markdown from '@/components/Markdown';
import MyIcon from '@fastgpt/web/components/common/Icon'; import MyIcon from '@fastgpt/web/components/common/Icon';
import FormLabel from '@fastgpt/web/components/common/MyBox/FormLabel'; 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 { type UserChatItemValueItemType } from '@fastgpt/global/core/chat/type';
import QuestionTip from '@fastgpt/web/components/common/MyTooltip/QuestionTip'; import QuestionTip from '@fastgpt/web/components/common/MyTooltip/QuestionTip';
import { type ChatBoxInputFormType } from '../../ChatBox/type'; import { type ChatBoxInputFormType } from '../../ChatBox/type';
...@@ -37,46 +34,13 @@ const RenderInput = () => { ...@@ -37,46 +34,13 @@ const RenderInput = () => {
const onNewChat = useContextSelector(PluginRunContext, (v) => v.onNewChat); const onNewChat = useContextSelector(PluginRunContext, (v) => v.onNewChat);
const onSubmit = useContextSelector(PluginRunContext, (v) => v.onSubmit); const onSubmit = useContextSelector(PluginRunContext, (v) => v.onSubmit);
const isChatting = useContextSelector(PluginRunContext, (v) => v.isChatting); const isChatting = useContextSelector(PluginRunContext, (v) => v.isChatting);
const fileSelectConfig = useContextSelector(PluginRunContext, (v) => v.fileSelectConfig);
const instruction = useContextSelector(PluginRunContext, (v) => v.instruction); 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 outLinkAuthData = useContextSelector(WorkflowRuntimeContext, (v) => v.outLinkAuthData);
const { llmModelList } = useSystemStore(); const { llmModelList } = useSystemStore();
const { control, handleSubmit, reset } = variablesForm; 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 // Get plugin input components
const formatPluginInputs = useMemoEnhance(() => { const formatPluginInputs = useMemoEnhance(() => {
if (histories.length === 0) return pluginInputs; if (histories.length === 0) return pluginInputs;
...@@ -103,7 +67,6 @@ const RenderInput = () => { ...@@ -103,7 +67,6 @@ const RenderInput = () => {
const onResetDefault = useCallback(() => { const onResetDefault = useCallback(() => {
reset({ reset({
files: [],
variables: formatPluginInputs.reduce( variables: formatPluginInputs.reduce(
(acc, input) => { (acc, input) => {
acc[input.key] = input.defaultValue; acc[input.key] = input.defaultValue;
...@@ -156,21 +119,14 @@ const RenderInput = () => { ...@@ -156,21 +119,14 @@ const RenderInput = () => {
return undefined; 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({ reset({
variables: historyVariables, variables: historyVariables
files: historyFileList
}); });
}, [histories, formatPluginInputs]); }, [histories, formatPluginInputs]);
const formFileUploading = useContextSelector(WorkflowRuntimeContext, (v) => v.fileUploading); const formFileUploading = useContextSelector(WorkflowRuntimeContext, (v) => v.fileUploading);
const fileUploading = formFileUploading || hasFileUploading; const fileUploading = formFileUploading;
const hasHistory = histories.length > 0; const hasHistory = histories.length > 0;
const isDisabledInput = !!hasHistory; const isDisabledInput = !!hasHistory;
...@@ -190,35 +146,6 @@ const RenderInput = () => { ...@@ -190,35 +146,6 @@ const RenderInput = () => {
<Markdown source={instruction} /> <Markdown source={instruction} />
</Box> </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 */} {/* Filed */}
{formatPluginInputs {formatPluginInputs
.filter((input) => { .filter((input) => {
......
import React, { type ReactNode, useCallback, useMemo, useRef } from 'react'; import React, { type ReactNode, useCallback, useMemo, useRef } from 'react';
import { createContext, useContextSelector } from 'use-context-selector'; import { createContext, useContextSelector } from 'use-context-selector';
import { type PluginRunBoxProps } from './type'; import { type PluginRunBoxProps } from './type';
import { import { type AIChatItemValueItemType } from '@fastgpt/global/core/chat/type';
type AIChatItemValueItemType,
type RuntimeUserPromptType
} from '@fastgpt/global/core/chat/type';
import { type FieldValues } from 'react-hook-form'; import { type FieldValues } from 'react-hook-form';
import { PluginRunBoxTabEnum } from './constants'; import { PluginRunBoxTabEnum } from './constants';
import { useToast } from '@fastgpt/web/hooks/useToast'; import { useToast } from '@fastgpt/web/hooks/useToast';
...@@ -18,8 +15,6 @@ import { chats2GPTMessages } from '@fastgpt/global/core/chat/adapt'; ...@@ -18,8 +15,6 @@ import { chats2GPTMessages } from '@fastgpt/global/core/chat/adapt';
import { clientGetWorkflowToolRunUserQuery } from '@fastgpt/global/core/workflow/utils'; import { clientGetWorkflowToolRunUserQuery } from '@fastgpt/global/core/workflow/utils';
import { ChatItemContext } from '@/web/core/chat/context/chatItemContext'; import { ChatItemContext } from '@/web/core/chat/context/chatItemContext';
import { ChatRecordContext } from '@/web/core/chat/context/chatRecordContext'; 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 { mergeChatResponseData } from '@fastgpt/global/core/chat/utils';
import { getErrText } from '@fastgpt/global/common/error/utils'; import { getErrText } from '@fastgpt/global/common/error/utils';
import { WorkflowRuntimeContextProvider } from '@/components/core/chat/ChatContainer/context/workflowRuntimeContext'; import { WorkflowRuntimeContextProvider } from '@/components/core/chat/ChatContainer/context/workflowRuntimeContext';
...@@ -28,7 +23,6 @@ type PluginRunContextType = PluginRunBoxProps & { ...@@ -28,7 +23,6 @@ type PluginRunContextType = PluginRunBoxProps & {
isChatting: boolean; isChatting: boolean;
onSubmit: (e: ChatBoxInputFormType) => Promise<any>; onSubmit: (e: ChatBoxInputFormType) => Promise<any>;
instruction: string; instruction: string;
fileSelectConfig: AppFileSelectConfigType;
}; };
export const PluginRunContext = createContext< export const PluginRunContext = createContext<
...@@ -38,8 +32,7 @@ export const PluginRunContext = createContext< ...@@ -38,8 +32,7 @@ export const PluginRunContext = createContext<
onSubmit: function (e: FieldValues): Promise<any> { onSubmit: function (e: FieldValues): Promise<any> {
throw new Error('Function not implemented.'); throw new Error('Function not implemented.');
}, },
instruction: '', instruction: ''
fileSelectConfig: defaultAppSelectFileConfig
}); });
const PluginRunContextProvider = ({ const PluginRunContextProvider = ({
...@@ -56,10 +49,7 @@ const PluginRunContextProvider = ({ ...@@ -56,10 +49,7 @@ const PluginRunContextProvider = ({
const setChatRecords = useContextSelector(ChatRecordContext, (v) => v.setChatRecords); const setChatRecords = useContextSelector(ChatRecordContext, (v) => v.setChatRecords);
const chatRecords = useContextSelector(ChatRecordContext, (v) => v.chatRecords); const chatRecords = useContextSelector(ChatRecordContext, (v) => v.chatRecords);
const { instruction = '', fileSelectConfig = defaultAppSelectFileConfig } = useMemo( const instruction = chatConfig?.instruction || '';
() => chatConfig || {},
[chatConfig]
);
const { toast } = useToast(); const { toast } = useToast();
const chatController = useRef(new AbortController()); const chatController = useRef(new AbortController());
...@@ -168,7 +158,7 @@ const PluginRunContextProvider = ({ ...@@ -168,7 +158,7 @@ const PluginRunContextProvider = ({
); );
const onSubmit = useCallback( const onSubmit = useCallback(
async ({ variables, files }: ChatBoxInputFormType) => { async ({ variables }: ChatBoxInputFormType) => {
if (!onStartChat) return; if (!onStartChat) return;
if (isChatting) { if (isChatting) {
toast({ toast({
...@@ -189,8 +179,7 @@ const PluginRunContextProvider = ({ ...@@ -189,8 +179,7 @@ const PluginRunContextProvider = ({
{ {
...clientGetWorkflowToolRunUserQuery({ ...clientGetWorkflowToolRunUserQuery({
pluginInputs, pluginInputs,
variables, variables
files: files as RuntimeUserPromptType['files']
}), }),
id: humanChatItemId, id: humanChatItemId,
dataId: humanChatItemId, dataId: humanChatItemId,
...@@ -230,10 +219,7 @@ const PluginRunContextProvider = ({ ...@@ -230,10 +219,7 @@ const PluginRunContextProvider = ({
responseChatItemId, responseChatItemId,
controller: chatController.current, controller: chatController.current,
generatingMessage, generatingMessage,
variables: { variables
files,
...variables
}
}); });
setChatRecords((state) => setChatRecords((state) =>
...@@ -286,8 +272,7 @@ const PluginRunContextProvider = ({ ...@@ -286,8 +272,7 @@ const PluginRunContextProvider = ({
...props, ...props,
isChatting, isChatting,
onSubmit, onSubmit,
instruction, instruction
fileSelectConfig
}; };
return ( return (
<WorkflowRuntimeContextProvider <WorkflowRuntimeContextProvider
......
...@@ -3,8 +3,7 @@ import type { ...@@ -3,8 +3,7 @@ import type {
GetHelperBotChatRecordsParamsType, GetHelperBotChatRecordsParamsType,
DeleteHelperBotChatParamsType, DeleteHelperBotChatParamsType,
GetHelperBotChatRecordsResponseType, GetHelperBotChatRecordsResponseType,
GetHelperBotFilePresignParamsType, GetHelperBotFilePresignParamsType
GetHelperBotFilePreviewParamsType
} from '@fastgpt/global/openapi/core/chat/helperBot/api'; } from '@fastgpt/global/openapi/core/chat/helperBot/api';
import type { CreatePostPresignedUrlResponseType } from '@fastgpt/global/common/file/s3/type'; import type { CreatePostPresignedUrlResponseType } from '@fastgpt/global/common/file/s3/type';
...@@ -16,6 +15,3 @@ export const deleteHelperBotChatRecord = (data: DeleteHelperBotChatParamsType) = ...@@ -16,6 +15,3 @@ export const deleteHelperBotChatRecord = (data: DeleteHelperBotChatParamsType) =
export const getHelperBotFilePresign = (data: GetHelperBotFilePresignParamsType) => export const getHelperBotFilePresign = (data: GetHelperBotFilePresignParamsType) =>
POST<CreatePostPresignedUrlResponseType>('/core/chat/helperBot/getFilePresign', data); 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'; ...@@ -12,11 +12,9 @@ import { type UseFieldArrayReturn } from 'react-hook-form';
import type { ChatBoxInputFormType, UserInputFileItemType } from '../../ChatContainer/ChatBox/type'; import type { ChatBoxInputFormType, UserInputFileItemType } from '../../ChatContainer/ChatBox/type';
import { type AppFileSelectConfigType } from '@fastgpt/global/core/app/type/config.schema'; import { type AppFileSelectConfigType } from '@fastgpt/global/core/app/type/config.schema';
import { useSystemStore } from '@/web/common/system/useSystemStore'; 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 { getUploadFileType } from '@fastgpt/global/core/app/constants';
import type { HelperBotTypeEnumType } from '@fastgpt/global/core/chat/helperBot/type'; 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 { useRequest } from '@fastgpt/web/hooks/useRequest';
import { putFileToS3 } from '@fastgpt/web/common/file/utils'; import { putFileToS3 } from '@fastgpt/web/common/file/utils';
...@@ -177,7 +175,7 @@ export const useFileUpload = (props: UseFileUploadOptions) => { ...@@ -177,7 +175,7 @@ export const useFileUpload = (props: UseFileUploadOptions) => {
const fileIndex = fileList.findIndex((item) => item.id === file.id)!; const fileIndex = fileList.findIndex((item) => item.id === file.id)!;
// Get Upload Post Presigned URL // Get Upload Post Presigned URL
const { url, key, headers, maxSize } = await getHelperBotFilePresign({ const { url, key, headers, maxSize, previewUrl } = await getHelperBotFilePresign({
type, type,
chatId, chatId,
filename: copyFile.rawFile.name filename: copyFile.rawFile.name
...@@ -198,10 +196,6 @@ export const useFileUpload = (props: UseFileUploadOptions) => { ...@@ -198,10 +196,6 @@ export const useFileUpload = (props: UseFileUploadOptions) => {
maxSize maxSize
}); });
const previewUrl = await getHelperBotFilePreview({
key: key
});
// Update file url and key // Update file url and key
copyFile.url = previewUrl; copyFile.url = previewUrl;
copyFile.key = key; copyFile.key = key;
......
import React, { useEffect } from 'react'; import React from 'react';
import { Box, Button, Flex, FormControl, FormErrorMessage } from '@chakra-ui/react'; import { Box, Button, Flex, FormControl, FormErrorMessage } from '@chakra-ui/react';
import { Controller, useForm, type UseFormHandleSubmit } from 'react-hook-form'; import { Controller, useForm, type UseFormHandleSubmit } from 'react-hook-form';
import Markdown from '@/components/Markdown'; import Markdown from '@/components/Markdown';
...@@ -12,10 +12,22 @@ import InputRender from '@/components/core/app/formRender'; ...@@ -12,10 +12,22 @@ import InputRender from '@/components/core/app/formRender';
import { nodeInputTypeToInputType } from '@/components/core/app/formRender/utils'; import { nodeInputTypeToInputType } from '@/components/core/app/formRender/utils';
import FormLabel from '@fastgpt/web/components/common/MyBox/FormLabel'; import FormLabel from '@fastgpt/web/components/common/MyBox/FormLabel';
import LeftRadio from '@fastgpt/web/components/common/Radio/LeftRadio'; 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 { useContextSelector } from 'use-context-selector';
import { WorkflowRuntimeContext } from '@/components/core/chat/ChatContainer/context/workflowRuntimeContext'; 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({ const DescriptionBox = React.memo(function DescriptionBox({
description description
...@@ -80,64 +92,26 @@ export const FormInputComponent = React.memo(function FormInputComponent({ ...@@ -80,64 +92,26 @@ export const FormInputComponent = React.memo(function FormInputComponent({
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
const { handleSubmit, control, watch, setValue } = useForm({ const { handleSubmit, control, watch } = useForm({
defaultValues defaultValues
}); });
const appId = useContextSelector(WorkflowRuntimeContext, (v) => v.appId); const runtimeFileUploading = useContextSelector(WorkflowRuntimeContext, (v) => v.fileUploading);
const outLinkAuthData = useContextSelector(WorkflowRuntimeContext, (v) => v.outLinkAuthData);
const formValues = watch(); 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(() => { const isFileUploading = React.useMemo(() => {
if (runtimeFileUploading) return true;
return inputForm.some((input) => { return inputForm.some((input) => {
if (input.type === 'fileSelect') { if (input.type === 'fileSelect') {
const files = formValues[input.key]; const files = formValues[input.key];
if (Array.isArray(files)) { if (Array.isArray(files)) {
return files.some((file: any) => !file.url && !file.error); return files.some(isPendingFileValue);
} }
} }
return false; return false;
}); });
}, [inputForm, formValues]); }, [inputForm, formValues, runtimeFileUploading]);
return ( return (
<Box> <Box>
......
...@@ -11,7 +11,7 @@ import { getErrText } from '@fastgpt/global/common/error/utils'; ...@@ -11,7 +11,7 @@ import { getErrText } from '@fastgpt/global/common/error/utils';
import { type UseFieldArrayReturn } from 'react-hook-form'; import { type UseFieldArrayReturn } from 'react-hook-form';
import { useSystemStore } from '@/web/common/system/useSystemStore'; import { useSystemStore } from '@/web/common/system/useSystemStore';
import { useUserStore } from '@/web/support/user/useUserStore'; 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 { putFileToS3 } from '@fastgpt/web/common/file/utils';
import type { PreviewInputFormType, UserInputFileItemType } from './type'; import type { PreviewInputFormType, UserInputFileItemType } from './type';
...@@ -128,6 +128,7 @@ export const usePreviewFileUpload = ({ fileCtrl, appId, chatId }: UsePreviewFile ...@@ -128,6 +128,7 @@ export const usePreviewFileUpload = ({ fileCtrl, appId, chatId }: UsePreviewFile
url, url,
key, key,
headers, headers,
previewUrl,
maxSize: uploadMaxSize maxSize: uploadMaxSize
} = await getUploadChatFilePresignedUrl({ } = await getUploadChatFilePresignedUrl({
filename: copyFile.rawFile.name, filename: copyFile.rawFile.name,
...@@ -154,12 +155,6 @@ export const usePreviewFileUpload = ({ fileCtrl, appId, chatId }: UsePreviewFile ...@@ -154,12 +155,6 @@ export const usePreviewFileUpload = ({ fileCtrl, appId, chatId }: UsePreviewFile
maxSize: uploadMaxSize maxSize: uploadMaxSize
}); });
// TODO: 替换为 skill 运行预览专用的文件预览 API
const previewUrl = await getPresignedChatFileGetUrl({
key,
appId,
outLinkAuthData: undefined
});
copyFile.url = previewUrl; copyFile.url = previewUrl;
copyFile.key = key; copyFile.key = key;
updateFiles(fileIndex, copyFile); 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 { NextAPI } from '@/service/middleware/entry';
import type { GetHelperBotFilePresignParamsType } from '@fastgpt/global/openapi/core/chat/helperBot/api'; import type { GetHelperBotFilePresignParamsType } from '@fastgpt/global/openapi/core/chat/helperBot/api';
import type { CreatePostPresignedUrlResponseType } from '@fastgpt/global/common/file/s3/type'; import type { CreatePostPresignedUrlResponseType } from '@fastgpt/global/common/file/s3/type';
...@@ -23,8 +23,7 @@ const authUploadLimit = (tmbId: string) => { ...@@ -23,8 +23,7 @@ const authUploadLimit = (tmbId: string) => {
}; };
async function handler( async function handler(
req: ApiRequestProps<getFilePresignBody, getFilePresignQuery>, req: ApiRequestProps<getFilePresignBody, getFilePresignQuery>
res: ApiResponseType<any>
): Promise<getFilePresignResponse> { ): Promise<getFilePresignResponse> {
const { type, chatId, filename } = req.body; const { type, chatId, filename } = req.body;
...@@ -37,14 +36,12 @@ async function handler( ...@@ -37,14 +36,12 @@ async function handler(
await authUploadLimit(userId); await authUploadLimit(userId);
const data = await getS3HelperBotSource().createUploadFileURL({ return await getS3HelperBotSource().createUploadFileURL({
type, type,
chatId, chatId,
userId, userId,
filename filename
}); });
return data;
} }
export default NextAPI(handler); 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 { NextAPI } from '@/service/middleware/entry';
import { import {
GetHelperBotChatRecordsParamsSchema, GetHelperBotChatRecordsParamsSchema,
...@@ -8,6 +8,8 @@ import { ...@@ -8,6 +8,8 @@ import {
import { authHelperBotChatCrud } from '@/service/support/permission/auth/chat'; import { authHelperBotChatCrud } from '@/service/support/permission/auth/chat';
import { MongoHelperBotChatItem } from '../../../../../../../../packages/service/core/chat/HelperBot/chatItemSchema'; import { MongoHelperBotChatItem } from '../../../../../../../../packages/service/core/chat/HelperBot/chatItemSchema';
import { parsePaginationRequest } from '@fastgpt/service/common/api/pagination'; 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; export type getRecordsQuery = GetHelperBotChatRecordsParamsType;
...@@ -16,8 +18,7 @@ export type getRecordsBody = {}; ...@@ -16,8 +18,7 @@ export type getRecordsBody = {};
export type getRecordsResponse = GetHelperBotChatRecordsResponseType; export type getRecordsResponse = GetHelperBotChatRecordsResponseType;
async function handler( async function handler(
req: ApiRequestProps<getRecordsBody, getRecordsQuery>, req: ApiRequestProps<getRecordsBody, getRecordsQuery>
res: ApiResponseType<any>
): Promise<getRecordsResponse> { ): Promise<getRecordsResponse> {
const { type, chatId } = GetHelperBotChatRecordsParamsSchema.parse(req.query); const { type, chatId } = GetHelperBotChatRecordsParamsSchema.parse(req.query);
const { userId } = await authHelperBotChatCrud({ const { userId } = await authHelperBotChatCrud({
...@@ -34,6 +35,7 @@ async function handler( ...@@ -34,6 +35,7 @@ async function handler(
MongoHelperBotChatItem.countDocuments({ userId, chatId }) MongoHelperBotChatItem.countDocuments({ userId, chatId })
]); ]);
histories.reverse(); histories.reverse();
await addPreviewUrlToChatItems(histories as unknown as ChatItemMiniType[], 'chatFlow');
return { return {
total, total,
......
...@@ -45,6 +45,14 @@ async function handler(req: NextApiRequest, res: NextApiResponse): Promise<InitC ...@@ -45,6 +45,14 @@ async function handler(req: NextApiRequest, res: NextApiResponse): Promise<InitC
// get app and history // get app and history
const { nodes, chatConfig } = await getAppLatestVersion(app._id, app); 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 = const pluginInputs =
chat?.pluginInputs ?? chat?.pluginInputs ??
nodes?.find((node) => node.flowNodeType === FlowNodeTypeEnum.pluginInput)?.inputs ?? nodes?.find((node) => node.flowNodeType === FlowNodeTypeEnum.pluginInput)?.inputs ??
...@@ -52,7 +60,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse): Promise<InitC ...@@ -52,7 +60,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse): Promise<InitC
const variables = await presignVariablesFileUrls({ const variables = await presignVariablesFileUrls({
variables: chat?.variables, variables: chat?.variables,
variableConfig: chat?.variableList variableConfig: appChatConfig.variables
}); });
return { return {
...@@ -64,13 +72,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse): Promise<InitC ...@@ -64,13 +72,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse): Promise<InitC
chatGenerateStatus: chat?.chatGenerateStatus, chatGenerateStatus: chat?.chatGenerateStatus,
hasBeenRead: chat?.hasBeenRead, hasBeenRead: chat?.hasBeenRead,
app: { app: {
chatConfig: getAppChatConfig({ chatConfig: appChatConfig,
chatConfig,
systemConfigNode: getGuideModule(nodes),
storeVariables: chat?.variableList,
storeWelcomeText: chat?.welcomeText,
isPublicFetch: false
}),
chatModels: getChatModelNameListByModules(nodes), chatModels: getChatModelNameListByModules(nodes),
name: app.name, name: app.name,
avatar: app.avatar, avatar: app.avatar,
......
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